text:
require_relative '../pegasus/src/env'
require 'cdo/solr'
require src_dir 'database'

# Generates a list of teachers based on these filters:
# Petition parents, software engineers, none of the above - US ONLY
# Volunteer engineer list - US ONLY
# HocSignup2014- US ONLY
# CSEdWeekEvent2013- US ONLY

SOLR = Solr::Server.new(host:'ec2-54-83-22-254.compute-1.amazonaws.com')

def export_contacts_to_csv(contacts, path)
  columns = nil

  CSV.open(path, 'wb') do |results|
    contacts.values.each do |contact|
      unless columns
        columns = contact.keys
        results << columns
      end
      results << columns.map{|column| contact[column]}
    end
  end
end

def query_contacts(params)
  fields = params[:fields] if params[:fields]

  [].tap do |results|
    SOLR.query(params.merge(rows:10000)).each do |i|
      i = yield(i) if block_given?
      results << {email:i['email_s'].downcase.strip, name:i['name_s']}.merge(i.slice(*fields)) if i
    end
  end
end

UNSUBSCRIBERS = {}.tap do |results|
  DB[:contacts].where('unsubscribed_at IS NOT NULL').each do |i|
    email = i[:email].downcase.strip
    results[email] = true
  end
end
puts "#{UNSUBSCRIBERS.count} unsubscribers loaded."

TEACHERS = {}.tap do |results|
  (
  query_contacts(q:'kind_s:"Petition" && create_ip_country_s:"United States"', fq:'-role_s:"student" && -role_s:"educator" && -role_s:"district_admin" && -role_s:"principal" && -role_s:"superintendent" && -role_s:"teacher"') +
      query_contacts(q:'kind_s:"VolunteerEngineerSubmission" && create_ip_country_s:"United States"') +
      query_contacts(q:'kind_s:"HocSignup2014" && create_ip_country_s:"United States"') +
      query_contacts(q:'kind_s:"CSEdWeekEvent2013" && create_ip_country_s:"United States"')
  ).each do |i|
    email = i[:email].downcase.strip
    results[email] = i unless UNSUBSCRIBERS[email]
  end
end
puts "#{TEACHERS.count} teachers loaded."

export_contacts_to_csv TEACHERS, "us-teachers.csv"


text:
package org.apache.hadoop.fs.azurebfs;

import java.util.HashMap;
import java.util.Map;

import org.apache.hadoop.fs.StorageStatistics.CommonStatisticNames;
import org.apache.hadoop.fs.azurebfs.constants.AbfsHttpConstants;
import org.apache.hadoop.fs.statistics.StoreStatisticNames;

/**
 * Statistic which are collected in Abfs.
 * Available as metrics in {@link AbfsCountersImpl}.
 */
public enum AbfsStatistic {

  CALL_CREATE(CommonStatisticNames.OP_CREATE,
      "Calls of create()."),
  CALL_OPEN(CommonStatisticNames.OP_OPEN,
      "Calls of open()."),
  CALL_GET_FILE_STATUS(CommonStatisticNames.OP_GET_FILE_STATUS,
      "Calls of getFileStatus()."),
  CALL_APPEND(CommonStatisticNames.OP_APPEND,
      "Calls of append()."),
  CALL_CREATE_NON_RECURSIVE(CommonStatisticNames.OP_CREATE_NON_RECURSIVE,
      "Calls of createNonRecursive()."),
  CALL_DELETE(CommonStatisticNames.OP_DELETE,
      "Calls of delete()."),
  CALL_EXIST(CommonStatisticNames.OP_EXISTS,
      "Calls of exist()."),
  CALL_GET_DELEGATION_TOKEN(CommonStatisticNames.OP_GET_DELEGATION_TOKEN,
      "Calls of getDelegationToken()."),
  CALL_LIST_STATUS(CommonStatisticNames.OP_LIST_STATUS,
      "Calls of listStatus()."),
  CALL_MKDIRS(CommonStatisticNames.OP_MKDIRS,
      "Calls of mkdirs()."),
  CALL_RENAME(CommonStatisticNames.OP_RENAME,
      "Calls of rename()."),
  DIRECTORIES_CREATED("directories_created",
      "Total number of directories created through the object store."),
  DIRECTORIES_DELETED("directories_deleted",
      "Total number of directories deleted through the object store."),
  FILES_CREATED("files_created",
      "Total number of files created through the object store."),
  FILES_DELETED("files_deleted",
      "Total number of files deleted from the object store."),
  ERROR_IGNORED("error_ignored",
      "Errors caught and ignored."),

  //Network statistics.
  CONNECTIONS_MADE("connections_made",
      "Total number of times a connection was made with the data store."),
  SEND_REQUESTS("send_requests",
      "Total number of times http requests were sent to the data store."),
  GET_RESPONSES("get_responses",
      "Total number of times a response was received."),
  BYTES_SENT("bytes_sent",
      "Total bytes uploaded."),
  BYTES_RECEIVED("bytes_received",
      "Total bytes received."),
  READ_THROTTLES("read_throttles",
      "Total number of times a read operation is throttled."),
  WRITE_THROTTLES("write_throttles",
      "Total number of times a write operation is throttled."),
  SERVER_UNAVAILABLE("server_unavailable",
      "Total number of times HTTP 503 status code is received in response."),

  // HTTP Duration Trackers
  HTTP_HEAD_REQUEST(StoreStatisticNames.ACTION_HTTP_HEAD_REQUEST,
      "Time taken to complete a HEAD request",
      AbfsHttpConstants.HTTP_METHOD_HEAD),
  HTTP_GET_REQUEST(StoreStatisticNames.ACTION_HTTP_GET_REQUEST,
      "Time taken to complete a GET request",
      AbfsHttpConstants.HTTP_METHOD_GET),
  HTTP_DELETE_REQUEST(StoreStatisticNames.ACTION_HTTP_DELETE_REQUEST,
      "Time taken to complete a DELETE request",
      AbfsHttpConstants.HTTP_METHOD_DELETE),
  HTTP_PUT_REQUEST(StoreStatisticNames.ACTION_HTTP_PUT_REQUEST,
      "Time taken to complete a PUT request",
      AbfsHttpConstants.HTTP_METHOD_PUT),
  HTTP_PATCH_REQUEST(StoreStatisticNames.ACTION_HTTP_PATCH_REQUEST,
      "Time taken to complete a PATCH request",
      AbfsHttpConstants.HTTP_METHOD_PATCH),
  HTTP_POST_REQUEST(StoreStatisticNames.ACTION_HTTP_POST_REQUEST,
      "Time taken to complete a POST request",
      AbfsHttpConstants.HTTP_METHOD_POST);

  private String statName;
  private String statDescription;

  //For http call stats only.
  private String httpCall;
  private static final Map<String, String> HTTP_CALL_TO_NAME_MAP = new HashMap<>();

  static {
    for (AbfsStatistic statistic : values()) {
      if (statistic.getHttpCall() != null) {
        HTTP_CALL_TO_NAME_MAP.put(statistic.getHttpCall(), statistic.getStatName());
      }
    }
  }

  /**
   * Constructor of AbfsStatistic to set statistic name and description.
   *
   * @param statName        Name of the statistic.
   * @param statDescription Description of the statistic.
   */
  AbfsStatistic(String statName, String statDescription) {
    this.statName = statName;
    this.statDescription = statDescription;
  }

  /**
   * Constructor for AbfsStatistic for HTTP durationTrackers.
   *
   * @param statName        Name of the statistic.
   * @param statDescription Description of the statistic.
   * @param httpCall        HTTP call associated with the stat name.
   */
  AbfsStatistic(String statName, String statDescription, String httpCall) {
    this.statName = statName;
    this.statDescription = statDescription;
    this.httpCall = httpCall;
  }

  /**
   * Getter for statistic name.
   *
   * @return Name of statistic.
   */
  public String getStatName() {
    return statName;
  }

  /**
   * Getter for statistic description.
   *
   * @return Description of statistic.
   */
  public String getStatDescription() {
    return statDescription;
  }

  /**
   * Getter for http call for HTTP duration trackers.
   *
   * @return http call of a statistic.
   */
  public String getHttpCall() {
    return httpCall;
  }

  /**
   * Get the statistic name using the http call name.
   *
   * @param httpCall The HTTP call used to get the statistic name.
   * @return Statistic name.
   */
  public static String getStatNameFromHttpCall(String httpCall) {
    return HTTP_CALL_TO_NAME_MAP.get(httpCall);
  }
}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import absolute_import

import os
import sys
import json
from distutils import log

import sentry

JS_SDK_REGISTRY_URL = (
    "https://release-registry.services.sentry.io/sdks/sentry.javascript.browser/versions"
)
LOADER_FOLDER = os.path.abspath(os.path.join(os.path.dirname(sentry.__file__), "loader"))

# We cannot leverage six here, so we need to vendor
# bits that we need.
if sys.version_info[0] == 3:

    def iteritems(d, **kw):
        return iter(d.items(**kw))

    from urllib.request import urlopen

else:

    def iteritems(d, **kw):
        return d.iteritems(**kw)  # NOQA

    from urllib2 import urlopen

def dump_registry(path, data):
    fn = os.path.join(LOADER_FOLDER, path + ".json")
    directory = os.path.dirname(fn)
    try:
        os.makedirs(directory)
    except OSError:
        pass
    with open(fn, "wb") as f:
        json.dump(data, f, indent=2)
        f.write("\n")

def sync_registry():
    body = urlopen(JS_SDK_REGISTRY_URL).read().decode("utf-8")
    data = json.loads(body)
    dump_registry("_registry", data)

from .base import BaseBuildCommand

class BuildJsSdkRegistryCommand(BaseBuildCommand):
    description = "build js sdk registry"

    def run(self):
        log.info("downloading js sdk information from the release registry")
        try:
            sync_registry()
        except BaseException:
            log.error("error ocurred while trying to fetch js sdk information from the registry")


text:
cask :v1 => 'pixelapse' do
  version '2.0.0'
  sha256 '6822de800b29b02f7ff6f94ef28bbbb3c38aef05fad0cf6c5cb293623227547c'

  url "https://s3.amazonaws.com/download-pixelapse/Pixelapse%20#{version}.dmg"
  homepage 'https://www.pixelapse.com'
  license :unknown    # todo: improve this machine-generated value

  app 'Pixelapse.app'
end


text:
'use strict';

const canvas = document.querySelector("canvas");
const context = canvas.getContext("2d");
const margin = {top: 20, right: 20, bottom: 30, left: 50};
const width = canvas.width - margin.left - margin.right;
const height = canvas.height - margin.top - margin.bottom;

const x = d3.scaleTime()
    .range([0, width]);

const y = d3.scaleLinear()
    .range([height, 0]);

const line = d3.line()
    .x(d => x(d.date))
    .y(d => y(d.value))
    //.curve(d3.curveCardinal.tension(0.5))
    //.curve(d3.curveStep)
    .context(context);

context.translate(margin.left, margin.top);

function prepareRow(row) {
  const newRow = {};
  const date = row.endDate.split('/').reverse().join('-');
  newRow.date = +(new Date(`${date}T${row.endTime}`));
  newRow.value = +(row.NO2 || 0);
  return newRow;
}

function prepareData(res) {
  const parsedRes = d3.csvParse(res)
  return parsedRes.map(prepareRow);
}

function drawLine(data) {
  context.clearRect(0, 0, canvas.width, canvas.height);

  context.beginPath();
  line(data);
  context.lineWidth = 1;
  context.strokeStyle = "steelblue";
  context.stroke();
}

//fetch('./data/nitrogen-dioxide-2016-09-01-161001120009.csv')
fetch('./data/nitrogen-dioxide-oct-2015-2016.csv')
//fetch('./data/test.csv')
  .then((res) => res.text())
  .then((res) => {
    const data = prepareData(res);

    x.domain(d3.extent(data, d => d.date));
    y.domain([-50, d3.max(data, d => d.value) + 50]);

    drawLine(data);

    setTimeout(function () {
      const interpolatorScale = d3.scaleLinear().range([0, 1]).domain([0, 2000]);
      const startValues = data.map(d => d.value);
      const endValues = data.map(d => d.value * (Math.random() + 0.6));
      const valuesInterpolator = d3.interpolateArray(startValues, endValues);

      var t = d3.interval(function(elapsed) {
        const step = interpolatorScale(elapsed);
        const interpolatodValues = valuesInterpolator(step);
        const interpolatedData = data.map((d, idx) => {
          const newObj = {
            date: d.date,
          };
          newObj.value = interpolatodValues[idx];
          return newObj;
        });
        drawLine(interpolatedData);
        if (elapsed > 2000) t.stop();
      }, 30);
    }, 2000);
  });


text:
package com.hkm.disqus.api.gson;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.hkm.disqus.api.model.blacklists.Entry;
import com.hkm.disqus.api.model.users.User;

import java.io.IOException;

/**
 * A {@link TypeAdapterFactory} to handle different {@link Entry} responses
 */
public class BlacklistsEntryTypeAdapterFactory implements TypeAdapterFactory {

    @Override
    public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) {
        // Return null if not a blacklist entry object
        if (!type.getType().equals(Entry.class)) {
            return null;
        }

        // Get delegate
        final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);

        // Return adapter
        return new TypeAdapter<T>() {

            @Override
            public void write(JsonWriter out, T value) throws IOException {
                delegate.write(out, value);
            }

            @Override
            public T read(JsonReader in) throws IOException {
                JsonElement jsonTree = gson.fromJson(in, JsonElement.class);
                JsonElement value = jsonTree.getAsJsonObject().get("value");

                // Process the entry with the delegate
                T entry = delegate.fromJsonTree(jsonTree);

                // Process value if needed
                if (value.isJsonObject()) {
                    ((Entry) entry).value = gson.fromJson(value, User.class);
                }

                // Return entry
                return entry;
            }

        };
    }

}


text:
package xdsclient_test

import (
	"testing"

	"google.golang.org/grpc/internal/grpctest"
	_ "google.golang.org/grpc/xds/internal/xdsclient/controller/version/v2" // Register the v2 API client.
)

type s struct {
	grpctest.Tester
}

func Test(t *testing.T) {
	grpctest.RunSubTests(t, s{})
}


text:
package org.springframework.http.client.reactive;

import java.util.Collection;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiFunction;

import io.netty.buffer.ByteBufAllocator;
import io.netty.handler.codec.http.cookie.Cookie;
import io.netty.handler.codec.http.cookie.DefaultCookie;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import reactor.core.publisher.Flux;
import reactor.netty.ChannelOperationsId;
import reactor.netty.Connection;
import reactor.netty.NettyInbound;
import reactor.netty.http.client.HttpClientResponse;

import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseCookie;
import org.springframework.lang.Nullable;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;

/**
 * {@link ClientHttpResponse} implementation for the Reactor-Netty HTTP client.
 *
 * @author Brian Clozel
 * @author Rossen Stoyanchev
 * @since 5.0
 * @see reactor.netty.http.client.HttpClient
 */
class ReactorClientHttpResponse implements ClientHttpResponse {

	private static final Log logger = LogFactory.getLog(ReactorClientHttpResponse.class);

	private final HttpClientResponse response;

	private final HttpHeaders headers;

	private final NettyInbound inbound;

	private final NettyDataBufferFactory bufferFactory;

	// 0 - not subscribed, 1 - subscribed, 2 - cancelled via connector (before subscribe)
	private final AtomicInteger state = new AtomicInteger();

	/**
	 * Constructor that matches the inputs from
	 * {@link reactor.netty.http.client.HttpClient.ResponseReceiver#responseConnection(BiFunction)}.
	 * @since 5.2.8
	 */
	public ReactorClientHttpResponse(HttpClientResponse response, Connection connection) {
		this.response = response;
		MultiValueMap<String, String> adapter = new NettyHeadersAdapter(response.responseHeaders());
		this.headers = HttpHeaders.readOnlyHttpHeaders(adapter);
		this.inbound = connection.inbound();
		this.bufferFactory = new NettyDataBufferFactory(connection.outbound().alloc());
	}

	/**
	 * Constructor with inputs extracted from a {@link Connection}.
	 * @deprecated as of 5.2.8, in favor of {@link #ReactorClientHttpResponse(HttpClientResponse, Connection)}
	 */
	@Deprecated
	public ReactorClientHttpResponse(HttpClientResponse response, NettyInbound inbound, ByteBufAllocator alloc) {
		this.response = response;
		MultiValueMap<String, String> adapter = new NettyHeadersAdapter(response.responseHeaders());
		this.headers = HttpHeaders.readOnlyHttpHeaders(adapter);
		this.inbound = inbound;
		this.bufferFactory = new NettyDataBufferFactory(alloc);
	}

	@Override
	public String getId() {
		String id = null;
		if (this.response instanceof ChannelOperationsId operationsId) {
			id = (logger.isDebugEnabled() ? operationsId.asLongText() : operationsId.asShortText());
		}
		if (id == null && this.response instanceof Connection connection) {
			id = connection.channel().id().asShortText();
		}
		return (id != null ? id : ObjectUtils.getIdentityHexString(this));
	}

	@Override
	public Flux<DataBuffer> getBody() {
		return this.inbound.receive()
				.doOnSubscribe(s -> {
					if (this.state.compareAndSet(0, 1)) {
						return;
					}
					if (this.state.get() == 2) {
						throw new IllegalStateException(
								"The client response body has been released already due to cancellation.");
					}
				})
				.map(byteBuf -> {
					byteBuf.retain();
					return this.bufferFactory.wrap(byteBuf);
				});
	}

	@Override
	public HttpHeaders getHeaders() {
		return this.headers;
	}

	@Override
	public HttpStatusCode getStatusCode() {
		return HttpStatusCode.valueOf(this.response.status().code());
	}

	@Override
	public MultiValueMap<String, ResponseCookie> getCookies() {
		MultiValueMap<String, ResponseCookie> result = new LinkedMultiValueMap<>();
		this.response.cookies().values().stream()
				.flatMap(Collection::stream)
				.forEach(cookie -> result.add(cookie.name(),
						ResponseCookie.fromClientResponse(cookie.name(), cookie.value())
								.domain(cookie.domain())
								.path(cookie.path())
								.maxAge(cookie.maxAge())
								.secure(cookie.isSecure())
								.httpOnly(cookie.isHttpOnly())
								.sameSite(getSameSite(cookie))
								.build()));
		return CollectionUtils.unmodifiableMultiValueMap(result);
	}

	@Nullable
	private static String getSameSite(Cookie cookie) {
		if (cookie instanceof DefaultCookie defaultCookie) {
			if (defaultCookie.sameSite() != null) {
				return defaultCookie.sameSite().name();
			}
		}
		return null;
	}

	/**
	 * Called by {@link ReactorClientHttpConnector} when a cancellation is detected
	 * but the content has not been subscribed to. If the subscription never
	 * materializes then the content will remain not drained. Or it could still
	 * materialize if the cancellation happened very early, or the response
	 * reading was delayed for some reason.
	 */
	void releaseAfterCancel(HttpMethod method) {
		if (mayHaveBody(method) && this.state.compareAndSet(0, 2)) {
			if (logger.isDebugEnabled()) {
				logger.debug("[" + getId() + "]" + "Releasing body, not yet subscribed.");
			}
			this.inbound.receive().doOnNext(byteBuf -> {}).subscribe(byteBuf -> {}, ex -> {});
		}
	}

	private boolean mayHaveBody(HttpMethod method) {
		int code = getStatusCode().value();
		return !((code >= 100 && code < 200) || code == 204 || code == 205 ||
				method.equals(HttpMethod.HEAD) || getHeaders().getContentLength() == 0);
	}

	@Override
	public String toString() {
		return "ReactorClientHttpResponse{" +
				"request=[" + this.response.method().name() + " " + this.response.uri() + "]," +
				"status=" + getStatusCode() + '}';
	}

}


text:
package com.aranya.kayacms.controller.admin.webpagetemplate;

import java.time.Instant;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@EqualsAndHashCode
@ToString
public class WebPageTemplateResponse {

  private Long webPageTemplateId;

  private String name;

  private String content;

  private String nameEdits;

  private String contentEdits;

  private Instant createDate;

  private Instant modifyDate;

  private Instant publishDate;

  private boolean edited;
}


text: module Extensions::Conditional; end


text:
using System;
using System.Runtime.InteropServices;

internal static partial class Interop
{
    internal static partial class Http
    {
        [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyCreate")]
        public static extern SafeCurlHandle EasyCreate();

        [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyDestroy")]
        private static extern void EasyDestroy(IntPtr handle);

        [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasySetOptionString", CharSet = CharSet.Ansi)]
        public static extern CURLcode EasySetOptionString(SafeCurlHandle curl, CURLoption option, string value);

        [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasySetOptionLong")]
        public static extern CURLcode EasySetOptionLong(SafeCurlHandle curl, CURLoption option, long value);

        [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasySetOptionPointer")]
        public static extern CURLcode EasySetOptionPointer(SafeCurlHandle curl, CURLoption option, IntPtr value);

        [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasySetOptionPointer")]
        public static extern CURLcode EasySetOptionPointer(SafeCurlHandle curl, CURLoption option, SafeHandle value);

        [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyGetErrorString")]
        public static extern IntPtr EasyGetErrorString(int code);

        [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyGetInfoPointer")]
        public static extern CURLcode EasyGetInfoPointer(IntPtr handle, CURLINFO info, out IntPtr value);

        [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyGetInfoLong")]
        public static extern CURLcode EasyGetInfoLong(SafeCurlHandle handle, CURLINFO info, out long value);

        [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyPerform")]
        public static extern CURLcode EasyPerform(SafeCurlHandle curl);

        [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyUnpause")]
        public static extern CURLcode EasyUnpause(SafeCurlHandle easy);

        public delegate CurlSeekResult SeekCallback(IntPtr userPointer, long offset, int origin);

        public delegate ulong ReadWriteCallback(IntPtr buffer, ulong bufferSize, ulong nitems, IntPtr userPointer);

        public delegate CURLcode SslCtxCallback(IntPtr curl, IntPtr sslCtx, IntPtr userPointer);

        [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_RegisterSeekCallback")]
        public static extern void RegisterSeekCallback(
            SafeCurlHandle curl,
            SeekCallback callback,
            IntPtr userPointer,
            ref SafeCallbackHandle callbackHandle);

        [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_RegisterReadWriteCallback")]
        public static extern void RegisterReadWriteCallback(
            SafeCurlHandle curl,
            ReadWriteFunction functionType,
            ReadWriteCallback callback,
            IntPtr userPointer,
            ref SafeCallbackHandle callbackHandle);

        [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_RegisterSslCtxCallback")]
        public static extern CURLcode RegisterSslCtxCallback(
            SafeCurlHandle curl,
            SslCtxCallback callback,
            IntPtr userPointer,
            ref SafeCallbackHandle callbackHandle);

        [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_FreeCallbackHandle")]
        private static extern void FreeCallbackHandle(IntPtr handle);

        // Curl options are of the format <type base> + <n>
        private const int CurlOptionLongBase = 0;
        private const int CurlOptionObjectPointBase = 10000;

        // Enum for constants defined for the enum CURLoption in curl.h
        internal enum CURLoption
        {
            CURLOPT_INFILESIZE = CurlOptionLongBase + 14,
            CURLOPT_VERBOSE = CurlOptionLongBase + 41,
            CURLOPT_NOBODY = CurlOptionLongBase + 44,
            CURLOPT_UPLOAD = CurlOptionLongBase + 46,
            CURLOPT_POST = CurlOptionLongBase + 47,
            CURLOPT_FOLLOWLOCATION = CurlOptionLongBase + 52,
            CURLOPT_PROXYPORT = CurlOptionLongBase + 59,
            CURLOPT_POSTFIELDSIZE = CurlOptionLongBase + 60,
            CURLOPT_MAXREDIRS = CurlOptionLongBase + 68,
            CURLOPT_HTTP_VERSION = CurlOptionLongBase + 84,
            CURLOPT_NOSIGNAL = CurlOptionLongBase + 99,
            CURLOPT_PROXYTYPE = CurlOptionLongBase + 101,
            CURLOPT_HTTPAUTH = CurlOptionLongBase + 107,
            CURLOPT_PROTOCOLS = CurlOptionLongBase + 181,
            CURLOPT_REDIR_PROTOCOLS = CurlOptionLongBase + 182,

            CURLOPT_URL = CurlOptionObjectPointBase + 2,
            CURLOPT_PROXY = CurlOptionObjectPointBase + 4,
            CURLOPT_PROXYUSERPWD = CurlOptionObjectPointBase + 6,
            CURLOPT_COOKIE = CurlOptionObjectPointBase + 22,
            CURLOPT_HTTPHEADER = CurlOptionObjectPointBase + 23,
            CURLOPT_CUSTOMREQUEST = CurlOptionObjectPointBase + 36,
            CURLOPT_ACCEPT_ENCODING = CurlOptionObjectPointBase + 102,
            CURLOPT_PRIVATE = CurlOptionObjectPointBase + 103,
            CURLOPT_COPYPOSTFIELDS = CurlOptionObjectPointBase + 165,
            CURLOPT_USERNAME = CurlOptionObjectPointBase + 173,
            CURLOPT_PASSWORD = CurlOptionObjectPointBase + 174,
        }

        internal enum ReadWriteFunction
        {
            Write = 0,
            Read = 1,
            Header = 2,
        }

        // Curl info are of the format <type base> + <n>
        private const int CurlInfoStringBase = 0x100000;
        private const int CurlInfoLongBase = 0x200000;

        // Enum for constants defined for CURL_HTTP_VERSION
        internal enum CurlHttpVersion
        {
            CURL_HTTP_VERSION_NONE = 0,
            CURL_HTTP_VERSION_1_0 = 1,
            CURL_HTTP_VERSION_1_1 = 2,
            CURL_HTTP_VERSION_2_0 = 3,
        };

        // Enum for constants defined for the enum CURLINFO in curl.h
        internal enum CURLINFO
        {
            CURLINFO_PRIVATE = CurlInfoStringBase + 21,
            CURLINFO_HTTPAUTH_AVAIL = CurlInfoLongBase + 23,
        }

        // AUTH related constants
        [Flags]
        internal enum CURLAUTH
        {
            None = 0,
            Basic = 1 << 0,
            Digest = 1 << 1,
            Negotiate = 1 << 2,
        }

        // Enum for constants defined for the enum curl_proxytype in curl.h
        internal enum curl_proxytype
        {
            CURLPROXY_HTTP = 0,
        }

        [Flags]
        internal enum CurlProtocols
        {
            CURLPROTO_HTTP = (1 << 0),
            CURLPROTO_HTTPS = (1 << 1),
        }

        // Enum for constants defined for the results of CURL_SEEKFUNCTION
        internal enum CurlSeekResult : int
        {
            CURL_SEEKFUNC_OK = 0,
            CURL_SEEKFUNC_FAIL = 1,
            CURL_SEEKFUNC_CANTSEEK = 2,
        }

        // constants defined for the results of a CURL_READ or CURL_WRITE function
        internal const ulong CURL_READFUNC_ABORT = 0x10000000;
        internal const ulong CURL_READFUNC_PAUSE = 0x10000001;
        internal const ulong CURL_WRITEFUNC_PAUSE = 0x10000001;

        internal sealed class SafeCurlHandle : SafeHandle
        {
            public SafeCurlHandle() : base(IntPtr.Zero, true)
            {
            }

            public override bool IsInvalid
            {
                get { return handle == IntPtr.Zero; }
            }

            protected override bool ReleaseHandle()
            {
                EasyDestroy(handle);
                SetHandle(IntPtr.Zero);
                return true;
            }
        }

        internal sealed class SafeCallbackHandle : SafeHandle
        {
            public SafeCallbackHandle()
                : base(IntPtr.Zero, true)
            {
            }

            public override bool IsInvalid
            {
                get { return handle == IntPtr.Zero; }
            }

            protected override bool ReleaseHandle()
            {
                FreeCallbackHandle(handle);
                SetHandle(IntPtr.Zero);
                return true;
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using Azure.Core;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.SecurityInsights;

namespace Azure.ResourceManager.SecurityInsights.Models
{
    /// <summary> Represents a security group entity. </summary>
    public partial class SecurityGroupEntity : EntityData
    {
        /// <summary> Initializes a new instance of SecurityGroupEntity. </summary>
        public SecurityGroupEntity()
        {
            AdditionalData = new ChangeTrackingDictionary<string, BinaryData>();
            Kind = EntityKind.SecurityGroup;
        }

        /// <summary> Initializes a new instance of SecurityGroupEntity. </summary>
        /// <param name="id"> The id. </param>
        /// <param name="name"> The name. </param>
        /// <param name="resourceType"> The resourceType. </param>
        /// <param name="systemData"> The systemData. </param>
        /// <param name="kind"> The kind of the entity. </param>
        /// <param name="additionalData"> A bag of custom fields that should be part of the entity and will be presented to the user. </param>
        /// <param name="friendlyName"> The graph item display name which is a short humanly readable description of the graph item instance. This property is optional and might be system generated. </param>
        /// <param name="distinguishedName"> The group distinguished name. </param>
        /// <param name="objectGuid"> A single-value attribute that is the unique identifier for the object, assigned by active directory. </param>
        /// <param name="sid"> The SID attribute is a single-value attribute that specifies the security identifier (SID) of the group. </param>
        internal SecurityGroupEntity(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, EntityKind kind, IReadOnlyDictionary<string, BinaryData> additionalData, string friendlyName, string distinguishedName, Guid? objectGuid, string sid) : base(id, name, resourceType, systemData, kind)
        {
            AdditionalData = additionalData;
            FriendlyName = friendlyName;
            DistinguishedName = distinguishedName;
            ObjectGuid = objectGuid;
            Sid = sid;
            Kind = kind;
        }

        /// <summary>
        /// A bag of custom fields that should be part of the entity and will be presented to the user.
        /// <para>
        /// To assign an object to the value of this property use <see cref="BinaryData.FromObjectAsJson{T}(T, System.Text.Json.JsonSerializerOptions?)"/>.
        /// </para>
        /// <para>
        /// To assign an already formated json string to this property use <see cref="BinaryData.FromString(string)"/>.
        /// </para>
        /// <para>
        /// Examples:
        /// <list type="bullet">
        /// <item>
        /// <term>BinaryData.FromObjectAsJson("foo")</term>
        /// <description>Creates a payload of "foo".</description>
        /// </item>
        /// <item>
        /// <term>BinaryData.FromString("\"foo\"")</term>
        /// <description>Creates a payload of "foo".</description>
        /// </item>
        /// <item>
        /// <term>BinaryData.FromObjectAsJson(new { key = "value" })</term>
        /// <description>Creates a payload of { "key": "value" }.</description>
        /// </item>
        /// <item>
        /// <term>BinaryData.FromString("{\"key\": \"value\"}")</term>
        /// <description>Creates a payload of { "key": "value" }.</description>
        /// </item>
        /// </list>
        /// </para>
        /// </summary>
        public IReadOnlyDictionary<string, BinaryData> AdditionalData { get; }
        /// <summary> The graph item display name which is a short humanly readable description of the graph item instance. This property is optional and might be system generated. </summary>
        public string FriendlyName { get; }
        /// <summary> The group distinguished name. </summary>
        public string DistinguishedName { get; }
        /// <summary> A single-value attribute that is the unique identifier for the object, assigned by active directory. </summary>
        public Guid? ObjectGuid { get; }
        /// <summary> The SID attribute is a single-value attribute that specifies the security identifier (SID) of the group. </summary>
        public string Sid { get; }
    }
}


text:
#ifndef _RTC_H
#define _RTC_H

#include "peripheral/impTypes.h"
#include "peripheral/bhm.h"
#include "peripheral/ppm.h"

#define RTC_PERIPHERAL_ID 0xB

typedef struct {                            /*!< RTC Structure                                                         */
  Uns32 TASKS_START;                        /*!< Start RTC Counter.                                                    */
  Uns32 TASKS_STOP;                         /*!< Stop RTC Counter.                                                     */
  Uns32 TASKS_CLEAR;                        /*!< Clear RTC Counter.                                                    */
  Uns32 TASKS_TRIGOVRFLW;                   /*!< Set COUNTER to 0xFFFFFFF0.                                            */
  Uns32 EVENTS_TICK;                        /*!< Event on COUNTER increment.                                           */
  Uns32 EVENTS_OVRFLW;                      /*!< Event on COUNTER overflow.                                            */
  Uns32 EVENTS_COMPARE[4];                  /*!< Compare event on CC[n] match.                                         */
  Uns32 INTENSET;                           /*!< Interrupt enable set register.                                        */
  Uns32 INTENCLR;                           /*!< Interrupt enable clear register.                                      */
  Uns32 EVTEN;                              /*!< Configures event enable routing to PPI for each RTC event.            */
  Uns32 EVTENSET;                           /*!< Enable events routing to PPI. The reading of this register gives
                                                         the value of EVTEN.                                                   */
  Uns32 EVTENCLR;                           /*!< Disable events routing to PPI. The reading of this register
                                                         gives the value of EVTEN.                                             */
  Uns32 COUNTER;                            /*!< Current COUNTER value.                                                */
  Uns32 PRESCALER;                          /*!< 12-bit prescaler for COUNTER frequency (32768/(PRESCALER+1)).
                                                         Must be written when RTC is STOPed.                                   */
  Uns32 CC[4];                                /*!< Capture/compare registers.                                            */
  Uns32 POWER;                              /*!< Peripheral power control.                                             */
} rtcRegs;

PPM_CONSTRUCTOR_CB(init);
PPM_CONSTRUCTOR_CB(periphConstructor);

void loop();

// Bus and net port declarations
ppmNetHandle irqHandle;
ppmNetHandle rtcNotificationHandle;

rtcRegs regs;
void* rtcWindow;

bhmEventHandle startEventHandle;

//
// prototypes
//
PPM_VIEW_CB(viewReg32);
PPM_REG_READ_CB(regRd32);
PPM_REG_WRITE_CB(regWr32);

#endif


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

namespace _07_Sum_Arrays
{
    class SumArrays
    {
        //Write a program that reads two arrays of integers and sums them.
        //When the arrays are not of the same size, duplicate the smaller array a few times.
        static void Main(string[] args)
        {
            int[] array1 = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
            int[] array2 = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
            int length = Math.Max(array1.Length, array2.Length);
            int[] result = new int[length];
            for (int i = 0; i < length; i++)
            {
                result[i] = array1[i % array1.Length] + array2[i % array2.Length];
            }
            Console.WriteLine(string.Join(" ", result));
        }
    }
}


text:
@interface ABHTTPAPIClient : OSHTTPClient <HTTPAPIClient>

+ (ABHTTPAPIClient *)sharedClient;

@end


text:
<?php

namespace app\assets;

use yii\web\AssetBundle;

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class DatePickerAsset extends AssetBundle
{
    public $sourcePath = '@vendor/almasaeed2010/adminlte/plugins/datepicker';
    public $css = [
        'datepicker3.css',
    ];
    public $js = [
        'bootstrap-datepicker.js'
    ];

    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
        'yii\bootstrap\BootstrapPluginAsset',
    ];
}


text:
/**
 * Base Socket Client
 *
 * @param {Object} socket
 */
function BaseSocketClient(socket, encoder)
{
    EventEmitter.call(this);

    this.socket    = socket;
    this.encoder   = encoder;
    this.callbacks = {};
    this.connected = true;
    this.callCount = 0;

    this.socket.binaryType = 'arraybuffer';

    this.onMessage = this.onMessage.bind(this);
    this.onClose   = this.onClose.bind(this);

    this.attachEvents();
}

BaseSocketClient.prototype = Object.create(EventEmitter.prototype);
BaseSocketClient.prototype.constructor = BaseSocketClient;

/**
 * On socket close
 */
BaseSocketClient.prototype.onClose = function()
{
    this.connected = false;
    this.emit('close', this);
    this.detachEvents();
};

/**
 * Attach events
 */
BaseSocketClient.prototype.attachEvents = function()
{
    this.socket.addEventListener('message', this.onMessage);
    this.socket.addEventListener('close', this.onClose);
};

/**
 * Detach Events
 */
BaseSocketClient.prototype.detachEvents = function()
{
    this.socket.removeEventListener('message', this.onMessage);
    this.socket.removeEventListener('close', this.onClose);
};

/**
 * Add an event to the list
 *
 * @param {Object} event
 * @param {Function} callback
 */
BaseSocketClient.prototype.addEvent = function (event, callback)
{
    if (typeof(callback) === 'function') {
        event.callback = this.indexCallback(callback);
    }

    this.sendEvents([event]);
};

/**
 * Index a new callback
 *
 * @param {Function} callback
 *
 * @return {Number}
 */
BaseSocketClient.prototype.indexCallback = function(callback)
{
    var index = this.callCount++;

    this.callbacks[index] = callback;

    return index;
};

/**
 * Add a callback
 *
 * @param {Object} message
 * @param {Object} data
 */
BaseSocketClient.prototype.addCallback = function (message, data)
{
    var event = {name: message.name + ':callback', id: message.callback};

    if (typeof(data) !== 'undefined') {
        event.data = data;
    }

    this.sendEvents([event]);
};

/**
 * Send events
 *
 * @param {Array} events
 */
BaseSocketClient.prototype.sendEvents = function (events)
{
    this.sendBuffer(this.encoder.encode(events));
};

/**
 * Send buffer
 *
 * @param {Buffer} buffer
 */
BaseSocketClient.prototype.sendBuffer = function (buffer)
{
    this.socket.send(buffer);
};

/**
 * On message
 *
 * @param {Event} e
 */
BaseSocketClient.prototype.onMessage = function (e)
{
    var events = this.encoder.decode(e.data),
        length = events.length;

    for (var i = 0; i < length; i++) {
        this.processMessage(events[i]);
    }
};

/**
 * Process message
 *
 * @param {Object} message
 */
BaseSocketClient.prototype.processMessage = function(message)
{
    if (typeof(message.id) !== 'undefined') {
        return this.playCallback(message.id, message.data);
    }

    if (typeof(message.callback) !== 'undefined') {
        var detail = {callback: this.createCallback(message)};

        if (typeof(message.data) !== 'undefined') {
            detail.data = message.data;
        }

        this.emit(message.name, detail);
    } else {
        this.emit(message.name, message.data);
    }
};

/**
 * Play an indexed callback
 *
 * @param {Number} id
 * @param {Object|null} data
 */
BaseSocketClient.prototype.playCallback = function(id, data)
{
    if (typeof(this.callbacks[id]) !== 'undefined') {
        this.callbacks[id](data);
        delete this.callbacks[id];
    }
};

/**
 * Create callback
 *
 * @param {Object} message
 *
 * @return {Function}
 */
BaseSocketClient.prototype.createCallback = function(message)
{
    return function (data) { this.addCallback(message, data); }.bind(this);
};


text: export {default} from './checkout-step'


text:
require_relative '../lib/util/destroyer'
require_relative '../lib/script_helper'
require 'optparse'

config = {}
ScriptHelper.read_defaults(config)

opt_parser = OptionParser.new do |opts|
  opts.banner = "Usage: #{File.basename(__FILE__)}"
  ScriptHelper.one_arg_opts(
    opts, config,
    name: 'Name to be used for PK, EBS, DNS, etc.',
    availability_zone: 'Availability Zone'
  )
  ScriptHelper.no_arg_opts(
    opts, config,
    debug: 'Turn on debug logging',
    unsafe: 'Delete based on name conventions, rather than dependency tree'
  )
  opts.separator('When run you are prompted to confirm,')
  opts.separator('and then everything relating to the name is deleted.')
end

ScriptHelper.read_args(config, opt_parser, [:availability_zone, :name])

print "Really destroy everything relating to #{config[:name]}? Reenter to confirm: "
unless gets.strip == config[:name]
  warn 'Quit without touching anything.'
  exit 1
end

Destroyer.new(debug: config[:debug], availability_zone: config[:availability_zone])
  .destroy(config[:name], config[:unsafe])


text:
<!doctype html>
<title>WebSockets: getting readyState in closed</title>

FAIL (script didn't run)


text:
class AddExcludedTaxonConceptsIdsToApiTaxonReferencesView < ActiveRecord::Migration
  def up
    execute "DROP VIEW IF EXISTS api_taxon_references_view"
    execute "CREATE VIEW api_taxon_references_view AS #{view_sql('20150302082111', 'api_taxon_references_view')}"
  end

  def down
    execute "DROP VIEW IF EXISTS api_taxon_references_view"
    execute "CREATE VIEW api_taxon_references_view AS #{view_sql('20150217174539', 'api_taxon_references_view')}"
  end
end


text:
/**
 * An instance of Report is used to report results of the
 * verification back to the main API.
 * @class Reporter
 * @constructor
 * @param {String[]} lines The text lines of the source.
 * @param {Object} ruleset The set of rules to work with, including if
 *      they are errors or warnings.
 * @param {Object} explicitly allowed lines
 * @param {[][]} ingore list of line ranges to be ignored
 */
function Reporter(lines, ruleset, allow, ignore) {
    "use strict";

    /**
     * List of messages being reported.
     * @property messages
     * @type String[]
     */
    this.messages = [];

    /**
     * List of statistics being reported.
     * @property stats
     * @type String[]
     */
    this.stats = [];

    /**
     * Lines of code being reported on. Used to provide contextual information
     * for messages.
     * @property lines
     * @type String[]
     */
    this.lines = lines;

    /**
     * Information about the rules. Used to determine whether an issue is an
     * error or warning.
     * @property ruleset
     * @type Object
     */
    this.ruleset = ruleset;

    /**
     * Lines with specific rule messages to leave out of the report.
     * @property allow
     * @type Object
     */
    this.allow = allow;
    if(!this.allow) {
        this.allow = {};
    }

    /**
     * Linesets not to include in the report.
     * @property ignore
     * @type [][]
     */
    this.ignore = ignore;
    if(!this.ignore) {
        this.ignore = [];
    }
}

Reporter.prototype = {

    //restore constructor
    constructor: Reporter,

    /**
     * Report an error.
     * @param {String} message The message to store.
     * @param {int} line The line number.
     * @param {int} col The column number.
     * @param {Object} rule The rule this message relates to.
     * @method error
     */
    error: function(message, line, col, rule) {
        "use strict";
        this.messages.push({
            type    : "error",
            line    : line,
            col     : col,
            message : message,
            evidence: this.lines[line-1],
            rule    : rule || {}
        });
    },

    /**
     * Report an warning.
     * @param {String} message The message to store.
     * @param {int} line The line number.
     * @param {int} col The column number.
     * @param {Object} rule The rule this message relates to.
     * @method warn
     * @deprecated Use report instead.
     */
    warn: function(message, line, col, rule) {
        "use strict";
        this.report(message, line, col, rule);
    },

    /**
     * Report an issue.
     * @param {String} message The message to store.
     * @param {int} line The line number.
     * @param {int} col The column number.
     * @param {Object} rule The rule this message relates to.
     * @method report
     */
    report: function(message, line, col, rule) {
        "use strict";

        // Check if rule violation should be allowed
        if (this.allow.hasOwnProperty(line) && this.allow[line].hasOwnProperty(rule.id)) {
            return;
        }

        var ignore = false;
        CSSLint.Util.forEach(this.ignore, function (range) {
            if(range[0] <= line && line <= range[1]) {
                ignore = true;
            }
        });
        if(ignore) {
            return;
        }

        this.messages.push({
            type    : this.ruleset[rule.id] === 2 ? "error" : "warning",
            line    : line,
            col     : col,
            message : message,
            evidence: this.lines[line-1],
            rule    : rule
        });
    },

    /**
     * Report some informational text.
     * @param {String} message The message to store.
     * @param {int} line The line number.
     * @param {int} col The column number.
     * @param {Object} rule The rule this message relates to.
     * @method info
     */
    info: function(message, line, col, rule) {
        "use strict";
        this.messages.push({
            type    : "info",
            line    : line,
            col     : col,
            message : message,
            evidence: this.lines[line-1],
            rule    : rule
        });
    },

    /**
     * Report some rollup error information.
     * @param {String} message The message to store.
     * @param {Object} rule The rule this message relates to.
     * @method rollupError
     */
    rollupError: function(message, rule) {
        "use strict";
        this.messages.push({
            type    : "error",
            rollup  : true,
            message : message,
            rule    : rule
        });
    },

    /**
     * Report some rollup warning information.
     * @param {String} message The message to store.
     * @param {Object} rule The rule this message relates to.
     * @method rollupWarn
     */
    rollupWarn: function(message, rule) {
        "use strict";
        this.messages.push({
            type    : "warning",
            rollup  : true,
            message : message,
            rule    : rule
        });
    },

    /**
     * Report a statistic.
     * @param {String} name The name of the stat to store.
     * @param {Variant} value The value of the stat.
     * @method stat
     */
    stat: function(name, value) {
        "use strict";
        this.stats[name] = value;
    }
};

//expose for testing purposes
CSSLint._Reporter = Reporter;


text:
      <input aria-required="true" checked=
      "checked" class="radio_buttons required form-control" id=
      "file_set_viewing_hint__p2676v670" name="file_set[viewing_hint]"
      required="required" type="radio" value="">Single
      Page<input aria-required=
      "true" class="radio_buttons required form-control" id=
      "file_set_viewing_hint_non-paged_p2676v670" name="file_set[viewing_hint]"
      required="required" type="radio" value="non-paged">Non-Paged<input aria-required="true"
      class="radio_buttons required form-control" id=
      "file_set_viewing_hint_facing-pages_p2676v670" name=
      "file_set[viewing_hint]" required="required" type="radio" value=
      "facing-pages">Facing
      pages


text:
using System;
using System.Web.Hosting;
using System.IO;

namespace DotNetNuke.Tests.Instance.Utilities
{
    /// <summary>
    /// Used to simulate an HttpRequest.
    /// </summary>
    public class SimulatedHttpRequest : SimpleWorkerRequest
    {
        readonly string _host;

        /// <summary>
        /// Creates a new <see cref="SimulatedHttpRequest"/> instance.
        /// </summary>
        /// <param name="appVirtualDir">App virtual dir.</param>
        /// <param name="appPhysicalDir">App physical dir.</param>
        /// <param name="page">Page.</param>
        /// <param name="query">Query.</param>
        /// <param name="output">Output.</param>
        /// <param name="host">Host.</param>
        public SimulatedHttpRequest(string appVirtualDir, string appPhysicalDir, string page, string query, TextWriter output, string host): base(appVirtualDir, appPhysicalDir, page, query, output)
        {
            if (string.IsNullOrEmpty(host))
                throw new ArgumentNullException("host", "Host cannot be null nor empty.");
            _host = host;
        }

        /// <summary>
        /// Gets the name of the server.
        /// </summary>
        /// <returns></returns>
        public override string GetServerName()
        {
            return _host;
        }

        /// <summary>
        /// Maps the path to a filesystem path.
        /// </summary>
        /// <param name="virtualPath">Virtual path.</param>
        /// <returns></returns>
        public override string MapPath(string virtualPath)
        {
            var path = "";
            var appPath = GetAppPath();

            if (appPath != null)
                path = Path.Combine(appPath, virtualPath);

            return path;
        }
    }
}


text:
package linear

import (
	"math"
	"testing"

	"github.com/m3db/m3/src/query/executor/transform"
	"github.com/m3db/m3/src/query/models"
	"github.com/m3db/m3/src/query/parser"
	"github.com/m3db/m3/src/query/test"
	"github.com/m3db/m3/src/query/test/compare"
	"github.com/m3db/m3/src/query/test/executor"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func expectedMathVals(values [][]float64, fn func(x float64) float64) [][]float64 {
	expected := make([][]float64, 0, len(values))
	for _, val := range values {
		v := make([]float64, len(val))
		for i, ev := range val {
			v[i] = fn(ev)
		}

		expected = append(expected, v)
	}
	return expected
}

func TestAbsWithAllValues(t *testing.T) {
	values, bounds := test.GenerateValuesAndBounds(nil, nil)
	values[0][0] = -values[0][0]
	values[1][1] = -values[1][1]

	block := test.NewBlockFromValues(bounds, values)
	c, sink := executor.NewControllerWithSink(parser.NodeID(rune(1)))
	mathOp, err := NewMathOp(AbsType)
	require.NoError(t, err)

	op, ok := mathOp.(transform.Params)
	require.True(t, ok)
	node := op.Node(c, transform.Options{})
	err = node.Process(models.NoopQueryContext(), parser.NodeID(rune(0)), block)
	require.NoError(t, err)
	expected := expectedMathVals(values, math.Abs)
	assert.Len(t, sink.Values, 2)
	assert.Equal(t, expected, sink.Values)
}

func TestAbsWithSomeValues(t *testing.T) {
	v := [][]float64{
		{0, math.NaN(), 2, 3, 4},
		{math.NaN(), 6, 7, 8, 9},
	}

	values, bounds := test.GenerateValuesAndBounds(v, nil)
	block := test.NewBlockFromValues(bounds, values)
	c, sink := executor.NewControllerWithSink(parser.NodeID(rune(1)))
	mathOp, err := NewMathOp(AbsType)
	require.NoError(t, err)

	op, ok := mathOp.(transform.Params)
	require.True(t, ok)

	node := op.Node(c, transform.Options{})
	err = node.Process(models.NoopQueryContext(), parser.NodeID(rune(0)), block)
	require.NoError(t, err)
	expected := expectedMathVals(values, math.Abs)
	assert.Len(t, sink.Values, 2)
	compare.EqualsWithNans(t, expected, sink.Values)
}

func TestLn(t *testing.T) {
	values, bounds := test.GenerateValuesAndBounds(nil, nil)

	block := test.NewBlockFromValues(bounds, values)
	c, sink := executor.NewControllerWithSink(parser.NodeID(rune(1)))
	mathOp, err := NewMathOp(LnType)
	require.NoError(t, err)

	op, ok := mathOp.(transform.Params)
	require.True(t, ok)

	node := op.Node(c, transform.Options{})
	err = node.Process(models.NoopQueryContext(), parser.NodeID(rune(0)), block)
	require.NoError(t, err)
	expected := expectedMathVals(values, math.Log)
	assert.Len(t, sink.Values, 2)
	assert.Equal(t, expected, sink.Values)
}

func TestLog10WithNoValues(t *testing.T) {
	v := [][]float64{
		{nan, nan, nan, nan, nan},
		{nan, nan, nan, nan, nan},
	}

	values, bounds := test.GenerateValuesAndBounds(v, nil)
	block := test.NewBlockFromValues(bounds, values)
	c, sink := executor.NewControllerWithSink(parser.NodeID(rune(1)))
	mathOp, err := NewMathOp(Log10Type)
	require.NoError(t, err)

	op, ok := mathOp.(transform.Params)
	require.True(t, ok)

	node := op.Node(c, transform.Options{})
	err = node.Process(models.NoopQueryContext(), parser.NodeID(rune(0)), block)
	require.NoError(t, err)
	expected := expectedMathVals(values, math.Log10)
	assert.Len(t, sink.Values, 2)
	compare.EqualsWithNans(t, expected, sink.Values)
}

func TestLog2WithSomeValues(t *testing.T) {
	v := [][]float64{
		{nan, 1, 2, 3, 3},
		{nan, 4, 5, 6, 6},
	}

	values, bounds := test.GenerateValuesAndBounds(v, nil)
	block := test.NewBlockFromValues(bounds, values)
	c, sink := executor.NewControllerWithSink(parser.NodeID(rune(1)))
	mathOp, err := NewMathOp(Log2Type)
	require.NoError(t, err)

	op, ok := mathOp.(transform.Params)
	require.True(t, ok)

	node := op.Node(c, transform.Options{})
	err = node.Process(models.NoopQueryContext(), parser.NodeID(rune(0)), block)
	require.NoError(t, err)
	expected := expectedMathVals(values, math.Log2)
	assert.Len(t, sink.Values, 2)
	compare.EqualsWithNans(t, expected, sink.Values)
}

func TestFloorWithSomeValues(t *testing.T) {
	v := [][]float64{
		{0, math.NaN(), 2.2, 3.3, 4},
		{math.NaN(), 6, 7.77, 8, 9.9},
	}

	values, bounds := test.GenerateValuesAndBounds(v, nil)
	block := test.NewBlockFromValues(bounds, values)
	c, sink := executor.NewControllerWithSink(parser.NodeID(rune(1)))
	mathOp, err := NewMathOp(FloorType)
	require.NoError(t, err)

	op, ok := mathOp.(transform.Params)
	require.True(t, ok)

	node := op.Node(c, transform.Options{})
	err = node.Process(models.NoopQueryContext(), parser.NodeID(rune(0)), block)
	require.NoError(t, err)
	expected := expectedMathVals(values, math.Floor)
	assert.Len(t, sink.Values, 2)
	compare.EqualsWithNans(t, expected, sink.Values)
}

func TestCeilWithSomeValues(t *testing.T) {
	v := [][]float64{
		{0, math.NaN(), 2.2, 3.3, 4},
		{math.NaN(), 6, 7.77, 8, 9.9},
	}

	values, bounds := test.GenerateValuesAndBounds(v, nil)
	block := test.NewBlockFromValues(bounds, values)
	c, sink := executor.NewControllerWithSink(parser.NodeID(rune(1)))
	mathOp, err := NewMathOp(CeilType)
	require.NoError(t, err)

	op, ok := mathOp.(transform.Params)
	require.True(t, ok)

	node := op.Node(c, transform.Options{})
	err = node.Process(models.NoopQueryContext(), parser.NodeID(rune(0)), block)
	require.NoError(t, err)
	expected := expectedMathVals(values, math.Ceil)
	assert.Len(t, sink.Values, 2)
	compare.EqualsWithNans(t, expected, sink.Values)
}
func TestExpWithSomeValues(t *testing.T) {
	v := [][]float64{
		{0, math.NaN(), 2, 3, 4},
		{math.NaN(), 6, 7, 8, 9},
	}

	values, bounds := test.GenerateValuesAndBounds(v, nil)
	block := test.NewBlockFromValues(bounds, values)
	c, sink := executor.NewControllerWithSink(parser.NodeID(rune(1)))
	mathOp, err := NewMathOp(ExpType)
	require.NoError(t, err)

	op, ok := mathOp.(transform.Params)
	require.True(t, ok)

	node := op.Node(c, transform.Options{})
	err = node.Process(models.NoopQueryContext(), parser.NodeID(rune(0)), block)
	require.NoError(t, err)
	expected := expectedMathVals(values, math.Exp)
	assert.Len(t, sink.Values, 2)
	compare.EqualsWithNans(t, expected, sink.Values)
}

func TestSqrtWithSomeValues(t *testing.T) {
	v := [][]float64{
		{0, math.NaN(), 2, 3, 4},
		{math.NaN(), 6, 7, 8, 9},
	}

	values, bounds := test.GenerateValuesAndBounds(v, nil)
	block := test.NewBlockFromValues(bounds, values)
	c, sink := executor.NewControllerWithSink(parser.NodeID(rune(1)))
	mathOp, err := NewMathOp(SqrtType)
	require.NoError(t, err)

	op, ok := mathOp.(transform.Params)
	require.True(t, ok)

	node := op.Node(c, transform.Options{})
	err = node.Process(models.NoopQueryContext(), parser.NodeID(rune(0)), block)
	require.NoError(t, err)
	expected := expectedMathVals(values, math.Sqrt)
	assert.Len(t, sink.Values, 2)
	compare.EqualsWithNans(t, expected, sink.Values)
}

func TestNonExistentFunc(t *testing.T) {
	_, err := NewMathOp("nonexistent_func")
	require.Error(t, err)
}


text:
var jsFiles = [
"src/AssetsManager.js",
"src/cocos.jquery.min.js",
"src/GLOBAL_DATA.js",
"src/resource.js",
"src/Util/EightSprite.js",
"src/Util/underscore.js",
"src/Util/util.js",
"src/Util/JQ/CocosSelector.js",
"src/Util/JQ/JQ.js",
"src/Util/JQ/JQCore.js",
"src/Util/JQ/jqCore/animate.js",
"src/Util/JQ/jqCore/css.js",
"src/Util/JQ/jqCore/event.js",
"src/Util/JQ/jqCore/operation.js",
"src/Util/JQ/jqCore/property.js",
"src/Util/JQ/jqCore/selector.js",
"src/Util/JQ/jqCore/util.js",
"src/Util/JQ/extend/ajax.js",
"src/Util/JQ/extend/css.js",
"src/Util/JQ/extend/util.js",
"src/Util/JQ/Component/device.js",
"src/Util/JQ/Component/encrypt.js",
"src/Util/JQ/Component/net.js",
"src/Util/JQ/Component/sql.js",
"src/Util/JQ/Component/ui.js",
"src/Util/JQ/Component/util.js",
"src/Util/JQ/Component/wx.js",
"src/StartScene/StartLayer.js",
"src/StartScene/StartScene.js",
"src/SelectorScene/SelectorLayer.js",
"src/SelectorScene/SelectorScene.js",
"src/OtherScene/OtherLayer.js",
"src/OtherScene/OtherScene.js",
"src/OperationScene/OperationLayer.js",
"src/OperationScene/OperationScene.js",
"src/MenuScene/MenuLayer.js",
"src/MenuScene/MenuScene.js",
"src/LoadingScene/LoadingScene.js",
"src/EventScene/EventLayer.js",
"src/EventScene/EventScene.js",
"src/CssScene/CssLayer.js",
"src/CssScene/CssScene.js",
"src/AnimateScene/AnimateLayer.js",
"src/AnimateScene/AnimateScene.js",
"src/AjaxScene/AjaxLayer.js",
"src/AjaxScene/AjaxScene.js"
];


text:
@interface TangModel : NSObject
@property(nonatomic,retain) NSString *oneTitleModel;
@property(nonatomic,retain) NSString *twoNameModel;
- (instancetype) initWithString:(NSString *)str;
@end


text:
// source:

package test.junit.vfs;

import junit.framework.Test;
import junit.framework.TestSuite;
import nl.uva.vlet.GlobalConfig;
import nl.uva.vlet.vrl.VRL;
import test.junit.TestSettings;

/**
 * Test SRB case
 *
 * TestSuite uses testVFS class to tests SRB implementation.
 *
 * @author P.T. de Boer
 */

public class testGFTP_V1_0_passive
{
    public static class testVFS_GFTP extends testVFS
    {
        @Override
        public VRL getRemoteLocation()
        {
            return TestSettings.getTestLocation(TestSettings.VFS_GFTP_V1_LOCATION);
        }
    }

    public static Test suite()
    {
        GlobalConfig.setPassiveMode(true);
        // Global.setDebug(true);

        testVFS.staticCheckProxy();

        return new TestSuite(testVFS_GFTP.class);
    }

    public static void main(String args[])
    {

        junit.textui.TestRunner.run(suite());

    }

}


text:
/*
 * This file is part of FFmpeg.
 *
 * FFmpeg 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 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg 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 FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

/**
 * @file
 * common internal api header.
 */

#ifndef AVCODEC_INTERNAL_H
#define AVCODEC_INTERNAL_H

#include <stdint.h>

#include "libavutil/buffer.h"
#include "libavutil/channel_layout.h"
#include "libavutil/mathematics.h"
#include "libavutil/pixfmt.h"
#include "avcodec.h"
#include "config.h"

/**
 * The codec does not modify any global variables in the init function,
 * allowing to call the init function without locking any global mutexes.
 */
#define FF_CODEC_CAP_INIT_THREADSAFE        (1 << 0)
/**
 * The codec allows calling the close function for deallocation even if
 * the init function returned a failure. Without this capability flag, a
 * codec does such cleanup internally when returning failures from the
 * init function and does not expect the close function to be called at
 * all.
 */
#define FF_CODEC_CAP_INIT_CLEANUP           (1 << 1)
/**
 * Decoders marked with FF_CODEC_CAP_SETS_PKT_DTS want to set
 * AVFrame.pkt_dts manually. If the flag is set, utils.c won't overwrite
 * this field. If it's unset, utils.c tries to guess the pkt_dts field
 * from the input AVPacket.
 */
#define FF_CODEC_CAP_SETS_PKT_DTS           (1 << 2)
/**
 * The decoder extracts and fills its parameters even if the frame is
 * skipped due to the skip_frame setting.
 */
#define FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM  (1 << 3)

#ifdef TRACE
#   define ff_tlog(ctx, ...) av_log(ctx, AV_LOG_TRACE, __VA_ARGS__)
#else
#   define ff_tlog(ctx, ...) do { } while(0)
#endif

#if !FF_API_QUANT_BIAS
#define FF_DEFAULT_QUANT_BIAS 999999
#endif

#define FF_SANE_NB_CHANNELS 64U

#define FF_SIGNBIT(x) ((x) >> CHAR_BIT * sizeof(x) - 1)

#if HAVE_AVX
#   define STRIDE_ALIGN 32
#elif HAVE_SIMD_ALIGN_16
#   define STRIDE_ALIGN 16
#else
#   define STRIDE_ALIGN 8
#endif

typedef struct FramePool {
    /**
     * Pools for each data plane. For audio all the planes have the same size,
     * so only pools[0] is used.
     */
    AVBufferPool *pools[4];

    /*
     * Pool parameters
     */
    int format;
    int width, height;
    int stride_align[AV_NUM_DATA_POINTERS];
    int linesize[4];
    int planes;
    int channels;
    int samples;
} FramePool;

typedef struct AVCodecInternal {
    /**
     * Whether the parent AVCodecContext is a copy of the context which had
     * init() called on it.
     * This is used by multithreading - shared tables and picture pointers
     * should be freed from the original context only.
     */
    int is_copy;

    /**
     * Whether to allocate progress for frame threading.
     *
     * The codec must set it to 1 if it uses ff_thread_await/report_progress(),
     * then progress will be allocated in ff_thread_get_buffer(). The frames
     * then MUST be freed with ff_thread_release_buffer().
     *
     * If the codec does not need to call the progress functions (there are no
     * dependencies between the frames), it should leave this at 0. Then it can
     * decode straight to the user-provided frames (which the user will then
     * free with av_frame_unref()), there is no need to call
     * ff_thread_release_buffer().
     */
    int allocate_progress;

    /**
     * An audio frame with less than required samples has been submitted and
     * padded with silence. Reject all subsequent frames.
     */
    int last_audio_frame;

    AVFrame *to_free;

    FramePool *pool;

    void *thread_ctx;

    /**
     * Current packet as passed into the decoder, to avoid having to pass the
     * packet into every function.
     */
    AVPacket *pkt;

    /**
     * temporary buffer used for encoders to store their bitstream
     */
    uint8_t *byte_buffer;
    unsigned int byte_buffer_size;

    void *frame_thread_encoder;

    /**
     * Number of audio samples to skip at the start of the next decoded frame
     */
    int skip_samples;

    /**
     * hwaccel-specific private data
     */
    void *hwaccel_priv_data;
} AVCodecInternal;

struct AVCodecDefault {
    const uint8_t *key;
    const uint8_t *value;
};

extern const uint8_t ff_log2_run[41];

/**
 * Return the index into tab at which {a,b} match elements {[0],[1]} of tab.
 * If there is no such matching pair then size is returned.
 */
int ff_match_2uint16(const uint16_t (*tab)[2], int size, int a, int b);

unsigned int avpriv_toupper4(unsigned int x);

/**
 * does needed setup of pkt_pts/pos and such for (re)get_buffer();
 */
int ff_init_buffer_info(AVCodecContext *s, AVFrame *frame);

void ff_color_frame(AVFrame *frame, const int color[4]);

extern volatile int ff_avcodec_locked;
int ff_lock_avcodec(AVCodecContext *log_ctx, const AVCodec *codec);
int ff_unlock_avcodec(const AVCodec *codec);

int avpriv_lock_avformat(void);
int avpriv_unlock_avformat(void);

/**
 * Maximum size in bytes of extradata.
 * This value was chosen such that every bit of the buffer is
 * addressable by a 32-bit signed integer as used by get_bits.
 */
#define FF_MAX_EXTRADATA_SIZE ((1 << 28) - AV_INPUT_BUFFER_PADDING_SIZE)

/**
 * Check AVPacket size and/or allocate data.
 *
 * Encoders supporting AVCodec.encode2() can use this as a convenience to
 * ensure the output packet data is large enough, whether provided by the user
 * or allocated in this function.
 *
 * @param avctx   the AVCodecContext of the encoder
 * @param avpkt   the AVPacket
 *                If avpkt->data is already set, avpkt->size is checked
 *                to ensure it is large enough.
 *                If avpkt->data is NULL, a new buffer is allocated.
 *                avpkt->size is set to the specified size.
 *                All other AVPacket fields will be reset with av_init_packet().
 * @param size    the minimum required packet size
 * @param min_size This is a hint to the allocation algorithm, which indicates
 *                to what minimal size the caller might later shrink the packet
 *                to. Encoders often allocate packets which are larger than the
 *                amount of data that is written into them as the exact amount is
 *                not known at the time of allocation. min_size represents the
 *                size a packet might be shrunk to by the caller. Can be set to
 *                0. setting this roughly correctly allows the allocation code
 *                to choose between several allocation strategies to improve
 *                speed slightly.
 * @return        non negative on success, negative error code on failure
 */
int ff_alloc_packet2(AVCodecContext *avctx, AVPacket *avpkt, int64_t size, int64_t min_size);

attribute_deprecated int ff_alloc_packet(AVPacket *avpkt, int size);

/**
 * Rescale from sample rate to AVCodecContext.time_base.
 */
static av_always_inline int64_t ff_samples_to_time_base(AVCodecContext *avctx,
                                                        int64_t samples)
{
    if(samples == AV_NOPTS_VALUE)
        return AV_NOPTS_VALUE;
    return av_rescale_q(samples, (AVRational){ 1, avctx->sample_rate },
                        avctx->time_base);
}

/**
 * 2^(x) for integer x
 * @return correctly rounded float
 */
static av_always_inline float ff_exp2fi(int x) {
    /* Normal range */
    if (-126 <= x && x <= 128)
        return av_int2float(x+127 << 23);
    /* Too large */
    else if (x > 128)
        return INFINITY;
    /* Subnormal numbers */
    else if (x > -150)
        return av_int2float(1 << (x+149));
    /* Negligibly small */
    else
        return 0;
}

/**
 * Get a buffer for a frame. This is a wrapper around
 * AVCodecContext.get_buffer() and should be used instead calling get_buffer()
 * directly.
 */
int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags);

/**
 * Identical in function to av_frame_make_writable(), except it uses
 * ff_get_buffer() to allocate the buffer when needed.
 */
int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame);

int ff_thread_can_start_frame(AVCodecContext *avctx);

int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx);

/**
 * Call avcodec_open2 recursively by decrementing counter, unlocking mutex,
 * calling the function and then restoring again. Assumes the mutex is
 * already locked
 */
int ff_codec_open2_recursive(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options);

/**
 * Finalize buf into extradata and set its size appropriately.
 */
int avpriv_bprint_to_extradata(AVCodecContext *avctx, struct AVBPrint *buf);

const uint8_t *avpriv_find_start_code(const uint8_t *p,
                                      const uint8_t *end,
                                      uint32_t *state);

/**
 * Check that the provided frame dimensions are valid and set them on the codec
 * context.
 */
int ff_set_dimensions(AVCodecContext *s, int width, int height);

/**
 * Check that the provided sample aspect ratio is valid and set it on the codec
 * context.
 */
int ff_set_sar(AVCodecContext *avctx, AVRational sar);

/**
 * Add or update AV_FRAME_DATA_MATRIXENCODING side data.
 */
int ff_side_data_update_matrix_encoding(AVFrame *frame,
                                        enum AVMatrixEncoding matrix_encoding);

/**
 * Select the (possibly hardware accelerated) pixel format.
 * This is a wrapper around AVCodecContext.get_format() and should be used
 * instead of calling get_format() directly.
 */
int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt);

/**
 * Set various frame properties from the codec context / packet data.
 */
int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame);

/**
 * Add a CPB properties side data to an encoding context.
 */
AVCPBProperties *ff_add_cpb_side_data(AVCodecContext *avctx);

int ff_side_data_set_encoder_stats(AVPacket *pkt, int quality, int64_t *error, int error_count, int pict_type);

#endif /* AVCODEC_INTERNAL_H */


text:
package com.facebook.buck.rules.macros;

import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.rules.BuildRuleResolver;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.core.sourcepath.resolver.SourcePathResolverAdapter;
import com.facebook.buck.rules.args.Arg;
import java.nio.file.Path;

/** Handles '$(output ...)' macro which expands to the path of a named supplementary output. */
public class OutputMacroExpander extends AbstractMacroExpanderWithoutPrecomputedWork<OutputMacro> {
  @Override
  public Arg expandFrom(BuildTarget target, ActionGraphBuilder graphBuilder, OutputMacro input) {
    return new OutputArg(input, graphBuilder, target);
  }

  @Override
  public Class<OutputMacro> getInputClass() {
    return OutputMacro.class;
  }

  private static class OutputArg extends AbstractOutputArg {

    OutputArg(OutputMacro input, BuildRuleResolver resolver, BuildTarget target) {
      super(input.getOutputName(), resolver, target);
    }

    @Override
    Path sourcePathToArgPath(SourcePath path, SourcePathResolverAdapter resolver) {
      return resolver.getRelativePath(path);
    }
  }
}


text:
package com.hazelcast.simulator.tests.map;

import com.hazelcast.config.Config;
import com.hazelcast.config.MapConfig;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.logging.ILogger;
import com.hazelcast.logging.Logger;
import com.hazelcast.simulator.test.TestContext;
import com.hazelcast.simulator.test.TestRunner;
import com.hazelcast.simulator.test.annotations.Run;
import com.hazelcast.simulator.test.annotations.Setup;
import com.hazelcast.simulator.test.annotations.Verify;
import com.hazelcast.simulator.utils.ThreadSpawner;

import java.util.Random;
import java.util.concurrent.TimeUnit;

import static com.hazelcast.simulator.utils.CommonUtils.humanReadableByteCount;
import static com.hazelcast.simulator.utils.CommonUtils.sleepMillis;

public class MapTTLSaturationTest {

    private static final ILogger LOGGER = Logger.getLogger(MapTTLSaturationTest.class);

    // properties
    public String basename = MapTTLSaturationTest.class.getSimpleName();
    public int threadCount = 3;
    public double maxHeapUsagePercentage = 80;

    private TestContext testContext;
    private IMap map;

    @Setup
    public void setup(TestContext testContext) throws Exception {
        this.testContext = testContext;
        map = testContext.getTargetInstance().getMap(basename);
    }

    private double heapUsedPercentage() {
        long total = Runtime.getRuntime().totalMemory();
        long max = Runtime.getRuntime().maxMemory();
        return (100d * total) / max;
    }

    @Run
    public void run() {
        ThreadSpawner spawner = new ThreadSpawner(testContext.getTestId());
        for (int k = 0; k < threadCount; k++) {
            spawner.spawn(new Worker());
        }
        spawner.awaitCompletion();
    }

    private class Worker implements Runnable {
        @Override
        public void run() {
            long free = Runtime.getRuntime().freeMemory();
            long total = Runtime.getRuntime().totalMemory();
            long baseLineUsed = total - free;
            long maxBytes = Runtime.getRuntime().maxMemory();
            double usedOfMax = 100.0 * ((double) baseLineUsed / (double) maxBytes);

            LOGGER.info(basename + " before Init");
            LOGGER.info(basename + " free = " + humanReadableByteCount(free, true) + " = " + free);
            LOGGER.info(basename + " used = " + humanReadableByteCount(baseLineUsed, true) + " = " + baseLineUsed);
            LOGGER.info(basename + " max = " + humanReadableByteCount(maxBytes, true) + " = " + maxBytes);
            LOGGER.info(basename + " usedOfMax = " + usedOfMax + "%");

            int counter = 1;
            Random random = new Random();

            while (!testContext.isStopped()) {
                double usedPercentage = heapUsedPercentage();
                if (usedPercentage >= maxHeapUsagePercentage) {
                    LOGGER.info("heap used: " + usedPercentage + " % map.size:" + map.size());

                    sleepMillis(10000);
                } else {
                    for (int k = 0; k < 1000; k++) {
                        counter++;
                        if (counter % 100000 == 0) {
                            LOGGER.info("at:" + counter + " heap used: " + usedPercentage + " % map.size:" + map.size());
                        }
                        long key = random.nextLong();
                        map.put(key, 0, 24, TimeUnit.HOURS);
                    }
                }
            }

            free = Runtime.getRuntime().freeMemory();
            total = Runtime.getRuntime().totalMemory();
            long nowUsed = total - free;
            maxBytes = Runtime.getRuntime().maxMemory();
            usedOfMax = 100.0 * ((double) nowUsed / (double) maxBytes);

            LOGGER.info(basename + " After Init");
            LOGGER.info(basename + " map = " + map.size());
            LOGGER.info(basename + " free = " + humanReadableByteCount(free, true) + " = " + free);
            LOGGER.info(basename + " used = " + humanReadableByteCount(nowUsed, true) + " = " + nowUsed);
            LOGGER.info(basename + " max = " + humanReadableByteCount(maxBytes, true) + " = " + maxBytes);
            LOGGER.info(basename + " usedOfMax = " + usedOfMax + "%");
            LOGGER.info(basename + " map size:" + map.size());
        }
    }

    @Verify(global = false)
    public void globalVerify() throws Exception {
        long free = Runtime.getRuntime().freeMemory();
        long total = Runtime.getRuntime().totalMemory();
        long used = total - free;
        long maxBytes = Runtime.getRuntime().maxMemory();
        double usedOfMax = 100.0 * ((double) used / (double) maxBytes);

        LOGGER.info(basename + " map = " + map.size());
        LOGGER.info(basename + "free = " + humanReadableByteCount(free, true) + " = " + free);
        LOGGER.info(basename + "used = " + humanReadableByteCount(used, true) + " = " + used);
        LOGGER.info(basename + "max = " + humanReadableByteCount(maxBytes, true) + " = " + maxBytes);
        LOGGER.info(basename + "usedOfMax = " + usedOfMax + "%");
    }

    public static void main(String[] args) throws Exception {
        Config config = new Config();
        config.addMapConfig(new MapConfig("mapttlsaturation*").setBackupCount(0).setStatisticsEnabled(false));
        HazelcastInstance hz = Hazelcast.newHazelcastInstance(config);
        new TestRunner<MapTTLSaturationTest>(new MapTTLSaturationTest()).withHazelcastInstance(hz).withDuration(6000).run();
    }
}


text:
Remove-Item ..\dist\* -Recurse
dotnet publish ..\src\carlserver\carlserver.blazor\Client\carlserver.blazor.Client.csproj -c Release -o ..\dist\output
cd ..\prerender
npx react-snap
Write-Host 'Delete last 2 script tags in index.html'
cd ..\deploy


text:
package com.devilmygod.admin.bean;

import com.devilmygod.admin.base.BaseBean;

import java.io.Serializable;

/**
 * 说明:系统用户表 实体类
 *
 * @author devil
 * @version 1.0
 * @date Created in 2018/1/18 15:33
 */
public class SysUser extends BaseBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private Integer id;

    /**
     * 账号
     */
    private String account;

    /**
     * 名称
     */
    private String name;

    /**
     * 加密后的密码
     */
    private String hashedPassword;

    /**
     * 状态(0:启用 1:停用)
     */
    private Integer status;

    /**
     * 现密码
     */
    private String curPassword;

    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getAccount() {
        return this.account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

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

    public void setName(String name) {
        this.name = name;
    }

    public String getHashedPassword() {
        return this.hashedPassword;
    }

    public void setHashedPassword(String hashedPassword) {
        this.hashedPassword = hashedPassword;
    }

    public Integer getStatus() {
        return this.status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getCurPassword() {
        return curPassword;
    }

    public void setCurPassword(String curPassword) {
        this.curPassword = curPassword;
    }

}


text:
from math import *

class Matrix:
    # implements basic operations of a Matrix class

    def __init__(self, value):
        self.value = value
        self.dimx = len(value)
        self.dimy = len(value[0])
        if value == [[]]:
            self.dimx = 0

    def zero(self, dimx, dimy):
        # check if valid dimensions
        if dimx < 1 or dimy < 1:
            raise ValueError, "Invalid size of Matrix"
        else:
            self.dimx = dimx
            self.dimy = dimy
            self.value = [[0 for row in range(dimy)] for col in range(dimx)]

    def identity(self, dim):
        # check if valid dimension
        if dim < 1:
            raise ValueError, "Invalid size of Matrix"
        else:
            self.dimx = dim
            self.dimy = dim
            self.value = [[0 for row in range(dim)] for col in range(dim)]
            for i in range(dim):
                self.value[i][i] = 1

    def show(self):
        for i in range(self.dimx):
            print self.value[i]
        print ' '

    def __add__(self, other):
        # check if correct dimensions
        if self.dimx != other.dimx or self.dimy != other.dimy:
            raise ValueError, "Matrices must be of equal dimensions to add"
        else:
            # add if correct dimensions
            res = Matrix([[]])
            res.zero(self.dimx, self.dimy)
            for i in range(self.dimx):
                for j in range(self.dimy):
                    res.value[i][j] = self.value[i][j] + other.value[i][j]
            return res

    def __sub__(self, other):
        # check if correct dimensions
        if self.dimx != other.dimx or self.dimy != other.dimy:
            raise ValueError, "Matrices must be of equal dimensions to subtract"
        else:
            # subtract if correct dimensions
            res = Matrix([[]])
            res.zero(self.dimx, self.dimy)
            for i in range(self.dimx):
                for j in range(self.dimy):
                    res.value[i][j] = self.value[i][j] - other.value[i][j]
            return res

    def __mul__(self, other):
        # check if correct dimensions
        if self.dimy != other.dimx:
            raise ValueError, "Matrices must be m*n and n*p to multiply"
        else:
            # subtract if correct dimensions
            res = Matrix([[]])
            res.zero(self.dimx, other.dimy)
            for i in range(self.dimx):
                for j in range(other.dimy):
                    for k in range(self.dimy):
                        res.value[i][j] += self.value[i][k] * other.value[k][j]
            return res

    def transpose(self):
        # compute transpose
        res = Matrix([[]])
        res.zero(self.dimy, self.dimx)
        for i in range(self.dimx):
            for j in range(self.dimy):
                res.value[j][i] = self.value[i][j]
        return res

    # Thanks to Ernesto P. Adorio for use of Cholesky and CholeskyInverse functions

    def Cholesky(self, ztol=1.0e-5):
        # Computes the upper triangular Cholesky factorization of
        # a positive definite Matrix.
        res = Matrix([[]])
        res.zero(self.dimx, self.dimx)

        for i in range(self.dimx):
            S = sum([(res.value[k][i]) ** 2 for k in range(i)])
            d = self.value[i][i] - S
            if abs(d) < ztol:
                res.value[i][i] = 0.0
            else:
                if d < 0.0:
                    raise ValueError, "Matrix not positive-definite"
                res.value[i][i] = sqrt(d)
            for j in range(i + 1, self.dimx):
                S = sum([res.value[k][i] * res.value[k][j] for k in range(self.dimx)])
                if abs(S) < ztol:
                    S = 0.0
                res.value[i][j] = (self.value[i][j] - S) / res.value[i][i]
        return res

    def CholeskyInverse(self):
        # Computes inverse of Matrix given its Cholesky upper Triangular
        # decomposition of Matrix.
        res = Matrix([[]])
        res.zero(self.dimx, self.dimx)

        # Backward step for inverse.
        for j in reversed(range(self.dimx)):
            tjj = self.value[j][j]
            S = sum([self.value[j][k] * res.value[j][k] for k in range(j + 1, self.dimx)])
            res.value[j][j] = 1.0 / tjj ** 2 - S / tjj
            for i in reversed(range(j)):
                res.value[j][i] = res.value[i][j] = -sum(
                    [self.value[i][k] * res.value[k][j] for k in range(i + 1, self.dimx)]) / self.value[i][i]
        return res

    def inverse(self):
        aux = self.Cholesky()
        res = aux.CholeskyInverse()
        return res

    def __repr__(self):
        return repr(self.value)

def kalman_filter(x, P):
    for i in range(len(measurements)):
        # measurement
        Z = Matrix([[measurements[i]]])
        y = Z - (H*x)
        s = H * P * H.transpose() + R
        k = P * H.transpose() * s.inverse()
        x = x + (k * y)
        P = (I - (k*H))*P

        # prediction
        x = F * x +u
        P = F *P *F.transpose()
    return x, P

measurements = [1, 2, 3]

x = Matrix([[0.], [0.]])  # initial state (location and velocity)
P = Matrix([[1000., 0.], [0., 1000.]])  # initial uncertainty
u = Matrix([[0.], [0.]])  # external motion
F = Matrix([[1., 1.], [0, 1.]])  # next state function
H = Matrix([[1., 0.]])  # measurement function
R = Matrix([[1.]])  # measurement uncertainty
I = Matrix([[1., 0.], [0., 1.]])  # identity Matrix

print kalman_filter(x, P)
# output should be:
# x: [[3.9996664447958645], [0.9999998335552873]]
# P: [[2.3318904241194827, 0.9991676099921091], [0.9991676099921067, 0.49950058263974184]]


text:
require 'spec_helper'

module Mock
  module Source
    def path
      '.'
    end
  end
end

describe Space::Source::Command do
  include Mock::Source

  let(:command) { Space::Source::Command.new(self, 'echo "FOO"') }

  # describe 'run' do
  #   subject { command.run }

  #   it 'runs the command' do
  #     should == 'FOO'
  #   end

  #   it 'switches to the context directory' do
  #     Dir.expects(:chdir).with('.').returns('bar')
  #     should == 'bar'
  #   end

  #   it 'clears the bundler env' do
  #     Bundler.expects(:with_clean_env).returns('bar')
  #     should == 'bar'
  #   end

  #   it 'notifies the context about changes' do
  #     subject
  #     events.should include(['echo "FOO"', 'FOO'])
  #   end
  # end
end


text:
#ifndef COIN_SOPICKRAYELEMENT_H
#define COIN_SOPICKRAYELEMENT_H

#include <Inventor/elements/SoSubElement.h>
#include <Inventor/SbViewVolume.h>

class COIN_DLL_API SoPickRayElement : public SoElement {
  typedef SoElement inherited;

  SO_ELEMENT_HEADER(SoPickRayElement);
public:
  static void initClass(void);
protected:
  virtual ~SoPickRayElement();

public:
  virtual void init(SoState * state);

  virtual SbBool matches(const SoElement * element) const;
  virtual SoElement *copyMatchInfo() const;

  static void set(SoState * const state, const SbViewVolume & volume);
  static const SbViewVolume &get(SoState * const state);

protected:
  SbViewVolume volume;
};

#endif // !COIN_SOPICKRAYELEMENT_H


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("@angular/core");
var common_1 = require("@angular/common");
var tables_routing_module_1 = require("./tables-routing.module");
var tables_component_1 = require("./tables.component");
var smartTable_component_1 = require("./smartTable/smartTable.component");
//basice component
var hoverRows_component_1 = require("./hoverRows/hoverRows.component");
var borderedTable_component_1 = require("./borderedTable/borderedTable.component");
var condensedTable_component_1 = require("./condensedTable/condensedTable.component");
var stripedTable_component_1 = require("./stripedTable/stripedTable.component");
var contextualRows_component_1 = require("./contextualRows/contextualRows.component");
var responsiveTable_component_1 = require("./responsiveTable/responsiveTable.component");
//third party component
var ng2_smart_table_1 = require("ng2-smart-table");
//the custom component
var theme_module_1 = require("../../theme/theme.module");
var TablesModule = (function () {
    function TablesModule() {
    }
    return TablesModule;
}());
TablesModule = __decorate([
    core_1.NgModule({
        imports: [
            tables_routing_module_1.TableRoutingModule,
            ng2_smart_table_1.Ng2SmartTableModule,
            theme_module_1.ThemeModule,
            common_1.CommonModule
        ],
        declarations: [
            tables_component_1.TablesComponent,
            smartTable_component_1.SmartTableComponent,
            hoverRows_component_1.HoverRowsComponent,
            borderedTable_component_1.BorderedTableComponent,
            condensedTable_component_1.CondensedTableComponent,
            stripedTable_component_1.StripedTableComponent,
            contextualRows_component_1.ContextualRowsComponent,
            responsiveTable_component_1.ResponsiveTableComponent
        ]
    })
], TablesModule);
exports.TablesModule = TablesModule;
//# sourceMappingURL=E:/Sonicwall/project/Sonicwall_demo/Sonicwall_demo/typescript-angular2-client/app/admin/pages/tables/tables.module.js.map


text:
package com.antew.redditinpictures.library.ui;

import android.net.Uri;
import android.os.Bundle;
import android.support.v13.app.FragmentStatePagerAdapter;
import android.widget.Toast;
import com.antew.redditinpictures.library.adapter.ImgurAlbumPagerAdapter;
import com.antew.redditinpictures.library.event.DownloadImageCompleteEvent;
import com.antew.redditinpictures.library.imgur.ImgurAlbumApi.Album;
import com.antew.redditinpictures.library.imgur.ImgurImageApi.ImgurImage;
import com.antew.redditinpictures.library.service.RedditService;
import com.antew.redditinpictures.library.util.Ln;
import com.antew.redditinpictures.library.util.StringUtil;
import com.antew.redditinpictures.pro.R;
import com.squareup.otto.Subscribe;
import java.util.List;

public class ImgurAlbumActivity extends ImageViewerActivity {
    public static final String TAG         = "ImgurAlbumActivity";
    public static final String EXTRA_ALBUM = "Album";
    private Album mAlbum;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Put the current page / total pages text in the ActionBar
        updateDisplay(mPager.getCurrentItem());
    }

    @Override
    public void getExtras() {
        super.getExtras();
        if (getIntent().hasExtra(EXTRA_ALBUM)) {
            mAlbum = getIntent().getParcelableExtra(EXTRA_ALBUM);
            mImages = mAlbum.getImages();
        }
    }

    @Override
    public FragmentStatePagerAdapter getPagerAdapter() {
        return new ImgurAlbumPagerAdapter(getFragmentManager(), getImages());
    }

    @SuppressWarnings("unchecked")
    protected List<ImgurImage> getImages() {
        return (List<ImgurImage>) mImages;
    }

    @Override
    protected void updateDisplay(int position) {
        getActionBar().setTitle(++position + "/" + getAdapter().getCount() + " - " + getString(R.string.reddit_in_pictures));
    }

    /**
     * Called upon reaching the last page present in the ViewPager
     */
    @Override
    public void reachedCloseToLastPage() {
        //Do nothing.
    }

    /**
     * Get the JSON representation of the current image/post in the ViewPager to report an error.
     *
     * @return The JSON representation of the currently viewed object.
     */
    @Override
    protected void reportCurrentItem() {
        RedditService.reportImage(this, getAdapter().getImage(mPager.getCurrentItem()));
    }

    @Override
    public String getSubreddit() {
        return "ImgurAlbum";
    }

    @Override
    public String getUrlForSharing() {
        ImgurImage image = getAdapter().getImage(mPager.getCurrentItem());
        return image.getLinks().getImgur_page();
    }

    @Override
    protected Uri getPostUri() {
        ImgurImage image = getAdapter().getImage(mPager.getCurrentItem());
        return Uri.parse(image.getLinks().getImgur_page());
    }

    @Override
    public String getFilenameForSave() {
        String name = super.getFilenameForSave();
        if (getAdapter() != null && mPager != null) {
            ImgurImage p = getAdapter().getImage(mPager.getCurrentItem());
            name = p.getImage().getHash();
            if (!p.getImage().getTitle().equals("")) {
                name = StringUtil.sanitizeFileName(p.getImage().getTitle());
            } else if (!p.getImage().getCaption().equals("")) {
                name = StringUtil.sanitizeFileName(p.getImage().getCaption());
            }
        }

        return name;
    }

    @Override
    public void onFinishSaveImageDialog(String filename) {
        ImgurImage image = getAdapter().getImage(mPager.getCurrentItem());
        mImageDownloader.downloadImage(image.getLinks().getOriginal(), filename);
    }

    @Subscribe
    public void onDownloadImageComplete(DownloadImageCompleteEvent event) {
        Ln.i("DownloadImageComplete - filename was: " + event.getFilename());
        Toast.makeText(this, "Post saved as " + event.getFilename(), Toast.LENGTH_SHORT).show();
    }

    private ImgurAlbumPagerAdapter getAdapter() {
        return (ImgurAlbumPagerAdapter) mAdapter;
    }
}