text:
package com.vk.api.sdk.queries.ads;

import com.vk.api.sdk.queries.EnumParam;

/**
 * Created by Anton Tsivarev on 22.09.16.
 */
public enum AdsGetStatisticsPeriod implements EnumParam {

    DAY("day"),
    MONTH("month"),
    OVERALL("overall");

    private final String value;

    AdsGetStatisticsPeriod(String value) {
        this.value = value;
    }

    @Override
    public String getValue() {
        return value;
    }
}


text:
using System;
using System.Globalization;
using Xamarin.Forms;

namespace BabbyJotz {
    public class NumberConverter : IValueConverter {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
            if (value is decimal && targetType == typeof(string)) {
                if ((decimal)value == 0.0m) {
                    return "";
                }
                return String.Format("{0}", value);
            }
            if (value is double && targetType == typeof(string)) {
                if ((double)value == 0.0) {
                    return "";
                }
                return String.Format("{0}", value);
            }
            if (value is TimeSpan && targetType == typeof(string)) {
                if (((TimeSpan)value).TotalMinutes == 0.0) {
                    return "";
                }
                return String.Format("{0}", ((TimeSpan)value).TotalMinutes);
            }
            throw new InvalidOperationException();
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
            if (value is string && targetType == typeof(decimal)) {
                var result = 0.0m;
                Decimal.TryParse((string)value, out result);
                return result;
            }
            if (value is string && targetType == typeof(double)) {
                var result = 0.0;
                Double.TryParse((string)value, out result);
                return result;
            }
            if (value is string && targetType == typeof(TimeSpan)) {
                var result = 0.0;
                Double.TryParse((string)value, out result);
                return TimeSpan.FromMinutes(result);
            }
            throw new InvalidOperationException();
        }
    }
}

redpajama_set_name: RedPajamaGithub


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

namespace ShoppingList.ApiServices.SharedModels
{
    public class BillingDescriptor
    {
        public string Name { get; set; }
        public string City { get; set; }
    }
}


text:
module Brcobranca
  module Boleto
    class Sicoob < Base # Sicoob (Bancoob)
      validates_length_of :agencia, maximum: 4, message: 'deve ser menor ou igual a 4 dígitos.'
      validates_length_of :conta_corrente, maximum: 8, message: 'deve ser menor ou igual a 8 dígitos.'
      validates_length_of :numero_documento, maximum: 7, message: 'deve ser menor ou igual a 7 dígitos.'
      validates_length_of :convenio, maximum: 7, message: 'deve ser menor ou igual a 7 dígitos.'
      validates_length_of :variacao, maximum: 2, message: 'deve ser menor ou igual a 2 dígitos.'
      validates_length_of :quantidade, maximum: 3, message: 'deve ser menor ou igual a 3 dígitos.'

      def initialize(campos = {})
        campos = { carteira: '1', variacao: '01', quantidade: '001' }.merge!(campos)
        super(campos)
      end

      # Codigo do banco emissor (3 dígitos sempre)
      #
      # @return [String] 3 caracteres numéricos.
      def banco
        '756'
      end

      # Dígito verificador do banco
      #
      # @return [String] 1 caractere.
      def banco_dv
        '0'
      end

      # Agência
      #
      # @return [String] 4 caracteres numéricos.
      def agencia=(valor)
        @agencia = valor.to_s.rjust(4, '0') if valor
      end

      # Convênio
      #
      # @return [String] 7 caracteres numéricos.
      def convenio=(valor)
        @convenio = valor.to_s.rjust(7, '0') if valor
      end

      # Número documento
      #
      # @return [String] 7 caracteres numéricos.
      def numero_documento=(valor)
        @numero_documento = valor.to_s.rjust(7, '0') if valor
      end

      # Quantidade
      #
      # @return [String] 3 caracteres numéricos.
      def quantidade=(valor)
        @quantidade = valor.to_s.rjust(3, '0') if valor
      end

      # Nosso número para exibição no boleto.
      #
      # @return [String] 8 caracteres numéricos.
      def nosso_numero_boleto
        dv_nosso_numero = Brcobranca::Util::Sicoob.calcule_dv_nosso_numero agencia, convenio, numero_documento

        "#{numero_documento}#{dv_nosso_numero}"
      end

      def agencia_conta_boleto
        "#{agencia} / #{convenio}"
      end

      # Posição     Tamanho     Conteúdo
      #    20 a 20      01                 Código da carteira de cobrança - vide planilha "Capa" deste arquivo
      #    21 a 24      04                 Código da agência/cooperativa - verificar na planilha "Capa" deste arquivo
      #    25 a 26      02                 Código da modalidade - verificar na planilha "Capa" deste arquivo
      #    27 a 33      07                 Código do cedente/cliente - verificar na planilha "Capa" deste arquivo
      #    34 a 41      08                 Nosso número do boleto
      #    41 a 44      03                 Número da parcela a que o boleto se refere - "001" se parcela única
      def codigo_barras_segunda_parte
        "#{carteira}#{agencia}#{variacao}#{convenio}#{nosso_numero_boleto}#{quantidade}"
      end
    end
  end
end


text:
//
//    Copyright(C) 2015  Elanna Stephenson
//
//    This software is released under the MIT license, see LICENSE for details.
//

using System;

namespace SCSRaytracer
{
    class DebugCheckerboard : PhongShader
    {

        public override RGBColor Shade(ShadeRec sr)
        {
            RGBColor multiplar = base.Shade(sr);
            float scalefactor;
            if(Math.Abs(sr.HitPoint.X) % 50 < 25 && Math.Abs(sr.HitPoint.Z) % 50 > 25)
            {
                scalefactor = 0.1f;
            }
            else
            {
                scalefactor = 1.0f;
            }
            return scalefactor * multiplar;
        }
    }
}


text:
The Docker container contains [RedPen][intro] server environment.

## Simple Usage

If you only try redpen-server, you can use trusted builds registered [Docker index][di],

    docker pull ainoya/redpen-server

## Deploying

* Run `docker build -t redpen-server`
* Run `docker run -d redpen-server`

## Running

Another example of running redpen-server is:

    docker run -d -t --name redpen-server \
                -e REDPEN_HOME /redpen-server \
                -p 49022:22 \
                -p 8080:8080 redpen-server

After a few minutes, you can access redpen-server:

    open http://localhost:8080/redpen-server

You can ssh to container as root, using password:`redpen`

    ssh root@localhost -p 49022 #The password is "redpen".

## Contributing

Once you've made your great commits:

1. [Fork][fk] docker-redpen
2. Create your feature branch (``git checkout -b my-new-feature``)
3. Write tests
4. Run tests with ``rake test``
5. Commit your changes (``git commit -am 'Added some feature'``)
6. Push to the branch (``git push origin my-new-feature``)
7. Create new pull request
8. That's it!

## Resources

RedPen is a tool to help writers or programmers who write technical documents or manuals that need to adhere to a writing standard.

* [Introduction page][intro]
* [Redpen repo][repo]

[fk]: http://help.github.com/forking/
[intro]: http://redpen.bigram.org/
[repo]: https://github.com/recruit-tech/redpen
[di]: https://index.docker.io/u/ainoya/redpen-server/


text:
namespace clotho {
namespace configuration_manager {

class config_manager {
public:
    typedef std::map< std::string, iconfigurable * > object_map;
    typedef typename object_map::iterator object_iterator;

    static config_manager * getInstance();
    config_manager();

    void register_configurable( iconfigurable * obj );
    void unregister_configurable( const std::string & n );

    int parse_commandline( int argc, char ** argv );
    int parse_commandline( int argc, char ** argv, po::variables_map & vm );

    virtual ~config_manager();
protected:
    object_map m_configs;
};

}   // namespace configuration_manager
}   // namespace clotho

#endif  // CONFIG_MANAGER_HPP_


text:
package cmd

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strings"

	kapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl"
	cmdutil "github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd/util"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/resource"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
	"github.com/spf13/cobra"

	//ocutil "github.com/openshift/origin/pkg/cmd/util"

	"github.com/openshift/origin/pkg/cmd/util/clientcmd"
)

const (
	envLong = `Update the environment on a pod

Each container in a pod may have its own environment variable definitions. This command can
add, update, or remove environment variables from containers in pods or any object that has
a pod template (replication controllers or deployment configurations). You can specify a
single object or multiple, and alter environment on all containers or just those that match
a wildcard.

If "--env -" is passed, environment variables can be read from STDIN using the standard env
syntax.`

	envExample = `  // Update deployment 'registry' with a new environment variable
  $ %[1]s env dc/registry STORAGE_DIR=/local

  // List the environment variables defined on a deployment 'registry'
  $ %[1]s env dc/registry --list

  // List the environment variables defined on all pods
  $ %[1]s env pods --all --list

  // Output a YAML object with updated enviroment for deployment 'registry'
  // Does not alter the object on the server
  $ %[1]s env dc/registry STORAGE_DIR=/local -o yaml

  // Update all replication controllers in the project to have ENV=prod
  $ %[1]s env replicationControllers --all ENV=prod

  // Remove the enviroment variable ENV from all deployment configs
  $ %[1]s env deploymentConfigs --all ENV-

  // Remove the enviroment variable ENV from a pod definition on disk and update the pod on the server
  $ %[1]s env -f pod.json ENV-

  // Set some of the local shell environment into a deployment on the server
  $ env | grep RAILS_ | %[1]s env -e - dc/registry`
)

func NewCmdEnv(fullName string, f *clientcmd.Factory, in io.Reader, out io.Writer) *cobra.Command {
	var filenames util.StringList
	var env util.StringList
	cmd := &cobra.Command{
		Use:     "env RESOURCE/NAME KEY_1=VAL_1 ... KEY_N=VAL_N [options]",
		Short:   "Update the environment on a resource with a pod template",
		Long:    envLong,
		Example: fmt.Sprintf(envExample, fullName),
		Run: func(cmd *cobra.Command, args []string) {
			err := RunEnv(f, in, out, cmd, args, env, filenames)
			if err == errExit {
				os.Exit(1)
			}
			cmdutil.CheckErr(err)
		},
	}
	cmd.Flags().StringP("containers", "c", "*", "The names of containers in the selected pod templates to change - may use wildcards")
	cmd.Flags().VarP(&env, "env", "e", "Specify key value pairs of environment variables to set into each container.")
	cmd.Flags().Bool("list", false, "Display the environment and any changes in the standard format")
	cmd.Flags().StringP("selector", "l", "", "Selector (label query) to filter on")
	cmd.Flags().Bool("all", false, "select all resources in the namespace of the specified resource types")
	cmd.Flags().VarP(&filenames, "filename", "f", "Filename, directory, or URL to file to use to edit the resource.")
	cmd.Flags().Bool("overwrite", true, "If true, allow environment to be overwritten, otherwise reject updates that overwrite existing environment.")
	cmd.Flags().String("resource-version", "", "If non-empty, the labels update will only succeed if this is the current resource-version for the object. Only valid when specifying a single resource.")
	cmd.Flags().StringP("output", "o", "", "Display the changed objects instead of updating them. One of: json|yaml.")
	cmd.Flags().String("output-version", "", "Output the changed objects with the given version (default api-version).")
	return cmd
}

func updateObject(info *resource.Info, updateFn func(runtime.Object) (runtime.Object, error)) (runtime.Object, error) {
	helper := resource.NewHelper(info.Client, info.Mapping)

	obj, err := updateFn(info.Object)
	if err != nil {
		return nil, err
	}
	data, err := helper.Codec.Encode(obj)
	if err != nil {
		return nil, err
	}

	_, err = helper.Update(info.Namespace, info.Name, true, data)
	if err != nil {
		return nil, err
	}
	return obj, nil
}

func validateNoOverwrites(meta *kapi.ObjectMeta, labels map[string]string) error {
	for key := range labels {
		if value, found := meta.Labels[key]; found {
			return fmt.Errorf("'%s' already has a value (%s), and --overwrite is false", key, value)
		}
	}
	return nil
}

func parseEnv(spec []string, defaultReader io.Reader) ([]kapi.EnvVar, []string, error) {
	env := []kapi.EnvVar{}
	exists := util.NewStringSet()
	var remove []string
	for _, envSpec := range spec {
		switch {
		case envSpec == "-":
			if defaultReader == nil {
				return nil, nil, fmt.Errorf("when '-' is used, STDIN must be open")
			}
			fileEnv, err := readEnv(defaultReader)
			if err != nil {
				return nil, nil, err
			}
			env = append(env, fileEnv...)
		case strings.Index(envSpec, "=") != -1:
			parts := strings.SplitN(envSpec, "=", 2)
			if len(parts) != 2 {
				return nil, nil, fmt.Errorf("invalid environment variable: %v", envSpec)
			}
			exists.Insert(parts[0])
			env = append(env, kapi.EnvVar{
				Name:  parts[0],
				Value: parts[1],
			})
		case strings.HasSuffix(envSpec, "-"):
			remove = append(remove, envSpec[:len(envSpec)-1])
		default:
			return nil, nil, fmt.Errorf("unknown environment variable: %v", envSpec)
		}
	}
	for _, removeLabel := range remove {
		if _, found := exists[removeLabel]; found {
			return nil, nil, fmt.Errorf("can not both modify and remove an environment variable in the same command")
		}
	}
	return env, remove, nil
}

func readEnv(r io.Reader) ([]kapi.EnvVar, error) {
	env := []kapi.EnvVar{}
	scanner := bufio.NewScanner(r)
	for scanner.Scan() {
		envSpec := scanner.Text()
		if pos := strings.Index(envSpec, "#"); pos != -1 {
			envSpec = envSpec[:pos]
		}
		if strings.Index(envSpec, "=") != -1 {
			parts := strings.SplitN(envSpec, "=", 2)
			if len(parts) != 2 {
				return nil, fmt.Errorf("invalid environment variable: %v", envSpec)
			}
			env = append(env, kapi.EnvVar{
				Name:  parts[0],
				Value: parts[1],
			})
		}
	}
	if err := scanner.Err(); err != nil && err != io.EOF {
		return nil, err
	}
	return env, nil
}

func RunEnv(f *clientcmd.Factory, in io.Reader, out io.Writer, cmd *cobra.Command, args []string, envParams, filenames util.StringList) error {
	resources, envArgs := []string{}, []string{}
	first := true
	for _, s := range args {
		isEnv := strings.Contains(s, "=") || strings.HasSuffix(s, "-")
		switch {
		case first && isEnv:
			first = false
			fallthrough
		case !first && isEnv:
			envArgs = append(envArgs, s)
		case first && !isEnv:
			resources = append(resources, s)
		case !first && !isEnv:
			return cmdutil.UsageError(cmd, "all resources must be specified before environment changes: %s", s)
		}
	}
	if len(resources) < 1 {
		return cmdutil.UsageError(cmd, "one or more resources must be specified as <resource> <name> or <resource>/<name>")
	}

	containerMatch := cmdutil.GetFlagString(cmd, "containers")
	list := cmdutil.GetFlagBool(cmd, "list")
	selector := cmdutil.GetFlagString(cmd, "selector")
	all := cmdutil.GetFlagBool(cmd, "all")
	//overwrite := cmdutil.GetFlagBool(cmd, "overwrite")
	resourceVersion := cmdutil.GetFlagString(cmd, "resource-version")
	outputFormat := cmdutil.GetFlagString(cmd, "output")

	if list && len(outputFormat) > 0 {
		return cmdutil.UsageError(cmd, "--list and --output may not be specified together")
	}

	clientConfig, err := f.ClientConfig()
	if err != nil {
		return err
	}
	outputVersion := cmdutil.OutputVersion(cmd, clientConfig.Version)

	cmdNamespace, err := f.DefaultNamespace()
	if err != nil {
		return err
	}

	env, remove, err := parseEnv(append(envParams, envArgs...), in)
	if err != nil {
		return err
	}

	mapper, typer := f.Object()
	b := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()).
		ContinueOnError().
		NamespaceParam(cmdNamespace).DefaultNamespace().
		FilenameParam(filenames...).
		SelectorParam(selector).
		ResourceTypeOrNameArgs(all, resources...).
		Flatten()

	one := false
	infos, err := b.Do().IntoSingular(&one).Infos()
	if err != nil {
		return err
	}

	// only apply resource version locking on a single resource
	if !one && len(resourceVersion) > 0 {
		return cmdutil.UsageError(cmd, "--resource-version may only be used with a single resource")
	}

	skipped := 0
	for _, info := range infos {
		ok, err := f.UpdatePodSpecForObject(info.Object, func(spec *kapi.PodSpec) error {
			containers := selectContainers(spec.Containers, containerMatch)
			if len(containers) == 0 {
				fmt.Fprintf(cmd.Out(), "warning: %s/%s does not have any containers matching %q\n", info.Mapping.Resource, info.Name, containerMatch)
				return nil
			}
			for _, c := range containers {
				c.Env = updateEnv(c.Env, env, remove)

				if list {
					fmt.Fprintf(out, "# %s %s, container %s\n", info.Mapping.Resource, info.Name, c.Name)
					for _, env := range c.Env {
						// if env.ValueFrom != nil && env.ValueFrom.FieldRef != nil {
						// 	fmt.Fprintf(cmd.Out(), "%s= # calculated from pod %s %s\n", env.Name, env.ValueFrom.FieldRef.FieldPath, env.ValueFrom.FieldRef.APIVersion)
						// 	continue
						// }
						fmt.Fprintf(out, "%s=%s\n", env.Name, env.Value)

					}
				}
			}
			return nil
		})
		if !ok {
			skipped++
			continue
		}
		if err != nil {
			fmt.Fprintf(cmd.Out(), "error: %s/%s %v\n", info.Mapping.Resource, info.Name, err)
			continue
		}
	}
	if one && skipped == len(infos) {
		return fmt.Errorf("the %s %s is not a pod or does not have a pod template", infos[0].Mapping.Resource, infos[0].Name)
	}

	if list {
		return nil
	}

	objects, err := resource.AsVersionedObject(infos, false, outputVersion)
	if err != nil {
		return err
	}

	if len(outputFormat) != 0 {
		p, _, err := kubectl.GetPrinter(outputFormat, "")
		if err != nil {
			return err
		}
		return p.PrintObj(objects, out)
	}

	failed := false
	for _, info := range infos {
		data, err := info.Mapping.Codec.Encode(info.Object)
		if err != nil {
			fmt.Fprintf(cmd.Out(), "Error: %v\n", err)
			failed = true
			continue
		}
		obj, err := resource.NewHelper(info.Client, info.Mapping).Update(info.Namespace, info.Name, true, data)
		if err != nil {
			handleUpdateError(cmd.Out(), err)
			failed = true
			continue
		}
		info.Refresh(obj, true)
		fmt.Fprintf(out, "%s/%s\n", info.Mapping.Resource, info.Name)
	}
	if failed {
		return errExit
	}
	return nil
}

func updateEnv(existing []kapi.EnvVar, env []kapi.EnvVar, remove []string) []kapi.EnvVar {
	out := []kapi.EnvVar{}
	covered := util.NewStringSet(remove...)
	for _, e := range existing {
		if covered.Has(e.Name) {
			continue
		}
		newer, ok := findEnv(env, e.Name)
		if ok {
			covered.Insert(e.Name)
			out = append(out, newer)
			continue
		}
		out = append(out, e)
	}
	for _, e := range env {
		if covered.Has(e.Name) {
			continue
		}
		covered.Insert(e.Name)
		out = append(out, e)
	}
	return out
}

func findEnv(env []kapi.EnvVar, name string) (kapi.EnvVar, bool) {
	for _, e := range env {
		if e.Name == name {
			return e, true
		}
	}
	return kapi.EnvVar{}, false
}

func selectContainers(containers []kapi.Container, spec string) []*kapi.Container {
	out := []*kapi.Container{}
	for i, c := range containers {
		if selectString(c.Name, spec) {
			out = append(out, &containers[i])
		}
	}
	return out
}

// selectString returns true if the provided string matches spec, where spec is a string with
// a non-greedy '*' wildcard operator.
// TODO: turn into a regex and handle greedy matches and backtracking.
func selectString(s, spec string) bool {
	if spec == "*" {
		return true
	}
	if !strings.Contains(spec, "*") {
		return s == spec
	}

	pos := 0
	match := true
	parts := strings.Split(spec, "*")
	for i, part := range parts {
		if len(part) == 0 {
			continue
		}
		next := strings.Index(s[pos:], part)
		switch {
		// next part not in string
		case next < pos:
			fallthrough
		// first part does not match start of string
		case i == 0 && pos != 0:
			fallthrough
		// last part does not exactly match remaining part of string
		case i == (len(parts)-1) && len(s) != (len(part)+next):
			match = false
			break
		default:
			pos = next
		}
	}
	return match
}

func handleUpdateError(out io.Writer, err error) {
	errored := false
	if statusError, ok := err.(*errors.StatusError); ok && errors.IsInvalid(err) {
		errorDetails := statusError.Status().Details
		if errorDetails.Kind == "Pod" {
			for _, cause := range errorDetails.Causes {
				if cause.Field == "spec" && strings.Contains(cause.Message, "may not update fields other than") {
					fmt.Fprintf(out, "Error updating pod %q: may not update environment variables in a pod directly\n", errorDetails.ID)
					errored = true
					break
				}
			}
		}
	}

	if !errored {
		fmt.Fprintf(out, "Error: %v\n", err)
	}
}


text:
'use strict';

/* global JuttleAdapterAPI */
let StaticFilterCompiler = JuttleAdapterAPI.compiler.StaticFilterCompiler;
let errors = JuttleAdapterAPI.errors;

class FilterOpenTSDBCompiler extends StaticFilterCompiler {

    constructor(query) {
        super();
        this.query = query;
    }
    compile(node) {
        return this.visit(node, this.query);
    }
    visitBinaryExpression(node, query) {
        //XXX The latest stable release v2.1 does not support complex filter expressions:
        //  http://opentsdb.net/docs/build/html/user_guide/query/filters.html

        if (node.operator === 'AND') {
            this.visit(node.left, query);
            return this.visit(node.right, query);
        } else if (node.operator === '==') {
            return this.handleEqualOperator(node, query);
        }

        this.featureNotSupported();
    }

    handleEqualOperator(node, query) {
        let left = this.visit(node.left);
        if (left === 'name') {
            return query.metric(this.visit(node.right));
        } else {
            return query.tags(left, this.visit(node.right));
        }
    }

    visitStringLiteral(node) {
        return String(node.value);
    }
    visitField(node) {
        return node.name;
    }
    featureNotSupported() {
        throw new errors.compileError('TYPE-ERROR', {
            message: "Only AND and '=' operators with string values are supported in the optimized filter expression."
        });
    }

}

module.exports = FilterOpenTSDBCompiler;


text:
require 'rubygems'
require 'bundler'
Bundler.setup

require 'shoulda'
require 'mocha'
require 'net/http'
require 'httpclient'
require 'open-uri'
require 'fakeweb'
require 'webrick'

require 'samuel'

FakeWeb.allow_net_connect = false

class Test::Unit::TestCase
  TEST_LOG_PATH = File.join(File.dirname(__FILE__), 'test.log')

  def self.should_log_lines(expected_count)
    should "log #{expected_count} line#{'s' unless expected_count == 1}" do
      lines = File.readlines(TEST_LOG_PATH)
      assert_equal expected_count, lines.length
    end
  end

  def self.should_log_including(what)
    should "log a line including #{what.inspect}" do
      contents = File.read(TEST_LOG_PATH)
      if what.is_a?(Regexp)
        assert_match what, contents
      else
        assert contents.include?(what),
               "Expected #{contents.inspect} to include #{what.inspect}"
      end
    end
  end

  def self.should_log_at_level(level)
    level = level.to_s.upcase
    should "log at the #{level} level" do
      assert File.read(TEST_LOG_PATH).include?("  #{level} -- :")
    end
  end

  def self.should_raise_exception(klass)
    should "raise an #{klass} exception" do
      @exception = nil if !defined?(@exception)
      assert @exception.is_a?(klass)
    end
  end

  def self.should_have_config_afterwards_including(config)
    config.each_pair do |key, value|
      should "continue afterwards with Samuel.config[#{key.inspect}] set to #{value.inspect}" do
        assert_equal value, Samuel.config[key]
      end
    end
  end

  # The path to the current ruby interpreter. Adapted from Rake's FileUtils.
  def ruby_path
    ext = ((RbConfig::CONFIG['ruby_install_name'] =~ /\.(com|cmd|exe|bat|rb|sh)$/) ? "" : RbConfig::CONFIG['EXEEXT'])
    File.join(RbConfig::CONFIG['bindir'], RbConfig::CONFIG['ruby_install_name'] + ext).sub(/.*\s.*/m, '"\&"')
  end

  def setup_test_logger
    FileUtils.rm_rf TEST_LOG_PATH
    FileUtils.touch TEST_LOG_PATH
    Samuel.logger = Logger.new(TEST_LOG_PATH)
  end

  def teardown_test_logger
    FileUtils.rm_rf TEST_LOG_PATH
  end

  def start_test_server
    return if defined?(@@server)

    @@server = WEBrick::HTTPServer.new(
      :Port => 8000, :AccessLog => [],
      :Logger => WEBrick::Log.new(nil, WEBrick::BasicLog::WARN)
    )
    @@server.mount "/", ResponseCodeServer
    at_exit { @@server.shutdown }
    Thread.new { @@server.start }
  end
end

class ResponseCodeServer < WEBrick::HTTPServlet::AbstractServlet
  def do_GET(request, response)
    response_code = request.query_string.nil? ? 200 : request.query_string.to_i
    response.status = response_code
  end
  alias_method :do_POST,   :do_GET
  alias_method :do_PUT,    :do_GET
  alias_method :do_DELETE, :do_GET
end


text:
using System;

namespace netDxf.Entities
{
    /// <summary>
    /// Represents datum reference, a theoretically exact point, axis, or plane from which you make measurements and verify dimensions.
    /// </summary>
    public class DatumReferenceValue :
        ICloneable
    {
        #region private fields

        private string datum;
        private ToleranceMaterialCondition materialCondition;

        #endregion

        #region constructors

        /// <summary>
        /// Initializes a new instance of the <c>DatumReferenceValue</c> class.
        /// </summary>
        public DatumReferenceValue()
        {
            this.datum = string.Empty;
            this.materialCondition = ToleranceMaterialCondition.None;
        }

        /// <summary>
        /// Initializes a new instance of the <c>DatumReferenceValue</c> class.
        /// </summary>
        /// <param name="value">Datum reference value.</param>
        /// <param name="materialCondition">Datum material condition.</param>
        public DatumReferenceValue(string value, ToleranceMaterialCondition materialCondition)
        {
            this.datum = value;
            this.materialCondition = materialCondition;
        }

        #endregion

        #region public properties

        /// <summary>
        /// Gets or sets the datum value.
        /// </summary>
        public string Value
        {
            get { return this.datum; }
            set { this.datum = value; }
        }

        /// <summary>
        /// Gets or sets the datum material condition.
        /// </summary>
        public ToleranceMaterialCondition MaterialCondition
        {
            get { return this.materialCondition; }
            set { this.materialCondition = value; }
        }

        #endregion

        #region ICloneable

        /// <summary>
        /// Creates a new DatumReferenceValue that is a copy of the current instance.
        /// </summary>
        /// <returns>A new DatumReferenceValue that is a copy of this instance.</returns>
        public object Clone()
        {
            return new DatumReferenceValue
            {
                Value = this.datum,
                MaterialCondition = this.materialCondition
            };
        }

        #endregion
    }
}


text:
keep track of all the active queries from a request to route live updates

[![build status](https://secure.travis-ci.org/substack/level-track.png)](http://travis-ci.org/substack/level-track)

# example

In this example we'll subscribe to the range of keys `"f"` through `"p"` and the
singular key `"c"`. The database is then populated with random keys and values
to show that only keys `"f"` through `"p"` inclusive and `"c"` are captured.

``` js
var sub = require('level-sublevel');
var db = sub(require('level')('test.db'));
var tracker = require('level-track')(db);
var through = require('through');

var t = tracker();
t.pipe(process.stdout);

t.write('"c"\n');
t.write('["f","p"]\n');

setInterval(function () {
    var l = Math.floor(Math.random() * 2) + 1;
    var key = '';
    for (var i = 0; i < l; i++) {
        key += String.fromCharCode(Math.random() * 26 + 97);
    }
    db.put(key, { n: Math.floor(Math.random() * 100) });
}, 250);
```

output:

```
{"type":"put","key":"jr","value":{"n":92}}
{"type":"put","key":"ft","value":{"n":41}}
{"type":"put","key":"g","value":{"n":32}}
{"type":"put","key":"c","value":{"n":55}}
{"type":"put","key":"kh","value":{"n":60}}
{"type":"put","key":"m","value":{"n":43}}
{"type":"put","key":"p","value":{"n":40}}
{"type":"put","key":"nc","value":{"n":64}}
{"type":"put","key":"l","value":{"n":70}}
{"type":"put","key":"fy","value":{"n":41}}
{"type":"put","key":"kp","value":{"n":98}}
{"type":"put","key":"mk","value":{"n":48}}
{"type":"put","key":"h","value":{"n":27}}
^C
```

# protocol

The tracking protocol is newline-delimited json.
Each line should match one of these formats:

## "key"

Receive updates from a single key.

## ["startkey","endkey"]

Receive updates from the range `"startkey"` through `"endkey"`, inclusive.

## ["startkey","endkey","sincekey"]

Receive updates from the range `"startkey"` through `"endkey"`, inclusive and
populate the result stream with data from the exclusive `"sincekey"` through
`"endkey"`.

This form is useful so that no updates slip past due to delays from rendering
the initial content and establishing a live connection.

# methods

``` js
var tracker = require('level-track')
```

## var t = tracker(opts)

Return a duplex stream that expects
input of the form documented in the protocol section and produces output of the
form:

``` json
{"type":"put","key":"h","value":{"n":27}}
```

which is the same format that `db.hooks` and `db.batch()` use.

When `opts.objectMode` is true, output is written as objects. Otherwise, output
is written as newline-delimited lines of json.

You may also specify an optional `opts.keyMap(key)` function to pre-transform
keys. Return the value you want to use for the key.

# install

With [npm](https://npmjs.org) do:

```
npm install level-tracker
```

# license

MIT


text:
module.exports = function (db) {
    db.Country.bulkCreate([
        { code: 'FR', name: 'France' },
        { code: 'US', name: 'United States' },
        { code: 'PT', name: 'Portugal' }
    ]).then(function () {
        return db.Department.bulkCreate([
            { code: '03', name: 'Allier', region: '1' },
            { code: '83', name: 'Var', region: '1' },
            { code: '06', name: 'Hautes-Alpes', region: '1' }
        ])
    }).then(function () {
        return db.Address.bulkCreate([
            { address1: 'Rue des Oliviers', address2: 'La Maisonette', zipCode: '03220', city: 'Trezelles', departmentId: 1, countryId: 1 },
            { address1: 'Avenue des Bozo', address2: 'Rouberre', zipCode: '83521', city: 'Vieilloles', departmentId: 2, countryId: 1 },
            { address1: '1415 E Denny Way', address2: 'Capitol Hill', zipCode: '98122', city: 'Seattle', state: 'WA', countryId: 2 }
        ])
    }).then(function () {
        return db.User.bulkCreate([
            { email: 'plop@plop.com', passwordHash: 'thisisnotarealhash', firstName: 'Bob', lastName: 'Dylan', birthDate: '1989-06-25 04:15:10', phone: '206-012-3465', isAdmin: false },
            { email: 'host@foo.com', passwordHash: '64faf5d0b1dc311fd0f94af64f6c296a03045571', firstName: 'Jean', lastName: 'Bon', birthDate: '1977-02-08 04:15:10', phone: '206-012-3465', isAdmin: false },
            { email: 'wwoofer@foo.com', passwordHash: '64faf5d0b1dc311fd0f94af64f6c296a03045571', firstName: 'Helen', lastName: 'Polmino', birthDate: '1984-10-10 10:10:25', phone: '206-012-3465', isAdmin: false },
            { email: 'admin@foo.com', passwordHash: '64faf5d0b1dc311fd0f94af64f6c296a03045571', firstName: 'Super', lastName: 'Admin', birthDate: '1974-08-03 02:45:25', phone: '206-012-3465', isAdmin: true }
        ])
    }).then(function () {
        return db.Host.bulkCreate([
            { farmName: 'La Belle Ferme', shortDescription: 'Ferme Bio dans le marais', fullDescription: 'Une description complete prendrait trop de place.', webSite: 'http://pouet.com', travelDetails: 'On vient vous prendre a la gare y\' pas sourcis!', isPending: false, isSuspended: false, addressId: 1, userId: 1 },
            { farmName: 'La Grange Verte', shortDescription: 'Ferme de fromages bio!', fullDescription: 'Encore un fois, une description complete prendrait trop de place.', webSite: 'http://plop.com', travelDetails: 'On vient vous prendre a la gare y\' pas sourcis!', isPending: false, isSuspended: false, addressId: 2, userId: 2 }
        ])
    }).then(function () {
        return db.Photo.bulkCreate([
            { fileName: 'maison.jpg', caption: 'Photo de Maison', hostId: 1 },
            { fileName: 'arbre.jpg', caption: 'Ceci est un arbre', hostId: 1 },
            { fileName: 'farm.jpg', caption: 'This is a farm', hostId: 1 }
        ])
    }).then(function () {
        return db.Wwoofer.bulkCreate([
            { firstName2: 'Another', lastName2: 'Name', birthDate2: '1985-03-24 18:15:10', nationality: 'FR', intro: 'I\'m a believer!', tripMotivation: 'Je veux apprendre a faire du fromage!', addressId: 3, userId: 3 }
        ])
    }).then(function () {
        return db.Membership.bulkCreate([
            { type: 'H', paymentId: '123', payerId: '456', saleId: '789', expireAt: '2015-06-25 04:15:10', itemCode: 'H', paymentType: 'PPL', total: 25, userId: 2 },
            { type: 'H', paymentId: '123', payerId: '456', saleId: '789', expireAt: '2016-06-25 04:15:10', itemCode: 'HR', paymentType: 'PPL', total: 25, userId: 2 }
        ])
    });
};


text:
#pragma once

#include <platform/ConnectivityManager.h>
#include <platform/internal/GenericConnectivityManagerImpl.h>
#include <platform/internal/GenericConnectivityManagerImpl_UDP.h>

#if INET_CONFIG_ENABLE_TCP_ENDPOINT
#include <platform/internal/GenericConnectivityManagerImpl_TCP.h>
#endif

#if CHIP_DEVICE_CONFIG_ENABLE_WIFI
#include <platform/internal/GenericConnectivityManagerImpl_WiFi.h>
#else
#include <platform/internal/GenericConnectivityManagerImpl_NoWiFi.h>
#endif

#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
#include <platform/internal/GenericConnectivityManagerImpl_Thread.h>
#else
#include <platform/internal/GenericConnectivityManagerImpl_NoThread.h>
#endif

#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
#include <platform/internal/GenericConnectivityManagerImpl_BLE.h>
#else
#include <platform/internal/GenericConnectivityManagerImpl_NoBLE.h>
#endif

#include <lib/support/BitFlags.h>

#include <wifi_conf.h>

namespace chip {

namespace Inet {
class IPAddress;
} // namespace Inet

namespace DeviceLayer {

class PlatformManagerImpl;

class ConnectivityManagerImpl final : public ConnectivityManager,
                                      public Internal::GenericConnectivityManagerImpl<ConnectivityManagerImpl>,
                                      public Internal::GenericConnectivityManagerImpl_UDP<ConnectivityManagerImpl>,
#if INET_CONFIG_ENABLE_TCP_ENDPOINT
                                      public Internal::GenericConnectivityManagerImpl_TCP<ConnectivityManagerImpl>,
#endif
#if CHIP_DEVICE_CONFIG_ENABLE_WIFI
                                      public Internal::GenericConnectivityManagerImpl_WiFi<ConnectivityManagerImpl>,
#else
                                      public Internal::GenericConnectivityManagerImpl_NoWiFi<ConnectivityManagerImpl>,
#endif
#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
                                      public Internal::GenericConnectivityManagerImpl_BLE<ConnectivityManagerImpl>,
#else
                                      public Internal::GenericConnectivityManagerImpl_NoBLE<ConnectivityManagerImpl>,
#endif
#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
                                      public Internal::GenericConnectivityManagerImpl_Thread<ConnectivityManagerImpl>
#else
                                      public Internal::GenericConnectivityManagerImpl_NoThread<ConnectivityManagerImpl>
#endif
{
    // Allow the ConnectivityManager interface class to delegate method calls to
    // the implementation methods provided by this class.
    friend class ConnectivityManager;

private:
    CHIP_ERROR _Init(void);
    void _OnPlatformEvent(const ChipDeviceEvent * event);

#if CHIP_DEVICE_CONFIG_ENABLE_WIFI
    using Flags = GenericConnectivityManagerImpl_WiFi::ConnectivityFlags;
    // ===== Members that implement the ConnectivityManager abstract interface.

    WiFiStationMode _GetWiFiStationMode(void);
    CHIP_ERROR _SetWiFiStationMode(WiFiStationMode val);
    bool _IsWiFiStationEnabled(void);
    bool _IsWiFiStationApplicationControlled(void);
    bool _IsWiFiStationConnected(void);
    System::Clock::Timeout _GetWiFiStationReconnectInterval(void);
    CHIP_ERROR _SetWiFiStationReconnectInterval(System::Clock::Timeout val);
    bool _IsWiFiStationProvisioned(void);
    void _ClearWiFiStationProvision(void);
    WiFiAPMode _GetWiFiAPMode(void);
    CHIP_ERROR _SetWiFiAPMode(WiFiAPMode val);
    bool _IsWiFiAPActive(void);
    bool _IsWiFiAPApplicationControlled(void);
    void _DemandStartWiFiAP(void);
    void _StopOnDemandWiFiAP(void);
    void _MaintainOnDemandWiFiAP(void);
    System::Clock::Timeout _GetWiFiAPIdleTimeout(void);
    void _SetWiFiAPIdleTimeout(System::Clock::Timeout val);
    CHIP_ERROR _GetAndLogWiFiStatsCounters(void);
    bool _CanStartWiFiScan();
    void _OnWiFiScanDone();
    void _OnWiFiStationProvisionChange();

    // ===== Private members reserved for use by this class only.

    System::Clock::Timestamp mLastStationConnectFailTime;
    System::Clock::Timestamp mLastAPDemandTime;
    WiFiStationMode mWiFiStationMode;
    WiFiStationState mWiFiStationState;
    WiFiAPMode mWiFiAPMode;
    WiFiAPState mWiFiAPState;
    System::Clock::Timeout mWiFiStationReconnectInterval;
    System::Clock::Timeout mWiFiAPIdleTimeout;
    BitFlags<Flags> mFlags;

    void DriveStationState(void);
    void OnStationConnected(void);
    void OnStationDisconnected(void);
    void ChangeWiFiStationState(WiFiStationState newState);
    static void DriveStationState(::chip::System::Layer * aLayer, void * aAppState);

    void DriveAPState(void);
    CHIP_ERROR ConfigureWiFiAP(void);
    void ChangeWiFiAPState(WiFiAPState newState);
    static void DriveAPState(::chip::System::Layer * aLayer, void * aAppState);

    void UpdateInternetConnectivityState(void);
    void OnStationIPv4AddressAvailable(void);
    void OnStationIPv4AddressLost(void);
    void OnIPv6AddressAvailable(void);

#endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI

    // ===== Members for internal use by the following friends.

    friend ConnectivityManager & ConnectivityMgr(void);
    friend ConnectivityManagerImpl & ConnectivityMgrImpl(void);

    static ConnectivityManagerImpl sInstance;
    static void RefreshMessageLayer(void);
    static void RtkWiFiStationConnectedHandler(char * buf, int buf_len, int flags, void * userdata);
    static void RtkWiFiStationDisconnectedHandler(char * buf, int buf_len, int flags, void * userdata);
    static void RtkWiFiScanCompletedHandler(void);
    void DHCPProcess(void);
    static void DHCPProcessThread(void * param);
    static int conn_callback_dispatcher(void * object);
};

#if CHIP_DEVICE_CONFIG_ENABLE_WIFI
inline bool ConnectivityManagerImpl::_IsWiFiStationApplicationControlled(void)
{
    return mWiFiStationMode == kWiFiStationMode_ApplicationControlled;
}

inline bool ConnectivityManagerImpl::_IsWiFiStationConnected(void)
{
    return mWiFiStationState == kWiFiStationState_Connected;
}

inline bool ConnectivityManagerImpl::_IsWiFiAPApplicationControlled(void)
{
    return mWiFiAPMode == kWiFiAPMode_ApplicationControlled;
}

inline System::Clock::Timeout ConnectivityManagerImpl::_GetWiFiStationReconnectInterval(void)
{
    return mWiFiStationReconnectInterval;
}

inline ConnectivityManager::WiFiAPMode ConnectivityManagerImpl::_GetWiFiAPMode(void)
{
    return mWiFiAPMode;
}

inline bool ConnectivityManagerImpl::_IsWiFiAPActive(void)
{
    return mWiFiAPState == kWiFiAPState_Active;
}

inline System::Clock::Timeout ConnectivityManagerImpl::_GetWiFiAPIdleTimeout(void)
{
    return mWiFiAPIdleTimeout;
}

inline bool ConnectivityManagerImpl::_CanStartWiFiScan()
{
    return mWiFiStationState != kWiFiStationState_Connecting;
}
#endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI

/**
 * Returns the public interface of the ConnectivityManager singleton object.
 *
 * Chip applications should use this to access features of the ConnectivityManager object
 * that are common to all platforms.
 */
inline ConnectivityManager & ConnectivityMgr(void)
{
    return ConnectivityManagerImpl::sInstance;
}

/**
 * Returns the platform-specific implementation of the ConnectivityManager singleton object.
 *
 * Chip applications can use this to gain access to features of the ConnectivityManager
 * that are specific to the Ameba platform.
 */
inline ConnectivityManagerImpl & ConnectivityMgrImpl(void)
{
    return ConnectivityManagerImpl::sInstance;
}

} // namespace DeviceLayer
} // namespace chip


text:
package com.lanyuan.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lanyuan.entity.Roles;
import com.lanyuan.entity.User;
import com.lanyuan.entity.UserRoles;
import com.lanyuan.service.RolesService;
import com.lanyuan.service.UserService;
import com.lanyuan.util.Common;
import com.lanyuan.util.PageView;

/**
 *
 * @author lanyuan
 * 2013-11-19
 * @Email: mmm333zzz520@163.com
 * @version 1.0v
 */
@Controller
@RequestMapping("/background/user/")
public class UserController {
	@Autowired
	private UserService userService;
	@Autowired
	private RolesService rolesService;
	/**
	 * @param model
	 * 存放返回界面的model
	 * @return
	 */
	@RequestMapping("query")
	public String query(Model model, User user, String pageNow) {
		PageView pageView = null;
		if (Common.isEmpty(pageNow)) {
			pageView = new PageView(1);
		} else {
			pageView = new PageView(Integer.parseInt(pageNow));
		}
		pageView = userService.query(pageView, user);
		model.addAttribute("pageView", pageView);
		return "/background/user/list";
	}

	/**
	 * 保存数据
	 *
	 * @param model
	 * @param videoType
	 * @return
	 */
	@RequestMapping("add")
	public String add(Model model, User user) {
		userService.add(user);
		return "redirect:query.html";
	}

	/**
	 * 跑到新增界面
	 *
	 * @param model
	 * @return
	 */
	@RequestMapping("addUI")
	public String addUI() {
		return "/background/user/add";
	}

	/**
	 * 删除
	 *
	 * @param model
	 * @param videoTypeId
	 * @return
	 */
	@RequestMapping("deleteById")
	public String deleteById(Model model, String userId) {
		userService.delete(userId);
		return "redirect:query.html";
	}

	/**
	 * 修改界面
	 *
	 * @param model
	 * @param videoTypeIds
	 * @return
	 */
	@RequestMapping("getById")
	public String getById(Model model, String userId, int type) {
		User user = userService.getById(userId);
		model.addAttribute("user", user);
		 List<Roles> roles=rolesService.findAll();
		 model.addAttribute("roles", roles);
		if (type == 1) {
			return "/background/user/edit";
		} else {
			return "/background/user/show";
		}
	}

	/**
	 * 更新类型
	 *
	 * @param model
	 * @return
	 */
	@RequestMapping("update")
	public String update(Model model, User user,UserRoles userRoles) {
		userService.modify(user);
		if(userRoles.getRoleId()!=null)
		rolesService.saveUserRole(userRoles);
		return "redirect:query.html";
	}

	/**
	 * 删除所选的
	 *
	 * @param model
	 * @return
	 */
	@RequestMapping("deleteAll")
	public String deleteAll(Model model, String[] check) {
		for (String string : check) {
			userService.delete(string);
		}
		return "redirect:query.html";
	}

	/**
	 * 给用户分配角色界面
	 * @return
	 */
	@RequestMapping("userRole")
	public String userRole(Model model,String userId){
		User user = userService.getById(userId);
		model.addAttribute("user", user);
		List<Roles> roles = rolesService.findAll();
		model.addAttribute("roles", roles);
		return "/background/user/userRole";
	}
	/**
	 * 保存用户分配角色
	 * @return
	 */
	@ResponseBody
	@RequestMapping("allocation")
	public String allocation(Model model,UserRoles userRoles){
		String errorCode = "1000";
		try {
			rolesService.saveUserRole(userRoles);
		} catch (Exception e) {
			e.printStackTrace();
			errorCode="1001";
		}
		return errorCode;
	}
}


text:
L.ExportAction = L.EditAction.extend({
  // This function is executed every time we select an image
  initialize(map, overlay, options) {
    const edit = overlay.editing;
    let tooltip;

    this.isExporting = false;
    this.mouseLeaveSkip = true;
    this.isHooksExecuted = false;

    if (edit instanceof L.DistortableImage.Edit) {
      L.DistortableImage.action_map.e = '_getExport';
      tooltip = overlay.options.translation.exportImage;
    } else {
      L.DistortableImage.group_action_map.e = 'runExporter';
      tooltip = overlay.options.translation.exportImages;
    }

    options = options || {};
    options.toolbarIcon = {
      svg: true,
      html: 'get_app',
      tooltip: tooltip,
    };

    L.EditAction.prototype.initialize.call(this, map, overlay, options);
  },

  addHooks() {
    const edit = this._overlay.editing;

    if (edit instanceof L.DistortableImage.Edit) {
      edit._getExport();
      return;
    }

    // Make sure that addHooks is executed only once, event listeners will handle the rest
    if (this.isHooksExecuted) {
      return;
    } else {
      this.isHooksExecuted = true;
    }

    const exportTool = this._link.parentElement;

    this.mouseEnterHandler = this.handleMouseEnter.bind(this);
    this.mouseLeaveHandler = this.handleMouseLeave.bind(this);

    L.DomEvent.on(exportTool, 'click', function() {
      if (!this.isExporting) {
        this.isExporting = true;
        this.renderExportIcon();

        setTimeout(this.attachMouseEventListeners.bind(this, exportTool), 100);
        edit.runExporter().then(
            function() {
              this.resetState();
              this.detachMouseEventListeners(exportTool);
            }.bind(this)
        );
      } else {
        // Clicking on the export icon after export has started will be ignored
        if (this.mouseLeaveSkip) {
          return;
        }

        this.resetState();
        this.detachMouseEventListeners(exportTool);
        edit.cancelExport();
      }
    }, this);
  },

  resetState() {
    this.renderDownloadIcon();
    this.isExporting = false;
    this.mouseLeaveSkip = true;
  },

  attachMouseEventListeners(element) {
    element.addEventListener('mouseenter', this.mouseEnterHandler);
    element.addEventListener('mouseleave', this.mouseLeaveHandler);
  },

  detachMouseEventListeners(element) {
    element.removeEventListener('mouseenter', this.mouseEnterHandler);
    element.removeEventListener('mouseleave', this.mouseLeaveHandler);
  },

  handleMouseEnter() {
    this.renderCancelIcon();
  },

  handleMouseLeave() {
    if (this.mouseLeaveSkip) {
      this.mouseLeaveSkip = false;
    } else {
      this.renderExportIcon();
    }
  },

  renderDownloadIcon() {
    L.IconUtil.toggleXlink(this._link, 'get_app', 'spinner');
    L.IconUtil.toggleTitle(this._link, 'Export Images', 'Loading...');
    L.DomUtil.removeClass(this._link.firstChild, 'loader');
  },

  renderExportIcon() {
    L.IconUtil.toggleXlink(this._link, 'spinner');
    L.IconUtil.toggleTitle(this._link, 'Export Images', 'Loading...');
    L.IconUtil.addClassToSvg(this._link, 'loader');
  },

  renderCancelIcon() {
    L.IconUtil.toggleXlink(this._link, 'cancel');
    L.IconUtil.toggleTitle(this._link, 'Cancel Export', 'Loading...');
    L.DomUtil.removeClass(this._link.firstChild, 'loader');
  },
});


text:
'use strict';

var loadTemplate = require('../utils/loadTemplate'),
    baseModal = require('./baseModal');

module.exports = baseModal.extend({
  className: 'guid-still-creating-modal',

  events: {
  },

  render: function() {
    var self = this;

    loadTemplate('./js/templates/guidStillCreatingModal.html', function(t) {
      self.$el.html(t());

      baseModal.prototype.render.apply(self, arguments);
    });

    return this;
  }
});


text:
<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin','admin',0);
pc_base::load_sys_class('form', '', 0);
class downservers extends admin {
	private $db;
	function __construct() {
		parent::__construct();
		$this->db = pc_base::load_model('downservers_model');
		$this->sites = pc_base::load_app_class('sites');
	}

	public function init() {
		if(isset($_POST['dosubmit'])) {
			$info['siteurl'] = trim($_POST['info']['siteurl']);
			$info['sitename'] = trim($_POST['info']['sitename']);
			$info['siteid'] = intval($_POST['info']['siteid']);
			if(empty($info['sitename'])) showmessage(L('downserver_not_empty'), HTTP_REFERER);
			if(empty($info['siteurl']) || !preg_match('/(\w+):\/\/(.+)[^\/]$/i', $info['siteurl'])) showmessage(L('downserver_error'), HTTP_REFERER);
			$insert_id = $this->db->insert($info,true);
			if($insert_id){
				$this->_set_cache();
				showmessage(L('operation_success'), HTTP_REFERER);
			}
		} else {
			$infos =  $sitelist = array();
			$current_siteid = get_siteid();
			$where = "`siteid`='$current_siteid' or `siteid`=''";
			$sitelists = $this->sites->get_list();
			if($_SESSION['roleid'] == '1') {
				foreach($sitelists as $key=>$v) $sitelist[$key] = $v['name'];
				$default = L('all_site');
			} else {
				$sitelist[$current_siteid] = $sitelists[$current_siteid]['name'];
				$default = '';
			}
			$page = $_GET['page'] ? $_GET['page'] : '1';
			$infos = $this->db->listinfo($where, 'listorder DESC,id DESC', $page, $pagesize = 20);
			$pages = $this->db->pages;
			include $this->admin_tpl('downservers_list');
		}
	}

	public function edit() {
		if(isset($_POST['dosubmit'])) {
			$info['siteurl'] = trim($_POST['info']['siteurl']);
			$info['sitename'] = trim($_POST['info']['sitename']);
			$info['siteid'] = intval($_POST['info']['siteid']);
			if(empty($info['sitename'])) showmessage(L('downserver_not_empty'), HTTP_REFERER);
			if(empty($info['siteurl']) || !preg_match('/(\w+):\/\/(.+)[^\/]$/i', $info['siteurl'])) showmessage(L('downserver_error'), HTTP_REFERER);
			$id = intval(trim($_POST['id']));
			$this->_set_cache();
			$this->db->update($info,array('id'=>$id));
			showmessage(L('operation_success'), '', '', 'edit');
		} else {
			$info =  $sitelist = array();
			$default = '';
			$sitelists = $this->sites->get_list();
			if($_SESSION['roleid'] == '1') {
				foreach($sitelists as $key=>$v) $sitelist[$key] = $v['name'];
				$default = L('all_site');
			} else {
				$current_siteid = self::get_siteid();
				$sitelist[$current_siteid] = $sitelists[$current_siteid]['name'];
				$default = '';
			}
			$info = $this->db->get_one(array('id'=>intval($_GET['id'])));
			extract($info);
			$show_validator = true;
			$show_header = true;
			include $this->admin_tpl('downservers_edit');
		}
	}

	public function delete() {
		$id = intval($_GET['id']);
		$this->db->delete(array('id'=>$id));
		$this->_set_cache();
		showmessage(L('downserver_del_success'), HTTP_REFERER);
	}

	/**
	 * 排序
	 */
	public function listorder() {
		if(isset($_POST['dosubmit'])) {
			foreach($_POST['listorders'] as $id => $listorder) {
				$this->db->update(array('listorder'=>$listorder),array('id'=>$id));
			}
			showmessage(L('operation_success'), HTTP_REFERER);
		} else {
			showmessage(L('operation_failure'), HTTP_REFERER);
		}
	}

	private function _set_cache() {
		$infos = $this->db->select();
		foreach ($infos as $info){
			$servers[$info['id']] = $info;
		}
		setcache('downservers', $servers,'commons');
		return $infos;
	}

}
?>


text:
angular.module('gRecaptcha', [])
  .directive('gRecaptcha', function () {
    return {
      require: 'ngModel',
      restrict: 'A',
      scope: {
        response: '=ngModel'
      },
      link: function (scope, el, attr) {
        sitekey = attr.gRecaptchaSitekey;
        if (! grecaptcha || ! sitekey) {
          return;
        }

        theme = attr.gRecaptchaTheme || 'light';
        type = attr.gRecaptchaType || 'image';

        grecaptcha.render(el[0], {
          sitekey: sitekey,
          theme: theme,
          type: type,
          callback: function (gRecaptchaResponse) {
            scope.response = gRecaptchaResponse;
          }
        });
      }
    };
  });


text:
require 'test_helper'
require 'support/compact_environment'

class ActionAccessTest < ActiveSupport::TestCase
  test "unauthorized accesses aren't allowed" do
    assert_equal false, keeper.lets?(:user, :edit, :posts)
    assert_equal false, keeper.lets?(:user, :edit, :posts, namespace: :admin)
  end

  test "authorized accesses are allowed" do
    keeper.let :editor, [:edit, :update], :posts
    assert_equal true, keeper.lets?(:editor, :edit, :posts)
    assert_equal true, keeper.lets?(:editor, :update, :posts)
  end

  test "authorized accesses within namespaces are allowed" do
    keeper.let :admin, [:new, :create], :posts, namespace: :admin
    assert_equal true, keeper.lets?(:admin, :new, :posts, namespace: :admin)
    assert_equal true, keeper.lets?(:admin, :create, :posts, namespace: :admin)
  end
end


text:
'use strict';

var test = require('tape');

test('window.__algolia', function(t) {
  t.plan(4);

  var algoliasearch = require('../../../');

  t.ok(window.__algolia, 'we exported it');
  t.equal(window.__algolia.algoliasearch.version, algoliasearch.version, 'version matches');
  t.equal(window.__algolia.algoliasearch.ua, algoliasearch.ua, 'ua matches');
  t.ok(window.__algolia.debug, 'debug is present');
});


text:
require 'rails_helper'

RSpec.describe "homes/new", type: :view do
  before(:each) do
    assign(:home, Home.new(
      :address => "MyString"
    ))
  end

  it "renders new home form" do
    render

    assert_select "form[action=?][method=?]", homes_path, "post" do

      assert_select "input#home_address[name=?]", "home[address]"
    end
  end
end


text:
package com.panzareon.spellcircles.block;

import com.panzareon.spellcircles.init.ModBlocks;
import com.panzareon.spellcircles.tileentity.TileEntitySpellCircle;
import com.panzareon.spellcircles.tileentity.TileEntitySpellCircleGag;
import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;

import javax.annotation.Nullable;
import java.util.Random;

public class BlockSpellCircleGag extends  SpellCirclesBlock implements ITileEntityProvider
{
    public BlockSpellCircleGag(){
        this.setUnlocalizedName("spell_circle");
    }

    //This block is called when block is broken and destroys the primary block.

    @Override
    public void breakBlock(World worldIn, BlockPos pos, IBlockState state)
    {
        //Reading the gag's tile entity.
        TileEntitySpellCircleGag tileEntity = (TileEntitySpellCircleGag)worldIn.getTileEntity(pos);
        //If not make this check, the game may crash if there's no tile entity at i, j, k.
        if (tileEntity != null){
            //Actually destroys primary block.
            worldIn.destroyBlock(tileEntity.primaryPos, false);
            //Forces removing tile entity from primary block coordinates,
            //cause sometimes minecraft forgets to do that.
            worldIn.removeTileEntity(tileEntity.primaryPos);
        }
        //Same as above, but for the gag block tile entity.
        worldIn.removeTileEntity(pos);
    }

    //This method checks if primary block exists.

    @Override
    public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn)
    {
        if (!worldIn.isRemote)
        {
            if (!worldIn.isSideSolid(pos.down(),EnumFacing.UP,true))
            {
                breakBlock(worldIn, pos, state);
            }
        }
        TileEntitySpellCircleGag tileEntity = (TileEntitySpellCircleGag)worldIn.getTileEntity(pos);
        if (tileEntity != null){
            //No need to check if block's Id matches the Id of our primary block,
            //because if a player want to change a block, he needs to brake it first,
            //and in this case block will be set to Air (Id = 0)
            if(worldIn.isAirBlock(tileEntity.primaryPos)){
                worldIn.destroyBlock(pos, false);
                worldIn.removeTileEntity(pos);
            }
        }
    }

    //This makes gag invisible.
    @Override
    public EnumBlockRenderType getRenderType(IBlockState state) {
        return EnumBlockRenderType.INVISIBLE;
    }

    @Override
    public boolean isOpaqueCube(IBlockState state)
    {
        return false;
    }

    @Override
    public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, World worldIn, BlockPos pos)
    {
        return null;
    }

    @Override
    public AxisAlignedBB getSelectedBoundingBox(IBlockState state, World worldIn, BlockPos pos) {
        return getBoundingBox(state, worldIn, pos);
    }
    @Override
    public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos){
        TileEntitySpellCircleGag te = (TileEntitySpellCircleGag) source.getTileEntity(pos);
        if(te != null && te.primaryPos != null)
        {
            TileEntitySpellCircle primaryTe = (TileEntitySpellCircle) source.getTileEntity(te.primaryPos);
            if(primaryTe != null)
            {
                return ModBlocks.spellCircle.getBoundingBox(getDefaultState(),source, primaryTe.getPos());
            }
        }
        return super.getBoundingBox(getDefaultState(), source, pos);
    }

    @Override
    public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, @Nullable ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ)
    {
        TileEntitySpellCircleGag te = (TileEntitySpellCircleGag) worldIn.getTileEntity(pos);
        if(te != null && te.primaryPos != null)
        {
            TileEntitySpellCircle primaryTe = (TileEntitySpellCircle) worldIn.getTileEntity(te.primaryPos);
            if(primaryTe != null)
            {
                BlockPos primaryPos = primaryTe.getPos();
                hitX += primaryPos.getX() - pos.getX();
                hitZ += primaryPos.getZ() - pos.getZ();
                return ModBlocks.spellCircle.onBlockActivated(worldIn, primaryPos, state, playerIn, hand, heldItem, side, hitX, hitY, hitZ);
            }
        }
        return super.onBlockActivated(worldIn, pos, state, playerIn, hand, heldItem, side, hitX, hitY, hitZ);
    }

    @Override
    public boolean isFullCube(IBlockState state)
    {
        return false;
    }

    @Override
    public TileEntity createNewTileEntity(World worldIn, int meta)
    {
        return new TileEntitySpellCircleGag();
    }

    @Override
    public int quantityDropped(Random random)
    {
        return 0;
    }
}


text:
package com.neilren.neilren4j.controller;

import com.neilren.neilren4j.common.baseclass.BasePageController;
import com.neilren.neilren4j.entity.Article;
import com.neilren.neilren4j.entity.BaiduXiongZhangJsonLD;
import com.neilren.neilren4j.entity.HeadTitle;
import com.neilren.neilren4j.entity.Menu;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author NeilRen
 * @version 1.0
 * @ClassName ArticleController
 * @Description TODO
 * @Date 2018/7/19 12:56
 */
@Slf4j
@Controller
@RequestMapping("/Article")
public class ArticleController extends BasePageController {
    @RequestMapping({"{id}", "{id}/", "{id}/{type}", "{id}/{type}/"})
    public ModelAndView getArticleById(@PathVariable("id") Long id,
                                       @PathVariable(value = "type", required = false) String type,
                                       HttpServletRequest request) throws NoHandlerFoundException {
        ModelAndView mv = new ModelAndView();
        List<Menu> menuList = siteMenuService.getAllMenu("/blog");
        mv.addObject("menu", menuList);
        try {
            Article article = articleService.getArticleById(id);
            if (article == null) {
                //查询不到文章
                HttpHeaders headers = new HttpHeaders();
                throw new NoHandlerFoundException(request.getMethod(), request.getRequestURL().toString(), headers);
            } else {
                HeadTitle headTitle = new HeadTitle(article.getTitle() + " - " + siteName, article.getDescribes(), article.getKeyword());
                mv.addObject("title", headTitle);
                mv.addObject("article", article);
                //其他文章
                List<Article> articleOther = articleService.getOtherRelated(article);
                if (articleOther != null && articleOther.size() > 0) {
                    mv.addObject("article_other", articleOther);
                }
                //TopView
                List<Article> articleTopView = articleService.selectTopViewArticle(1, 4);
                if (articleTopView != null && articleTopView.size() > 0) {
                    mv.addObject("topview", articleTopView);
                }
                //百度熊掌号搜索结果出图
                BaiduXiongZhangJsonLD baiduXiongZhangJsonLD = new BaiduXiongZhangJsonLD(
                        neilren4jConfig.getBaidu().getSite() + "Article/" + article.getId(),
                        article.getTitle(),
                        new ArrayList<String>() {{
                            if (article.getImg() != null && article.getImg() != "") {
                                add(article.getImg());
                            }
                        }},
                        article.getDate(),
                        neilren4jConfig.getBaidu().getXiongzhangappid()
                );
                mv.addObject("baiduXiongZhangJsonLD", baiduXiongZhangJsonLD.getHtmlCode(baiduXiongZhangJsonLD));
                if ("mip".equals(type)) {
                    headTitle.setCanonical(neilren4jConfig.getHost() + "/Article/" + id);
                    mv.addObject("title", headTitle);
                    mv.setViewName("mip/article/detail");
                } else if ("amp".equals(type)) {
                    mv.setViewName("amp/article/detail");
                } else if (type == null) {
                    headTitle.setMiphtml(neilren4jConfig.getHost() + "/Article/" + id + "/mip");
                    mv.addObject("title", headTitle);
                    mv.setViewName("article/detail");
                } else {
                    HttpHeaders headers = new HttpHeaders();
                    throw new NoHandlerFoundException(request.getMethod(), request.getRequestURL().toString(), headers);
                }
            }
        } catch (NoHandlerFoundException e) {
            log.error(e.getMessage(), e);
            throw e;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return mv;
    }
}


text:
% runc-restore "8"

# NAME
   runc restore - restore a container from a previous checkpoint

# SYNOPSIS
   runc restore [command options] `<container-id>`

Where "`<container-id>`" is the name for the instance of the container to be
restored.

# DESCRIPTION
   Restores the saved state of the container instance that was previously saved
using the runc checkpoint command.

# OPTIONS
    --image-path value           path to criu image files for restoring
    --work-path value            path for saving work files and logs
    --tcp-established            allow open tcp connections
    --ext-unix-sk                allow external unix sockets
    --shell-job                  allow shell jobs
    --file-locks                 handle file locks, for safety
    --manage-cgroups-mode value  cgroups mode: 'soft' (default), 'full' and 'strict'
    --bundle value, -b value     path to the root of the bundle directory
    --detach, -d                 detach from the container's process
    --pid-file value             specify the file to write the process id to
    --no-subreaper               disable the use of the subreaper used to reap reparented processes
    --no-pivot                   do not use pivot root to jail process inside rootfs.  This should be used whenever the rootfs is on top of a ramdisk


text:
package com.mattunderscore.trees.impl.providers;

import com.mattunderscore.trees.binary.OpenMutableBinaryTreeNode;
import com.mattunderscore.trees.spi.Rotator;
import com.mattunderscore.trees.transformation.RotationDirection;

/**
 * Provider for {@link Rotator} components.
 * @author Matt Champion on 26/08/2015
 */
public interface RotatorProvider {
    <E, N extends OpenMutableBinaryTreeNode<E, N>> Rotator<E, N> get(N node, RotationDirection direction);
}


text:
package com.intellij.util.indexing.impl;

import com.intellij.util.indexing.ID;
import com.intellij.util.indexing.IndexExtension;
import com.intellij.util.io.KeyDescriptor;
import org.jetbrains.annotations.NotNull;

public abstract class AbstractForwardIndex<Key, Value> implements ForwardIndex<Key,Value> {
  protected final ID<Key, Value> myIndexId;
  protected final KeyDescriptor<Key> myKeyDescriptor;
  protected final IndexExtension<Key, Value, ?> myIndexExtension;

  protected AbstractForwardIndex(@NotNull IndexExtension<Key, Value, ?> extension) {
    myIndexId = extension.getName();
    myKeyDescriptor = extension.getKeyDescriptor();
    myIndexExtension = extension;
  }

  @NotNull
  public IndexExtension<Key, Value, ?> getIndexExtension() {
    return myIndexExtension;
  }

  public boolean hasOnlyKeysData() {
    return true;
  }
}


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html" charset="utf-8">
    <title>ler</title>
    <link rel="stylesheet" type="text/css" href="/clinica/css2/deletepatient.css"/>

<?php
foreach ($this->session->getFlashBag()->all() as $type => $messages) {
    foreach ($messages as $message) {
        echo '
'.$message.'
';
    }
}
echo $error;
?>
<form name="excluir" action="/clinica/front.php/deleteconsult" method="POST">

INSIRA O CPF DO CLIENTE:

    <input type="text" name="cpf" >

INSIRA A DATA DA CONSULTA A EXCLUIR

    <input type="text" name="date" >

    <input type="submit" value="Enviar">
</form>
voltar


text:
package com.github.moonstar.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.github.moonstar.common.RequestHelper;
import com.github.moonstar.dto.ResultView;
import com.github.moonstar.entity.UserEntity;
import com.github.moonstar.service.UserService;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.hibernate.validator.constraints.Length;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 *
 */

@RestController
@RequestMapping(value = "api/v1")
@Validated
public class UserController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping(value = "query/user/{userId}")
    public UserEntity getUserInfo(@PathVariable(value = "userId") String userId) {
        if (StringUtils.isEmpty(userId) || !StringUtils.isNumber(userId)) {
            return null;
        }
        //
        return new UserEntity().setUserName("test");
    }

    @GetMapping(value = "add/user")
    public UserEntity addUser(@RequestParam(value = "username") String userName,
        @RequestParam(value = "password") @Length(min = 6, max = 18) String password) {
        return userService.addUser(userName, password);
    }

    @PostMapping(value = "/update/user")
    public ResultView<Boolean> updateUser(HttpServletRequest request) {
        try {
            UserEntity user = RequestHelper.getFromJson(request, UserEntity.class);
            return ResultView.success(userService.updateUser(user));
        } catch (IOException e) {
            LOGGER.error("update UserEntity error! e={}", e);
            return ResultView.failed(201, "system error!", false);
        }
    }

    @PostMapping(value = "/testTransaction")
    public int testTransaction(HttpServletRequest request, @RequestBody String str) throws IOException {
        UserEntity user = JSON.parseObject(str, UserEntity.class);
        return userService.testTransaction(user);
    }

}


text:
namespace hect
{

///
/// Maps user input to input axes.
///
/// \system
class HECT_EXPORT InputSystem :
    public System<InputSystem>
{
public:
    InputSystem(Scene& scene, Platform& platform, const DataValue& settings);

    ///
    /// Adds an axis.
    ///
    /// \param axis The axis to add.
    ///
    /// \throws InvalidOperation If an axis already exists with the same name.
    void add_axis(const InputAxis& axis);

    ///
    /// Returns the value of the axis with the given name.
    ///
    /// \param name The name of the axis.
    ///
    /// \returns The value of the axis; 0 if the axis does not exist.
    double axis_value(Name name) const;

    ///
    /// Update the values of all axes.
    ///
    /// \param time_step The duration of time in seconds to update for.
    void update_axes(Seconds time_step);

private:
    Platform& _platform;
    std::unordered_map<Name, InputAxis> _axes;
};

}


text:
module Test.Pos.Chain.Delegation.Example
       ( exampleLightDlgIndices
       , exampleProxySKBlockInfo
       , exampleUndo
       , staticHeavyDlgIndexes
       , staticProxySKHeavys
       ) where

import           Universum

import qualified Data.HashSet as HS
import           Data.List (zipWith4, (!!))

import           Pos.Chain.Delegation (DlgUndo (..), HeavyDlgIndex (..),
                     LightDlgIndices (..), ProxySKBlockInfo, ProxySKHeavy)
import           Pos.Core (EpochIndex (..))
import           Pos.Crypto (ProtocolMagic (..), ProtocolMagicId (..),
                     RequiresNetworkMagic (..), safeCreatePsk)

import           Test.Pos.Core.ExampleHelpers (examplePublicKey,
                     examplePublicKeys, exampleStakeholderId,
                     staticSafeSigners)

staticHeavyDlgIndexes :: [HeavyDlgIndex]
staticHeavyDlgIndexes = map (HeavyDlgIndex . EpochIndex) [5,1,3,27,99,247]

staticProtocolMagics :: [ProtocolMagic]
staticProtocolMagics = map mkPm [0..5]
  where
    mkPm :: Int32 -> ProtocolMagic
    mkPm x = ProtocolMagic { getProtocolMagicId = ProtocolMagicId x
                           , getRequiresNetworkMagic = RequiresNoMagic
                           }

staticProxySKHeavys :: [ProxySKHeavy]
staticProxySKHeavys = zipWith4 safeCreatePsk
                               staticProtocolMagics staticSafeSigners
                               (examplePublicKeys 1 6) staticHeavyDlgIndexes

exampleProxySKBlockInfo :: ProxySKBlockInfo
exampleProxySKBlockInfo = Just (staticProxySKHeavys !! 0, examplePublicKey)

exampleLightDlgIndices :: LightDlgIndices
exampleLightDlgIndices = LightDlgIndices (EpochIndex 7, EpochIndex 88)

exampleUndo :: DlgUndo
exampleUndo = DlgUndo
  { duPsks = staticProxySKHeavys
  , duPrevEpochPosted = HS.singleton exampleStakeholderId
  }


text:
window.addEventListener("DOMContentLoaded", function(){
	var url = 'https://vine.co/oembed.json?id=eD5rFELn5ZP';
	console.log('initalitized');

	//var url = 'https://vine.co/oembed.json?url=https%3A%2F%2Fvine.co%2Fv%2'+id;
	var xhr = new XMLHttpRequest();

	xhr.onreadystatechange = function(){
		if(xhr.readystate === 4){
	  		console.log(xhr.responseText);
		}
	}

	xhr.open("GET",url,true);
	xhr.send();
});
//https://vine.co/u/907780965202538496


text:
package li.vin.net;

import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import rx.Observable;

public class Message implements VinliItem {
  /*package*/ static final Type TIME_SERIES_TYPE = new TypeToken<TimeSeries<Message>>() {
  }.getType();
  /*package*/ static final Type WRAPPED_TYPE = new TypeToken<Wrapped<Message>>() {
  }.getType();

  /*package*/
  static final void registerGson(GsonBuilder gb) {
    gb.registerTypeAdapter(TIME_SERIES_TYPE,
        TimeSeries.Adapter.create(TIME_SERIES_TYPE, Message.class));
    gb.registerTypeAdapter(WRAPPED_TYPE, Wrapped.Adapter.create(Message.class));
  }

  public static Observable<Message> messageWithId(@NonNull String messageId) {
    return Vinli.curApp().message(messageId);
  }

  public static Observable<TimeSeries<Message>> messagesWithDeviceId(@NonNull String deviceId) {
    return messagesWithDeviceId(deviceId, (Long) null, null, null, null);
  }

  public static Observable<TimeSeries<Message>> messagesWithDeviceId(@NonNull String deviceId,
      @Nullable Long sinceMs, @Nullable Long untilMs, @Nullable Integer limit,
      @Nullable String sortDir) {
    return Vinli.curApp().messages().messages(deviceId, sinceMs, untilMs, limit, sortDir);
  }

  public static Observable<TimeSeries<Message>> messagesWithVehicleId(@NonNull String vehicleId) {
    return messagesWithVehicleId(vehicleId, null, null, null, null);
  }

  public static Observable<TimeSeries<Message>> messagesWithVehicleId(@NonNull String vehicleId,
      @Nullable Long sinceMs, @Nullable Long untilMs, @Nullable Integer limit,
      @Nullable String sortDir) {
    return Vinli.curApp().messages().vehicleMessages(vehicleId, sinceMs, untilMs, limit, sortDir);
  }

  @Deprecated
  public static Observable<TimeSeries<Message>> messagesWithDeviceId(@NonNull String deviceId,
      @Nullable Date since, @Nullable Date until, @Nullable Integer limit,
      @Nullable String sortDir) {
    Long sinceMs = since == null ? null : since.getTime();
    Long untilMs = until == null ? null : until.getTime();
    return Vinli.curApp().messages().messages(deviceId, sinceMs, untilMs, limit, sortDir);
  }

  public String id;
  public String timestamp;
  private LinkedTreeMap<String, Object> data;
  /*package*/ Links links;

  /*package*/ Message() {

  }

  /*package*/ Message(Parcel in) {
    Gson gson = new Gson();
    Message message = gson.fromJson(in.readString(), Message.class);
    this.id = message.id();
    this.timestamp = message.timestamp;
    this.data = message.data;
  }

  public String id() {
    return id;
  }

  @Nullable
  public String rawVal(@NonNull String key) {
    try {
      if (data == null) return null;
      Object val = data.get(key);
      if (val == null) return null;
      if (val instanceof String) return (String) val;
      if (val instanceof Number) return val.toString();
      if (val instanceof LinkedTreeMap) {
        //noinspection unchecked
        return convertLinkedTreeMapToJSON((LinkedTreeMap<String, Object>) val).toString();
      }
      if (val instanceof Collection) {
        //noinspection unchecked
        return convertCollectionToJSON((Collection<Object>) val).toString();
      }
      if (val instanceof Object[]) {
        //noinspection unchecked
        return convertArrayToJSON((Object[]) val).toString();
      }
      if (val instanceof JSONObject || val instanceof JSONArray) {
        return val.toString();
      }
    } catch (Exception ignored) {
    }
    return null;
  }

  public double doubleVal(@NonNull String key, double def) {
    String raw = rawVal(key);
    if (raw != null) {
      try {
        return Double.parseDouble(raw);
      } catch (NumberFormatException ignored) {
      }
    }
    return def;
  }

  public long longVal(@NonNull String key, long def) {
    return Math.round(doubleVal(key, def));
  }

  public float floatVal(@NonNull String key, float def) {
    return Double.valueOf(doubleVal(key, def)).floatValue();
  }

  public int intVal(@NonNull String key, int def) {
    return Long.valueOf(longVal(key, def)).intValue();
  }

  @Nullable
  public Coordinate coord() {
    try {
      if (data == null) return null;
      Object locObj = data.get("location");
      if (!(locObj instanceof LinkedTreeMap)) return null;
      //noinspection unchecked
      Object coordObj = ((LinkedTreeMap<String, Object>) locObj).get("coordinates");
      Object[] coords;
      if (coordObj instanceof Collection) {
        coords = ((Collection) coordObj).toArray();
      } else if (coordObj instanceof Object[]) {
        coords = (Object[]) coordObj;
      } else {
        return null;
      }
      return Coordinate.builder()
          .lat(((Number) coords[1]).floatValue())
          .lon(((Number) coords[0]).floatValue())
          .build();
    } catch (Exception ignored) {
    }
    return null;
  }

  @Nullable
  public AccelData accel() {
    try {
      return new Gson().fromJson(rawVal("accel"), AccelData.class);
    } catch (Exception ignored) {
    }
    return null;
  }

  @NonNull
  private static JSONObject convertLinkedTreeMapToJSON(LinkedTreeMap<String, Object> ltm) {
    JSONObject jo = new JSONObject();
    Object[] objs = ltm.entrySet().toArray();
    for (Object obj : objs) {
      Map.Entry o = (Map.Entry) obj;
      try {
        if (o.getValue() instanceof LinkedTreeMap) {
          //noinspection unchecked
          jo.put(o.getKey().toString(),
              convertLinkedTreeMapToJSON((LinkedTreeMap<String, Object>) o.getValue()));
        } else {
          jo.put(o.getKey().toString(), o.getValue());
        }
      } catch (JSONException ignored) {
      }
    }
    return jo;
  }

  @NonNull
  private static JSONArray convertCollectionToJSON(@NonNull Collection<Object> col) {
    JSONArray ja = new JSONArray();
    for (Object o : col) {
      if (o instanceof LinkedTreeMap) {
        //noinspection unchecked
        ja.put(convertLinkedTreeMapToJSON((LinkedTreeMap<String, Object>) o));
      } else {
        ja.put(o);
      }
    }
    return ja;
  }

  @NonNull
  private static JSONArray convertArrayToJSON(@NonNull Object[] arr) {
    JSONArray ja = new JSONArray();
    for (Object o : arr) {
      if (o instanceof LinkedTreeMap) {
        //noinspection unchecked
        ja.put(convertLinkedTreeMapToJSON((LinkedTreeMap<String, Object>) o));
      } else {
        ja.put(o);
      }
    }
    return ja;
  }

  public static final class AccelData {

    /*
    "accel": {
        "maxZ": 6.282417,
        "maxX": -2.911364,
        "maxY": -2.489982,
        "minX": -7.853021,
        "minY": -10.649463,
        "minZ": -0.804456
      }
     */

    private Double maxX;
    private Double maxY;
    private Double maxZ;
    private Double minX;
    private Double minY;
    private Double minZ;

    AccelData(double maxX, double maxY, double maxZ, double minX, double minY, double minZ) {
      this.maxX = maxX;
      this.maxY = maxY;
      this.maxZ = maxZ;
      this.minX = minX;
      this.minY = minY;
      this.minZ = minZ;
    }

    AccelData() {
    }

    public double maxX() {
      if (maxX == null) return 0d;
      return maxX;
    }

    public double maxY() {
      if (maxY == null) return 0d;
      return maxY;
    }

    public double maxZ() {
      if (maxZ == null) return 0d;
      return maxZ;
    }

    public double minX() {
      if (minX == null) return 0d;
      return minX;
    }

    public double minY() {
      if (minY == null) return 0d;
      return minY;
    }

    public double minZ() {
      if (minZ == null) return 0d;
      return minZ;
    }

    @Override
    public String toString() {
      return "AccelData{" +
          "maxX=" + maxX +
          ", maxY=" + maxY +
          ", maxZ=" + maxZ +
          ", minX=" + minX +
          ", minY=" + minY +
          ", minZ=" + minZ +
          '}';
    }

    @Override
    public boolean equals(Object o) {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;
      AccelData accelData = (AccelData) o;
      return !(maxX != null
          ? !maxX.equals(accelData.maxX)
          : accelData.maxX != null) && !(maxY != null
          ? !maxY.equals(accelData.maxY)
          : accelData.maxY != null) && !(maxZ != null
          ? !maxZ.equals(accelData.maxZ)
          : accelData.maxZ != null) && !(minX != null
          ? !minX.equals(accelData.minX)
          : accelData.minX != null) && !(minY != null
          ? !minY.equals(accelData.minY)
          : accelData.minY != null) && !(minZ != null
          ? !minZ.equals(accelData.minZ)
          : accelData.minZ != null);
    }

    @Override
    public int hashCode() {
      int result = maxX != null
          ? maxX.hashCode()
          : 0;
      result = 31 * result + (maxY != null
          ? maxY.hashCode()
          : 0);
      result = 31 * result + (maxZ != null
          ? maxZ.hashCode()
          : 0);
      result = 31 * result + (minX != null
          ? minX.hashCode()
          : 0);
      result = 31 * result + (minY != null
          ? minY.hashCode()
          : 0);
      result = 31 * result + (minZ != null
          ? minZ.hashCode()
          : 0);
      return result;
    }
  }

  @Override
  public int describeContents() {
    return 0;
  }

  @Override
  public void writeToParcel(Parcel dest, int flags) {
    Gson gson = new Gson();
    dest.writeString(gson.toJson(this, Message.class));
  }

  private static final Parcelable.Creator<Message> CREATOR = new Parcelable.Creator<Message>() {

    @Override
    public Message createFromParcel(Parcel in) {
      return new Message(in);
    }

    @Override
    public Message[] newArray(int size) {
      return new Message[size];
    }
  };

  static class Links {
    public String self;
  }
}


text:
//// [ExportClassWithInaccessibleTypeInTypeParameterConstraint.ts]
module A {

    class Point {
        x: number;
        y: number;
    }

    export var Origin: Point = { x: 0, y: 0 };

    export class Point3d extends Point {
        z: number;
    }

    export var Origin3d: Point3d = { x: 0, y: 0, z: 0 };

    export class Line<TPoint extends Point>{
        constructor(public start: TPoint, public end: TPoint) { }

        static fromorigin2d(p: Point): Line<Point>{
            return null;
        }
    }
}

//// [ExportClassWithInaccessibleTypeInTypeParameterConstraint.js]
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var A;
(function (A) {
    var Point = /** @class */ (function () {
        function Point() {
        }
        return Point;
    }());
    A.Origin = { x: 0, y: 0 };
    var Point3d = /** @class */ (function (_super) {
        __extends(Point3d, _super);
        function Point3d() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return Point3d;
    }(Point));
    A.Point3d = Point3d;
    A.Origin3d = { x: 0, y: 0, z: 0 };
    var Line = /** @class */ (function () {
        function Line(start, end) {
            this.start = start;
            this.end = end;
        }
        Line.fromorigin2d = function (p) {
            return null;
        };
        return Line;
    }());
    A.Line = Line;
})(A || (A = {}));


text:
/** @file  IRRShared.h
  * @brief Shared utilities for the IRR and IRRMESH loaders
  */

#ifndef INCLUDED_AI_IRRSHARED_H
#define INCLUDED_AI_IRRSHARED_H

#include "irrXMLWrapper.h"
#include "BaseImporter.h"
// Urho3D: VS2008 compatibility
#if !defined(_MSC_VER) || (_MSC_VER >= 1600)
#include <stdint.h>
#else
#include "../include/assimp/Compiler/pstdint.h"
#endif

struct aiMaterial;

namespace Assimp    {

/** @brief Matrix to convert from Assimp to IRR and backwards
 */
extern const aiMatrix4x4 AI_TO_IRR_MATRIX;

// Default: 0 = solid, one texture
#define AI_IRRMESH_MAT_solid_2layer         0x10000

// Transparency flags
#define AI_IRRMESH_MAT_trans_vertex_alpha   0x1
#define AI_IRRMESH_MAT_trans_add            0x2

// Lightmapping flags
#define AI_IRRMESH_MAT_lightmap             0x2
#define AI_IRRMESH_MAT_lightmap_m2          (AI_IRRMESH_MAT_lightmap|0x4)
#define AI_IRRMESH_MAT_lightmap_m4          (AI_IRRMESH_MAT_lightmap|0x8)
#define AI_IRRMESH_MAT_lightmap_light       (AI_IRRMESH_MAT_lightmap|0x10)
#define AI_IRRMESH_MAT_lightmap_light_m2    (AI_IRRMESH_MAT_lightmap|0x20)
#define AI_IRRMESH_MAT_lightmap_light_m4    (AI_IRRMESH_MAT_lightmap|0x40)
#define AI_IRRMESH_MAT_lightmap_add         (AI_IRRMESH_MAT_lightmap|0x80)

// Standard NormalMap (or Parallax map, they're treated equally)
#define AI_IRRMESH_MAT_normalmap_solid      (0x100)

// Normal map combined with vertex alpha
#define AI_IRRMESH_MAT_normalmap_tva    \
    (AI_IRRMESH_MAT_normalmap_solid | AI_IRRMESH_MAT_trans_vertex_alpha)

// Normal map combined with additive transparency
#define AI_IRRMESH_MAT_normalmap_ta     \
    (AI_IRRMESH_MAT_normalmap_solid | AI_IRRMESH_MAT_trans_add)

// Special flag. It indicates a second texture has been found
// Its type depends ... either a normal textue or a normal map
#define AI_IRRMESH_EXTRA_2ND_TEXTURE        0x100000

// ---------------------------------------------------------------------------
/** Base class for the Irr and IrrMesh importers.
 *
 *  Declares some irrlight-related xml parsing utilities and provides tools
 *  to load materials from IRR and IRRMESH files.
 */
class IrrlichtBase
{
protected:

    /** @brief Data structure for a simple name-value property
     */
    template <class T>
    struct Property
    {
        std::string name;
        T value;
    };

    typedef Property<uint32_t>      HexProperty;
    typedef Property<std::string>   StringProperty;
    typedef Property<bool>          BoolProperty;
    typedef Property<float>         FloatProperty;
    typedef Property<aiVector3D>    VectorProperty;
    typedef Property<int>           IntProperty;

    /** XML reader instance
     */
  irr::io::IrrXMLReader* reader;

    // -------------------------------------------------------------------
    /** Parse a material description from the XML
     *  @return The created material
     *  @param matFlags Receives AI_IRRMESH_MAT_XX flags
     */
    aiMaterial* ParseMaterial(unsigned int& matFlags);

    // -------------------------------------------------------------------
    /** Read a property of the specified type from the current XML element.
     *  @param out Recives output data
     */
    void ReadHexProperty    (HexProperty&    out);
    void ReadStringProperty (StringProperty& out);
    void ReadBoolProperty   (BoolProperty&   out);
    void ReadFloatProperty  (FloatProperty&  out);
    void ReadVectorProperty (VectorProperty&  out);
    void ReadIntProperty    (IntProperty&    out);
};

// ------------------------------------------------------------------------------------------------
// Unpack a hex color, e.g. 0xdcdedfff
inline void ColorFromARGBPacked(uint32_t in, aiColor4D& clr)
{
    clr.a = ((in >> 24) & 0xff) / 255.f;
    clr.r = ((in >> 16) & 0xff) / 255.f;
    clr.g = ((in >>  8) & 0xff) / 255.f;
    clr.b = ((in      ) & 0xff) / 255.f;
}

} // end namespace Assimp

#endif // !! INCLUDED_AI_IRRSHARED_H


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

/**
 * @fileoverview A thick wrapper around paths.
 * @author robbyw@google.com (Robby Walker)
 */

goog.provide('goog.graphics.ext.Path');

goog.require('goog.graphics.AffineTransform');
goog.require('goog.graphics.Path');
goog.require('goog.math.Rect');

/**
 * Creates a path object
 * @constructor
 * @extends {goog.graphics.Path}
 * @final
 */
goog.graphics.ext.Path = function() {
  goog.graphics.Path.call(this);
};
goog.inherits(goog.graphics.ext.Path, goog.graphics.Path);

/**
 * Optional cached or user specified bounding box.  A user may wish to
 * precompute a bounding box to save time and include more accurate
 * computations.
 * @type {goog.math.Rect?}
 * @private
 */
goog.graphics.ext.Path.prototype.bounds_ = null;

/**
 * Clones the path.
 * @return {!goog.graphics.ext.Path} A clone of this path.
 * @override
 */
goog.graphics.ext.Path.prototype.clone = function() {
  var output = /** @type {goog.graphics.ext.Path} */
      (goog.graphics.ext.Path.superClass_.clone.call(this));
  output.bounds_ = this.bounds_ && this.bounds_.clone();
  return output;
};

/**
 * Transforms the path. Only simple paths are transformable. Attempting
 * to transform a non-simple path will throw an error.
 * @param {!goog.graphics.AffineTransform} tx The transformation to perform.
 * @return {!goog.graphics.ext.Path} The path itself.
 * @override
 */
goog.graphics.ext.Path.prototype.transform = function(tx) {
  goog.graphics.ext.Path.superClass_.transform.call(this, tx);

  // Make sure the precomputed bounds are cleared when the path is transformed.
  this.bounds_ = null;

  return this;
};

/**
 * Modify the bounding box of the path.  This may cause the path to be
 * simplified (i.e. arcs converted to curves) as a side-effect.
 * @param {number} deltaX How far to translate the x coordinates.
 * @param {number} deltaY How far to translate the y coordinates.
 * @param {number} xFactor After translation, all x coordinates are multiplied
 *     by this number.
 * @param {number} yFactor After translation, all y coordinates are multiplied
 *     by this number.
 * @return {!goog.graphics.ext.Path} The path itself.
 */
goog.graphics.ext.Path.prototype.modifyBounds = function(deltaX, deltaY,
    xFactor, yFactor) {
  if (!this.isSimple()) {
    var simple = goog.graphics.Path.createSimplifiedPath(this);
    this.clear();
    this.appendPath(simple);
  }

  return this.transform(goog.graphics.AffineTransform.getScaleInstance(
      xFactor, yFactor).translate(deltaX, deltaY));
};

/**
 * Set the precomputed bounds.
 * @param {goog.math.Rect?} bounds The bounds to use, or set to null to clear
 *     and recompute on the next call to getBoundingBox.
 */
goog.graphics.ext.Path.prototype.useBoundingBox = function(bounds) {
  this.bounds_ = bounds && bounds.clone();
};

/**
 * @return {goog.math.Rect?} The bounding box of the path, or null if the
 *     path is empty.
 */
goog.graphics.ext.Path.prototype.getBoundingBox = function() {
  if (!this.bounds_ && !this.isEmpty()) {
    var minY;
    var minX = minY = Number.POSITIVE_INFINITY;
    var maxY;
    var maxX = maxY = Number.NEGATIVE_INFINITY;

    var simplePath = this.isSimple() ? this :
        goog.graphics.Path.createSimplifiedPath(this);
    simplePath.forEachSegment(function(type, points) {
      for (var i = 0, len = points.length; i < len; i += 2) {
        minX = Math.min(minX, points[i]);
        maxX = Math.max(maxX, points[i]);
        minY = Math.min(minY, points[i + 1]);
        maxY = Math.max(maxY, points[i + 1]);
      }
    });

    this.bounds_ = new goog.math.Rect(minX, minY, maxX - minX, maxY - minY);
  }

  return this.bounds_;
};