text:
from django.http import HttpResponseRedirect
import logging
import re

from readthedocs.projects.models import Project

log = logging.getLogger(__name__)

def project_and_path_from_request(request, path):
    if hasattr(request, 'slug'):
        project_slug = request.slug
    elif path.startswith('/docs/'):
        # In this case we use the docs without subdomains. So let's strip the
        # docs prefix.
        match = re.match(
            r'^/docs/(?P<project_slug>[^/]+)(?P<path>/.*)$',
            path)
        project_slug = match.groupdict()['project_slug']
        path = match.groupdict()['path']
    else:
        return None, path

    try:
        project = Project.objects.get(slug=project_slug)
    except Project.DoesNotExist:
        return None, path
    return project, path

def language_and_version_from_path(path):
    match = re.match(
        r'^/(?P<language>[^/]+)/(?P<version_slug>[^/]+)(?P<path>/.*)$',
        path)
    if match:
        language = match.groupdict()['language']
        version_slug = match.groupdict()['version_slug']
        path = match.groupdict()['path']
        return language, version_slug, path
    return None, None, path

def get_redirect_response(request, path):
    project, path = project_and_path_from_request(request, path)
    if not project:
        return None

    language = None
    version_slug = None
    if not project.single_version:
        language, version_slug, path = language_and_version_from_path(path)

    new_path = project.redirects.get_redirect_path(
        path=path, language=language, version_slug=version_slug)

    if new_path is None:
        return None

    # Re-use the domain and protocol used in the current request.
    # Redirects shouldn't change the domain, version or language.
    new_path = request.build_absolute_uri(new_path)
    return HttpResponseRedirect(new_path)


text:
import sys

if sys.platform == 'darwin':
	from mac.ode import *
elif sys.platform == 'win32':
	from win32.ode import *
	InitODE()
else:
	assert False, 'ODE not available for this platform'

redpajama_set_name: RedPajamaGithub


text:
module Para
  module Admin
    class SettingsComponentController < Para::Admin::ComponentController
      def show
        @settings = SettingsRails::Form.new
      end

      def update
        form = SettingsRails::Form.new
        form.settings_attributes = settings_params[:settings_attributes]
        form.save
        flash_message(:success, form)
        redirect_to admin_settings_path(@component)
      end

      private

      def settings_params
        params.require(:resource).permit(settings_attributes: [:key, :_type, :value])
      end
    end
  end
end


text:
* Path to runit's sv depend on system.

## 0.1.0

* Extract all supported services to separate gems
* Rename gem from capistrano-runit to capistrano-runit-core

# capistrano-runit
## 2.0.0.rc1 (unreleased)

* Add sidekiq module.
* Add puma module.
* Drop Capistrano 2.x support.

## 1.1.4 2014-02-06

* Added 'runit_unicorn_before_fork_code' variable for unicorn recipe.

## 1.1.3 2013-04-19

* Added recipes for sidekiq.
* Fixed: runit:setup should run on servers with db-role too.
* Added recipes for thinking-sphinx.
* Use rails_env variable instead of hardwired 'production' in run-unicorn.

## 1.1.2 2011-11-05

* Added double quotes for environment variables values.

## 1.1.1 2011-11-05

* default_environment hash was added in templates (special usefull for rbenv).

## 1.1.0 2011-10-23

* Bugfixes.
* Added Resque recipe.

## 1.0

* Initial release.


text:
[Chart.js](http://www.chartjs.org) is "Easy, object orientated client side graphs for designers and developers".

This is a package for simple integration in Rails.

## Installation

Add this line to your application's Gemfile:

    gem 'chartjs-rails'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install chartjs-rails

## Usage

Require using Assets pipeline

    //= require chart

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
using System;
using System.Threading.Tasks;

namespace Template10.Services.ExtendedSessionService
{
    public class ExtendedSessionService : IExtendedSessionService, IDisposable
    {
        public ExtendedServiceHelper _helper { get; }

        public ExtendedSessionService()
        {
            _helper = new ExtendedServiceHelper();
        }

        public async Task<bool> StartUnspecifiedAsync()
        {
            if (_helper.IsActive)
            {
                if (_helper.CurrentKind == ExtendedServiceHelper.SessionKinds.Unspecified)
                {
                    return true;
                }
                return false;
            }
            else
            {
                return await _helper.StartAsync(ExtendedServiceHelper.SessionKinds.Unspecified);
            }
        }

        public async Task<bool> StartSaveDataAsync()
        {
            if (_helper.IsActive)
            {
                if (_helper.CurrentKind == ExtendedServiceHelper.SessionKinds.SavingData)
                {
                    return true;
                }
                _helper.Stop();
            }
            return await _helper.StartAsync(ExtendedServiceHelper.SessionKinds.SavingData);
        }

        public void Dispose()
        {
            _helper.Dispose();
        }
    }
}


text:
package com.jwetherell.algorithms.sorts;

/**
 * Bubble sort is a simple sorting algorithm that works by repeatedly stepping
 * through the list to be sorted, comparing each pair of adjacent items and
 * swapping them if they are in the wrong order. The pass through the list is
 * repeated until no swaps are needed, which indicates that the list is sorted.
 *
 * Family: Exchanging.
 * Space: In-place.
 * Stable: True.
 *
 * Average case = O(n^2) Worst case = O(n^2) Best case = O(n)
 *
 * http://en.wikipedia.org/wiki/Bubble_sort
 *
 * @author Justin Wetherell <phishman3579@gmail.com>
 */
public class BubbleSort<T extends Comparable<T>> {

    private BubbleSort() { }

    public static <T extends Comparable<T>> T[] sort(T[] unsorted) {
        boolean swapped = true;
        int length = unsorted.length;
        while (swapped) {
            swapped = false;
            for (int i = 1; i < length; i++) {
                if (unsorted[i].compareTo(unsorted[i - 1]) < 0) {
                    swap(i, i - 1, unsorted);
                    swapped = true;
                }
            }
            length--;
        }
        return unsorted;
    }

    private static <T extends Comparable<T>> void swap(int index1, int index2, T[] unsorted) {
        T value = unsorted[index1];
        unsorted[index1] = unsorted[index2];
        unsorted[index2] = value;
    }
}


text:
'use strict';

var crypto = require('crypto');
var utils = require('../utils');

/**
 * Create a new random cipher key and initialization vector
 * @constructor
 * @license LGPL-3.0
 * @param {String|Buffer} [password] - The unique cipher password
 * @param {String|Buffer} [salt] - The unique salt
 */
function DataCipherKeyIv(pass, salt) {
  if (!(this instanceof DataCipherKeyIv)) {
    return new DataCipherKeyIv(pass, salt);
  }

  if (!pass && !salt) {
    pass = crypto.randomBytes(DataCipherKeyIv.PASS_BYTES);
    salt = crypto.randomBytes(DataCipherKeyIv.SALT_BYTES);
  }

  this._pass = Buffer.isBuffer(pass) ? pass : Buffer(pass, 'hex');
  this._salt = Buffer.isBuffer(salt) ? salt : Buffer(salt, 'hex');
  this._pbkdf2 = crypto.pbkdf2Sync(
    this._pass,
    this._salt,
    25000,
    512,
    'sha512'
  );
}

DataCipherKeyIv.PASS_BYTES = 512;
DataCipherKeyIv.SALT_BYTES = 32;

/**
 * Returns the cipher key and iv in an array
 * @returns {Array}
 */
DataCipherKeyIv.prototype.getCipherKeyIv = function() {
  return [
    Buffer(utils.sha256(this._pbkdf2), 'hex'),
    Buffer(utils.rmd160(this._salt), 'hex').slice(0, 16)
  ];
};

/**
 * Returns the key and iv as an array
 * @returns {Array}
 */
DataCipherKeyIv.prototype.toObject = function() {
  return {
    pass: this._pass.toString('hex'),
    salt: this._salt.toString('hex')
  };
};

/**
 * Returns the a {@link DataCipherKeyIv} from an object
 * @param {Object} object
 * @param {Buffer|String} object.pass - The unique password
 * @param {Buffer|String} object.salt - The unique salt
 * @returns {DataCipherKeyIv}
 */
DataCipherKeyIv.fromObject = function(object) {
  return new DataCipherKeyIv(object.pass, object.salt);
};

module.exports = DataCipherKeyIv;


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

namespace DGrok.Framework
{
    public enum TokenType
    {
        // Sentinel
        EndOfFile,
        // Comments
        SingleLineComment,
        CurlyBraceComment,
        ParenStarComment,
        CompilerDirective,
        // Values
        Identifier,
        Number,
        StringLiteral,
        #region Semikeywords (context keywords, can be used as identifiers)
        AbsoluteSemikeyword,
        AbstractSemikeyword,
        AssemblerSemikeyword,
        AssemblySemikeyword,
        AtSemikeyword,
        AutomatedSemikeyword,
        CdeclSemikeyword,
        ContainsSemikeyword,
        DefaultSemikeyword,
        DeprecatedSemikeyword,
        DispIdSemikeyword,
        DynamicSemikeyword,
        ExperimentalSemikeyword,
        ExportSemikeyword,
        ExternalSemikeyword,
        FarSemikeyword,
        FinalSemikeyword,
        ForwardSemikeyword,
        HelperSemikeyword,
        ImplementsSemikeyword,
        IndexSemikeyword,
        LocalSemikeyword,
        MessageSemikeyword,
        NameSemikeyword,
        NearSemikeyword,
        NoDefaultSemikeyword,
        OnSemikeyword,
        OperatorSemikeyword,
        OutSemikeyword,
        OverloadSemikeyword,
        OverrideSemikeyword,
        PackageSemikeyword,
        PascalSemikeyword,
        PlatformSemikeyword,
        PrivateSemikeyword,
        ProtectedSemikeyword,
        PublicSemikeyword,
        PublishedSemikeyword,
        ReadSemikeyword,
        ReadOnlySemikeyword,
        RegisterSemikeyword,
        ReintroduceSemikeyword,
        RequiresSemikeyword,
        ResidentSemikeyword,
        SafecallSemikeyword,
        SealedSemikeyword,
        StaticSemikeyword,
        StdcallSemikeyword,
        StoredSemikeyword,
        StrictSemikeyword,
        UnsafeSemikeyword,
        VarArgsSemikeyword,
        VirtualSemikeyword,
        WriteSemikeyword,
        WriteOnlySemikeyword,
        #endregion
        #region Real keywords (can't be used as identifiers, except after '.')
        AndKeyword,
        ArrayKeyword,
        AsKeyword,
        AsmKeyword,
        BeginKeyword,
        CaseKeyword,
        ClassKeyword,
        ConstKeyword,
        ConstructorKeyword,
        DestructorKeyword,
        DispInterfaceKeyword,
        DivKeyword,
        DoKeyword,
        DownToKeyword,
        ElseKeyword,
        EndKeyword,
        ExceptKeyword,
        ExportsKeyword,
        FileKeyword,
        FinalizationKeyword,
        FinallyKeyword,
        ForKeyword,
        FunctionKeyword,
        GotoKeyword,
        IfKeyword,
        ImplementationKeyword,
        InKeyword,
        InheritedKeyword,
        InitializationKeyword,
        InlineKeyword,
        InterfaceKeyword,
        IsKeyword,
        LabelKeyword,
        LibraryKeyword,
        ModKeyword,
        NilKeyword,
        NotKeyword,
        ObjectKeyword,
        OfKeyword,
        OrKeyword,
        PackedKeyword,
        ProcedureKeyword,
        ProgramKeyword,
        PropertyKeyword,
        RaiseKeyword,
        RecordKeyword,
        RepeatKeyword,
        ResourceStringKeyword,
        SetKeyword,
        ShlKeyword,
        ShrKeyword,
        StringKeyword,
        ThenKeyword,
        ThreadVarKeyword,
        ToKeyword,
        TryKeyword,
        TypeKeyword,
        UnitKeyword,
        UntilKeyword,
        UsesKeyword,
        VarKeyword,
        WhileKeyword,
        WithKeyword,
        XorKeyword,
        #endregion
        // Equality / inequality / assignment
        ColonEquals,
        EqualSign,
        GreaterOrEqual,
        GreaterThan,
        LessOrEqual,
        LessThan,
        NotEqual,
        // Punctuation
        AtSign,
        Caret,
        CloseBracket,
        CloseParenthesis,
        Colon,
        Comma,
        DivideBySign,
        Dot,
        DotDot,
        MinusSign,
        OpenBracket,
        OpenParenthesis,
        PlusSign,
        Semicolon,
        TimesSign,
    }
}


text:
package search

import (
	_ "embed"
	"log"
	"strings"

	"github.com/dchest/jsmin"
	"github.com/dchest/kkr/search/indexer"
)

//go:embed ui/stemmer.min.js
var stemmer string

//go:embed ui/search.js
var mainScript string

func GetSearchScript(searchIndexURL string) string {
	script := strings.ReplaceAll(mainScript, "__KKR_SEARCH_INDEX_URL__", searchIndexURL)
	script = strings.ReplaceAll(script, "__KKR_STOP_WORDS__", indexer.StopWords)
	out := stemmer + script
	minified, err := jsmin.Minify([]byte(out))
	if err != nil {
		log.Printf("Failed to minify search-script, continuing with unminified")
	} else {
		out = string(minified)
	}
	return out
}


text:
package v1alpha3

import (
	"time"

	accesslog "github.com/envoyproxy/go-control-plane/envoy/config/accesslog/v3"
	core "github.com/envoyproxy/go-control-plane/envoy/config/core/v3"
	mongo_proxy "github.com/envoyproxy/go-control-plane/envoy/config/filter/network/mongo_proxy/v2"
	mysql_proxy "github.com/envoyproxy/go-control-plane/envoy/config/filter/network/mysql_proxy/v1alpha1"
	redis_proxy "github.com/envoyproxy/go-control-plane/envoy/config/filter/network/redis_proxy/v2"
	thrift_proxy "github.com/envoyproxy/go-control-plane/envoy/config/filter/network/thrift_proxy/v2alpha1"
	listener "github.com/envoyproxy/go-control-plane/envoy/config/listener/v3"
	alsconfig "github.com/envoyproxy/go-control-plane/envoy/extensions/access_loggers/grpc/v3"
	tcp_proxy "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/tcp_proxy/v3"
	"github.com/envoyproxy/go-control-plane/pkg/wellknown"
	"github.com/golang/protobuf/ptypes"

	networking "istio.io/api/networking/v1alpha3"

	"istio.io/istio/pilot/pkg/features"
	"istio.io/istio/pilot/pkg/model"
	istio_route "istio.io/istio/pilot/pkg/networking/core/v1alpha3/route"
	"istio.io/istio/pilot/pkg/networking/util"
	"istio.io/istio/pkg/config/host"
	"istio.io/istio/pkg/config/protocol"
)

var (
	// redisOpTimeout is the default operation timeout for the Redis proxy filter.
	redisOpTimeout = 5 * time.Second

	// tcpGrpcAccessLog is used when access log service is enabled in mesh config.
	tcpGrpcAccessLog = buildTCPGrpcAccessLog()
)

// buildInboundNetworkFilters generates a TCP proxy network filter on the inbound path
func buildInboundNetworkFilters(push *model.PushContext, node *model.Proxy, instance *model.ServiceInstance) []*listener.Filter {
	clusterName := model.BuildSubsetKey(model.TrafficDirectionInbound, instance.ServicePort.Name,
		instance.Service.Hostname, instance.ServicePort.Port)
	statPrefix := clusterName
	// If stat name is configured, build the stat prefix from configured pattern.
	if len(push.Mesh.InboundClusterStatName) != 0 {
		statPrefix = util.BuildStatPrefix(push.Mesh.InboundClusterStatName, string(instance.Service.Hostname), "", instance.ServicePort, instance.Service.Attributes)
	}
	tcpProxy := &tcp_proxy.TcpProxy{
		StatPrefix:       statPrefix,
		ClusterSpecifier: &tcp_proxy.TcpProxy_Cluster{Cluster: clusterName},
	}
	tcpFilter := setAccessLogAndBuildTCPFilter(push, tcpProxy)
	return buildNetworkFiltersStack(node, instance.ServicePort, tcpFilter, statPrefix, clusterName)
}

// setAccessLog sets the AccessLog configuration in the given TcpProxy instance.
func setAccessLog(push *model.PushContext, config *tcp_proxy.TcpProxy) {
	if push.Mesh.AccessLogFile != "" {
		config.AccessLog = append(config.AccessLog, maybeBuildAccessLog(push.Mesh))
	}

	if push.Mesh.EnableEnvoyAccessLogService {
		config.AccessLog = append(config.AccessLog, tcpGrpcAccessLog)
	}
}

// setAccessLogAndBuildTCPFilter sets the AccessLog configuration in the given
// TcpProxy instance and builds a TCP filter out of it.
func setAccessLogAndBuildTCPFilter(push *model.PushContext, config *tcp_proxy.TcpProxy) *listener.Filter {
	setAccessLog(push, config)

	tcpFilter := &listener.Filter{
		Name:       wellknown.TCPProxy,
		ConfigType: &listener.Filter_TypedConfig{TypedConfig: util.MessageToAny(config)},
	}
	return tcpFilter
}

// buildOutboundNetworkFiltersWithSingleDestination takes a single cluster name
// and builds a stack of network filters.
func buildOutboundNetworkFiltersWithSingleDestination(push *model.PushContext, node *model.Proxy,
	statPrefix, clusterName string, port *model.Port) []*listener.Filter {

	tcpProxy := &tcp_proxy.TcpProxy{
		StatPrefix:       statPrefix,
		ClusterSpecifier: &tcp_proxy.TcpProxy_Cluster{Cluster: clusterName},
		// TODO: Need to set other fields such as Idle timeouts
	}

	idleTimeout, err := time.ParseDuration(node.Metadata.IdleTimeout)
	if idleTimeout > 0 && err == nil {
		tcpProxy.IdleTimeout = ptypes.DurationProto(idleTimeout)
	}

	tcpFilter := setAccessLogAndBuildTCPFilter(push, tcpProxy)
	return buildNetworkFiltersStack(node, port, tcpFilter, statPrefix, clusterName)
}

// buildOutboundNetworkFiltersWithWeightedClusters takes a set of weighted
// destination routes and builds a stack of network filters.
func buildOutboundNetworkFiltersWithWeightedClusters(node *model.Proxy, routes []*networking.RouteDestination,
	push *model.PushContext, port *model.Port, configMeta model.ConfigMeta) []*listener.Filter {

	statPrefix := configMeta.Name + "." + configMeta.Namespace
	clusterSpecifier := &tcp_proxy.TcpProxy_WeightedClusters{
		WeightedClusters: &tcp_proxy.TcpProxy_WeightedCluster{},
	}

	proxyConfig := &tcp_proxy.TcpProxy{
		StatPrefix:       statPrefix,
		ClusterSpecifier: clusterSpecifier,
		// TODO: Need to set other fields such as Idle timeouts
	}

	idleTimeout, err := time.ParseDuration(node.Metadata.IdleTimeout)
	if idleTimeout > 0 && err == nil {
		proxyConfig.IdleTimeout = ptypes.DurationProto(idleTimeout)
	}

	for _, route := range routes {
		service := node.SidecarScope.ServiceForHostname(host.Name(route.Destination.Host), push.ServiceByHostnameAndNamespace)
		if route.Weight > 0 {
			clusterName := istio_route.GetDestinationCluster(route.Destination, service, port.Port)
			clusterSpecifier.WeightedClusters.Clusters = append(clusterSpecifier.WeightedClusters.Clusters, &tcp_proxy.TcpProxy_WeightedCluster_ClusterWeight{
				Name:   clusterName,
				Weight: uint32(route.Weight),
			})
		}
	}

	// TODO: Need to handle multiple cluster names for Redis
	clusterName := clusterSpecifier.WeightedClusters.Clusters[0].Name
	tcpFilter := setAccessLogAndBuildTCPFilter(push, proxyConfig)
	return buildNetworkFiltersStack(node, port, tcpFilter, statPrefix, clusterName)
}

// buildNetworkFiltersStack builds a slice of network filters based on
// the protocol in use and the given TCP filter instance.
func buildNetworkFiltersStack(_ *model.Proxy, port *model.Port, tcpFilter *listener.Filter, statPrefix string, clusterName string) []*listener.Filter {
	filterstack := make([]*listener.Filter, 0)
	switch port.Protocol {
	case protocol.Mongo:
		filterstack = append(filterstack, buildMongoFilter(statPrefix), tcpFilter)
	case protocol.Redis:
		if features.EnableRedisFilter {
			// redis filter has route config, it is a terminating filter, no need append tcp filter.
			filterstack = append(filterstack, buildRedisFilter(statPrefix, clusterName))
		} else {
			filterstack = append(filterstack, tcpFilter)
		}
	case protocol.MySQL:
		if features.EnableMysqlFilter {
			filterstack = append(filterstack, buildMySQLFilter(statPrefix))
		}
		filterstack = append(filterstack, tcpFilter)
	case protocol.Thrift:
		if features.EnableThriftFilter {
			// Thrift filter has route config, it is a terminating filter, no need append tcp filter.
			filterstack = append(filterstack, buildThriftFilter(statPrefix))
		} else {
			filterstack = append(filterstack, tcpFilter)
		}
	default:
		filterstack = append(filterstack, tcpFilter)
	}

	return filterstack
}

// buildOutboundNetworkFilters generates a TCP proxy network filter for outbound
// connections. In addition, it generates protocol specific filters (e.g., Mongo
// filter).
func buildOutboundNetworkFilters(node *model.Proxy,
	routes []*networking.RouteDestination, push *model.PushContext,
	port *model.Port, configMeta model.ConfigMeta) []*listener.Filter {
	if len(routes) == 1 {
		service := node.SidecarScope.ServiceForHostname(host.Name(routes[0].Destination.Host), push.ServiceByHostnameAndNamespace)
		clusterName := istio_route.GetDestinationCluster(routes[0].Destination, service, port.Port)
		statPrefix := clusterName
		// If stat name is configured, build the stat prefix from configured pattern.
		if len(push.Mesh.OutboundClusterStatName) != 0 && service != nil {
			statPrefix = util.BuildStatPrefix(push.Mesh.OutboundClusterStatName, routes[0].Destination.Host,
				routes[0].Destination.Subset, port, service.Attributes)
		}
		return buildOutboundNetworkFiltersWithSingleDestination(push, node, statPrefix, clusterName, port)
	}
	return buildOutboundNetworkFiltersWithWeightedClusters(node, routes, push, port, configMeta)
}

// buildThriftFilter builds an outbound Envoy Thrift filter.
func buildThriftFilter(statPrefix string) *listener.Filter {
	thriftProxy := &thrift_proxy.ThriftProxy{
		StatPrefix: statPrefix, // TODO (peter.novotnak@reddit.com) Thrift stats are prefixed with thrift.<statPrefix> by Envoy.
	}

	out := &listener.Filter{
		Name:       wellknown.ThriftProxy,
		ConfigType: &listener.Filter_TypedConfig{TypedConfig: util.MessageToAny(thriftProxy)},
	}

	return out
}

// buildMongoFilter builds an outbound Envoy MongoProxy filter.
func buildMongoFilter(statPrefix string) *listener.Filter {
	// TODO: add a watcher for /var/lib/istio/mongo/certs
	// if certs are found use, TLS or mTLS clusters for talking to MongoDB.
	// User is responsible for mounting those certs in the pod.
	mongoProxy := &mongo_proxy.MongoProxy{
		StatPrefix: statPrefix, // mongo stats are prefixed with mongo.<statPrefix> by Envoy
		// TODO enable faults in mongo
	}

	out := &listener.Filter{
		Name:       wellknown.MongoProxy,
		ConfigType: &listener.Filter_TypedConfig{TypedConfig: util.MessageToAny(mongoProxy)},
	}

	return out
}

// buildOutboundAutoPassthroughFilterStack builds a filter stack with sni_cluster and tcp_proxy
// used by auto_passthrough gateway servers
func buildOutboundAutoPassthroughFilterStack(push *model.PushContext, node *model.Proxy, port *model.Port) []*listener.Filter {
	// First build tcp_proxy with access logs
	// then add sni_cluster to the front
	tcpProxy := buildOutboundNetworkFiltersWithSingleDestination(push, node, util.BlackHoleCluster, util.BlackHoleCluster, port)
	filterstack := make([]*listener.Filter, 0)
	filterstack = append(filterstack, &listener.Filter{
		Name: util.SniClusterFilter,
	})
	filterstack = append(filterstack, tcpProxy...)

	return filterstack
}

// buildRedisFilter builds an outbound Envoy RedisProxy filter.
// Currently, if multiple clusters are defined, one of them will be picked for
// configuring the Redis proxy.
func buildRedisFilter(statPrefix, clusterName string) *listener.Filter {
	redisProxy := &redis_proxy.RedisProxy{
		LatencyInMicros: true,       // redis latency stats are captured in micro seconds which is typically the case.
		StatPrefix:      statPrefix, // redis stats are prefixed with redis.<statPrefix> by Envoy
		Settings: &redis_proxy.RedisProxy_ConnPoolSettings{
			OpTimeout: ptypes.DurationProto(redisOpTimeout), // TODO: Make this user configurable
		},
		PrefixRoutes: &redis_proxy.RedisProxy_PrefixRoutes{
			CatchAllRoute: &redis_proxy.RedisProxy_PrefixRoutes_Route{
				Cluster: clusterName,
			},
		},
	}

	out := &listener.Filter{
		Name:       wellknown.RedisProxy,
		ConfigType: &listener.Filter_TypedConfig{TypedConfig: util.MessageToAny(redisProxy)},
	}

	return out
}

// buildMySQLFilter builds an outbound Envoy MySQLProxy filter.
func buildMySQLFilter(statPrefix string) *listener.Filter {
	mySQLProxy := &mysql_proxy.MySQLProxy{
		StatPrefix: statPrefix, // MySQL stats are prefixed with mysql.<statPrefix> by Envoy.
	}

	out := &listener.Filter{
		Name:       wellknown.MySQLProxy,
		ConfigType: &listener.Filter_TypedConfig{TypedConfig: util.MessageToAny(mySQLProxy)},
	}

	return out
}

func buildTCPGrpcAccessLog() *accesslog.AccessLog {
	fl := &alsconfig.TcpGrpcAccessLogConfig{
		CommonConfig: &alsconfig.CommonGrpcAccessLogConfig{
			LogName: tcpEnvoyAccessLogFriendlyName,
			GrpcService: &core.GrpcService{
				TargetSpecifier: &core.GrpcService_EnvoyGrpc_{
					EnvoyGrpc: &core.GrpcService_EnvoyGrpc{
						ClusterName: EnvoyAccessLogCluster,
					},
				},
			},
		},
	}

	fl.CommonConfig.FilterStateObjectsToLog = envoyWasmStateToLog

	return &accesslog.AccessLog{
		Name:       tcpEnvoyALSName,
		ConfigType: &accesslog.AccessLog_TypedConfig{TypedConfig: util.MessageToAny(fl)},
	}
}


text:
<?php

/* OCPlatformBundle::layout.html.twig */
class __TwigTemplate_4cf40d68b2a89d48098a0fa1d2f4f0f6d244c9203ff1424da6b23fd520d1e422 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 3
        try {
            $this->parent = $this->env->loadTemplate("::layout.html.twig");
        } catch (Twig_Error_Loader $e) {
            $e->setTemplateFile($this->getTemplateName());
            $e->setTemplateLine(3);

            throw $e;
        }

        $this->blocks = array(
            'title' => array($this, 'block_title'),
            'body' => array($this, 'block_body'),
            'ocplatform_body' => array($this, 'block_ocplatform_body'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "::layout.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 5
    public function block_title($context, array $blocks = array())
    {
        // line 6
        echo "  Announces - ";
        $this->displayParentBlock("title", $context, $blocks);
        echo "
";
    }

    // line 9
    public function block_body($context, array $blocks = array())
    {
        // line 10
        echo "
  ";
        // line 12
        echo "
Announces

  ";
        // line 17
        echo "  ";
        $this->displayBlock('ocplatform_body', $context, $blocks);
        // line 19
        echo "
";
    }

    // line 17
    public function block_ocplatform_body($context, array $blocks = array())
    {
        // line 18
        echo "  ";
    }

    public function getTemplateName()
    {
        return "OCPlatformBundle::layout.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  71 => 18,  68 => 17,  63 => 19,  60 => 17,  54 => 12,  51 => 10,  48 => 9,  41 => 6,  38 => 5,  11 => 3,);
    }
}


text:
namespace TelerikForumRSS
{
    public class RSS
    {
        public Channel Channel { get; set; }
    }
}


text:
<!DOCTYPE html>

  {%- block site_meta %}
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  {% if page and page.is_homepage %}<meta name="description" content="{{ config.site_description }}">{% endif %}
  {% if config.site_author %}<meta name="author" content="{{ config.site_author }}">{% endif %}
  {% if page and page.canonical_url %}<link rel="canonical" href="{{ page.canonical_url }}">{% endif %}
  {% if config.site_favicon %}<link rel="shortcut icon" href="{{ config.site_favicon|url }}">
  {% else %}<link rel="shortcut icon" href="{{ 'img/favicon.ico'|url }}">{% endif %}
  {%- endblock %}

  {%- block htmltitle %}
  <title>{% if page and page.title and not page.is_hompage %}{{ page.title }} - {% endif %}{{ config.site_name }}</title>
  {%- endblock %}

  {%- block styles %}
  <link href='https://fonts.googleapis.com/css?family=Lato:400,700|Source+Sans+Pro:400,700|Inconsolata:400,700' rel='stylesheet' type='text/css'>

  <link rel="stylesheet" href="{{ 'css/theme.css'|url }}" type="text/css" />
  <link rel="stylesheet" href="{{ 'css/theme_extra.css'|url }}" type="text/css" />
  {%- if config.theme.highlightjs %}
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/github.min.css">
  {%- endif %}
  {%- for path in config['extra_css'] %}
  <link href="{{ path|url }}" rel="stylesheet">
  {%- endfor %}
  {%- endblock %}

  {%- block libs %}
  {% if page %}

  {% endif %}

  {%- if config.theme.highlightjs %}

  {%- for lang in config.theme.hljs_languages %}

  {%- endfor %}

  {%- endif %}
  {%- endblock %}

  {%- block extrahead %} {% endblock %}

  {%- block analytics %}
  {% if config.google_analytics %}

  {% endif %}
  {%- endblock %}

    {# SIDE NAV, TOGGLES ON MOBILE #}

          Keras-contrib Docs

	  {%- block search_button %}
        {% if 'search' in config['plugins'] %}{% include "searchbox.html" %}{% endif %}
	  {%- endblock %}

        {%- block site_nav %}
        {%- set navlevel = 1 %}
        {%- for nav_item in nav %}
            {%- if nav_item.is_section %}

{{ nav_item.title }}

                    {%- for nav_item in nav_item.children %}

                        {%- include 'nav.html' %}

                    {%- endfor %}

            {%- elif config.theme.include_homepage_in_sidebar or (not nav_item == nav.homepage) %}

                        {%- include 'nav.html' %}

            {%- endif %}
        {%- endfor %}
    {%- endblock %}

      {# MOBILE NAV, TRIGGLES SIDE NAV ON TOGGLE #}

        {{ config.site_name }}

      {# PAGE CONTENT #}

          {% include "breadcrumbs.html" %}

              {% block content %}
                {{ page.content }}
              {% endblock %}

      {%- block footer %}
          {% include "footer.html" %}
      {% endblock %}

  {% include "versions.html" %}

  {%- block scripts %}

    {%- for path in config['extra_javascript'] %}

    {%- endfor %}

  {%- endblock %}

{% if page and page.is_homepage %}

{% endif %}


text:
import templateReader
import openpyxl
import os
import time
import logging

#Logging set-up information, check if the log directory exists, if not create it then set up the log
now=time.strftime("%c")
os.makedirs("logs",exist_ok=True)
logging.basicConfig(filename='logs/ExcelReader.log',level=logging.DEBUG)
logging.info('\nDate and Time:\n' + now + '\n-------------------------------\n')

try:
    os.remove("template.db")
except OSError:
    pass

wb = openpyxl.load_workbook(filename='Sample Excel Files/testExcel.xlsx')

for ws in wb.worksheets:
    templateReader.templateSheet(ws)


text:
<?php
namespace WL\AppBundle\Lib\View\Data\Converter\Filters\Callback\PriceRanges;

use Nokaut\ApiKit\Collection\Products;
use Nokaut\ApiKit\Ext\Data\Collection\Filters\PriceRanges;
use Nokaut\ApiKit\Ext\Data\Converter\Filters\Callback\PriceRanges\CallbackInterface;
use Nokaut\ApiKit\Ext\Data\Entity\Filter\PriceRange;

/**
 * Created by PhpStorm.
 * User: jjuszkiewicz
 * Date: 08.10.2014
 * Time: 15:30
 */
class SetName implements CallbackInterface
{

    /**
     * @param PriceRanges $priceRanges
     * @param Products $products
     */
    public function __invoke(PriceRanges $priceRanges, Products $products)
    {
        foreach ($priceRanges as $priceRange) {
            $name = "";
            /** @var PriceRange $priceRange */
            if ($priceRange->getMin()) {
                $name .= "od " . number_format($priceRange->getMin(), 2, ',', ' ') . " ";
            }
            if ($priceRange->getMax()) {
                $name .= "do " . number_format($priceRange->getMax(), 2, ',', ' ');
            }
            $priceRange->setName(trim($name));
        }
    }
}


text:
'use strict';

process.env.PATH += require('../build/jvm_dll_path.json');

var path = require('path');
var binaryPath = path.resolve(path.join(__dirname, "../build/Release/nodejavabridge_bindings.node"));
var bindings = require(binaryPath);

var java = module.exports = new bindings.Java();
java.classpath.push(path.resolve(__dirname, "../commons-lang3-node-java.jar"));
java.classpath.push(path.resolve(__dirname, __dirname, "../src-java"));
java.nativeBindingLocation = binaryPath;

var syncSuffix = undefined;
var asyncSuffix = undefined;

var SyncCall = function(obj, method) {
  if (syncSuffix === undefined)
    throw new Error('Sync call made before jvm created');
  var syncMethodName = method + syncSuffix;
  if (syncMethodName in obj)
    return obj[syncMethodName].bind(obj);
  else
    throw new Error('Sync method not found:' + syncMethodName);
}

java.onJvmCreated = function() {
  if (java.asyncOptions) {
    syncSuffix = java.asyncOptions.syncSuffix;
    asyncSuffix = java.asyncOptions.asyncSuffix;
    if (typeof syncSuffix !== 'string') {
      throw new Error('In asyncOptions, syncSuffix must be defined and must a string');
    }
    var promiseSuffix = java.asyncOptions.promiseSuffix;
    var promisify = java.asyncOptions.promisify;
    if (typeof promiseSuffix === 'string' && typeof promisify === 'function') {
      var methods = ['newInstance', 'callMethod', 'callStaticMethod'];
      methods.forEach(function (name) {
        java[name + promiseSuffix] = promisify(java[name]);
      });
    } else if (typeof promiseSuffix === 'undefined' && typeof promisify === 'undefined') {
      // no promises
    } else {
      throw new Error('In asyncOptions, if either promiseSuffix or promisify is defined, both most be.');
    }
  } else {
    syncSuffix = 'Sync';
    asyncSuffix = '';
  }
}

var MODIFIER_PUBLIC = 1;
var MODIFIER_STATIC = 8;

java.import = function(name) {
  var clazz = java.findClassSync(name); // TODO: change to Class.forName when classloader issue is resolved.
  var result = function() {
    var args = [name];
    for (var i = 0; i < arguments.length; i++) {
      args.push(arguments[i]);
    }
    return java.newInstanceSync.apply(java, args);
  };
  var i;

  result.class = clazz;

  // copy static fields
  var fields = SyncCall(clazz, 'getDeclaredFields')();
  for (i = 0; i < fields.length; i++) {
    var modifiers = SyncCall(fields[i], 'getModifiers')();
    if (((modifiers & MODIFIER_PUBLIC) === MODIFIER_PUBLIC)
      && ((modifiers & MODIFIER_STATIC) === MODIFIER_STATIC)) {
      var fieldName = SyncCall(fields[i], 'getName')();
      result.__defineGetter__(fieldName, function(name, fieldName) {
        return java.getStaticFieldValue(name, fieldName);
      }.bind(this, name, fieldName));
      result.__defineSetter__(fieldName, function(name, fieldName, val) {
        java.setStaticFieldValue(name, fieldName, val);
      }.bind(this, name, fieldName));
    }
  }

  var promisify = undefined;
  var promiseSuffix;
  if (java.asyncOptions && java.asyncOptions.promisify) {
    promisify = java.asyncOptions.promisify;
    promiseSuffix = java.asyncOptions.promiseSuffix;
  }

  // copy static methods
  var methods = SyncCall(clazz, 'getDeclaredMethods')();
  for (i = 0; i < methods.length; i++) {
    var modifiers = SyncCall(methods[i], 'getModifiers')();
    if (((modifiers & MODIFIER_PUBLIC) === MODIFIER_PUBLIC)
      && ((modifiers & MODIFIER_STATIC) === MODIFIER_STATIC)) {
      var methodName = SyncCall(methods[i], 'getName')();
      result[methodName + syncSuffix] = java.callStaticMethodSync.bind(java, name, methodName);
      if (typeof asyncSuffix === 'string') {
        result[methodName + asyncSuffix] = java.callStaticMethod.bind(java, name, methodName);
      }
      if (promisify) {
        result[methodName + promiseSuffix] = promisify(java.callStaticMethod.bind(java, name, methodName));
      }
    }
  }

  // copy static classes/enums
  var classes = SyncCall(clazz, 'getDeclaredClasses')();
  for (i = 0; i < classes.length; i++) {
    var modifiers = SyncCall(classes[i], 'getModifiers')();
    if (((modifiers & MODIFIER_PUBLIC) === MODIFIER_PUBLIC)
      && ((modifiers & MODIFIER_STATIC) === MODIFIER_STATIC)) {
      var className = SyncCall(classes[i], 'getName')();
      var simpleName = SyncCall(classes[i], 'getSimpleName')();
      Object.defineProperty(result, simpleName, {
        get: function(result, simpleName, className) {
          var c = java.import(className);

          // memoize the import
          var d = Object.getOwnPropertyDescriptor(result, simpleName);
          d.get = function(c) { return c; }.bind(null, c);
          Object.defineProperty(result, simpleName, d);

          return c;
        }.bind(this, result, simpleName, className),
        enumerable: true,
        configurable: true
      });
    }
  }

  return result;
};


text:
package com.softrism.roo.addon.senchatouch.beans;

import java.util.LinkedHashMap;

/**
 * Created with IntelliJ IDEA.
 * User: sudhir
 * Date: 2/4/14
 * Time: 1:02 PM
 * To change this template use File | Settings | File Templates.
 */
public class EntityBean
{
    private String name;
    private LinkedHashMap<String,String> attrMap;

    public EntityBean()
    {
    }

    public EntityBean(String name)
    {
        this.name = name;
    }

	public String getName() {
		return name;
	}

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

    public String getLowerCase() {
        return name.toLowerCase();
    }

    public LinkedHashMap<String, String> getAttrMap() {
        if(attrMap == null){
            attrMap = new LinkedHashMap<String, String>();
        }
        return attrMap;
    }

    public void setAttrMap(LinkedHashMap<String, String> attrMap) {
        this.attrMap = attrMap;
    }
}


text:
layout: popup
---

- File: `thormang3_feet_ft_module_msgs/BothWrench.msg`

- Message Definition
 ```
  string                  name
 geometry_msgs/Wrench    right
 geometry_msgs/Wrench    left
 ```

- Description
This message is used when publishing values to calibrate FT sensors in the [thormang3_feet_ft_module].

    * ` string name`
   name
   This field should be either "ft_air" or "ft_gnd".

    * `geometry_msgs/Wrench right`
   average output from the force torque sensor on the right foot
    * `geometry_msgs/Wrench left`
   average output from the force torque sensor on the left foot

[thormang3_feet_ft_module]: /docs/en/platform/thormang3/thormang3_ros_packages/#thormang3-feet-ft-module


text:
package com.commercetools.sunrise.common.reverserouter;

import play.mvc.Call;

public interface MyPersonalDetailsReverseRouter {

    Call myPersonalDetailsPageCall(final String languageTag);

    Call myPersonalDetailsProcessFormCall(final String languageTag);
}


text:
import http.cookies
from aiohttp import hdrs
from datetime import datetime, timedelta

def cors_headers(headers, nocreds=False):
    origin = headers.get(hdrs.ORIGIN, '*')
    if origin == 'null':
        origin = '*'
    cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),)

    ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS)
    if ac_headers:
        cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),)

    if origin != '*':
        return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, 'true'),)
    else:
        return cors

def session_cookie(request):
    cookie = request.cookies.get('JSESSIONID', 'dummy')
    cookies = http.cookies.SimpleCookie()
    cookies['JSESSIONID'] = cookie
    cookies['JSESSIONID']['path'] = '/'
    return ((hdrs.SET_COOKIE, cookies['JSESSIONID'].output(header='')[1:]),)

td365 = timedelta(days=365)
td365seconds = str(
    int((td365.microseconds +
         (td365.seconds + td365.days*24*3600) * 10**6) / 10**6))

def cache_headers():
    d = datetime.now() + td365
    return (
        (hdrs.ACCESS_CONTROL_MAX_AGE, td365seconds),
        (hdrs.CACHE_CONTROL, 'max-age=%s, public' % td365seconds),
        (hdrs.EXPIRES, d.strftime('%a, %d %b %Y %H:%M:%S')),
    )


text:
import * as assert from 'assert'
import * as t from '../../src/index'
import { assertSuccess, assertFailure } from './helpers'

describe('UnknownRecord', () => {
  describe('is', () => {
    it('should return `true` for valid objects', () => {
      const T = t.UnknownRecord
      assert.strictEqual(T.is({}), true)
      assert.strictEqual(T.is({ a: 1 }), true)
      assert.strictEqual(T.is(new Number()), true)
    })

    it('should return `false` for invalid objects', () => {
      const T = t.UnknownRecord
      assert.strictEqual(T.is(undefined), false)
      // #407
      assert.strictEqual(T.is([]), false)
    })
  })

  describe('decode', () => {
    it('should succeed validating a valid value', () => {
      const T = t.UnknownRecord
      assertSuccess(T.decode({}))
      assertSuccess(T.decode({ a: 1 }))
      assertSuccess(T.decode(new Number()))
    })

    it('should fail validating an invalid value', () => {
      const T = t.UnknownRecord
      assertFailure(T, 's', ['Invalid value "s" supplied to : UnknownRecord'])
      assertFailure(T, 1, ['Invalid value 1 supplied to : UnknownRecord'])
      assertFailure(T, true, ['Invalid value true supplied to : UnknownRecord'])
      assertFailure(T, null, ['Invalid value null supplied to : UnknownRecord'])
      assertFailure(T, undefined, ['Invalid value undefined supplied to : UnknownRecord'])
      // #407
      assertFailure(T, [], ['Invalid value [] supplied to : UnknownRecord'])
    })
  })
})

describe('UnknownArray', () => {
  it('should succeed decoding a valid value', () => {
    const T = t.UnknownArray
    assertSuccess(T.decode([]))
    assertSuccess(T.decode([1]))
  })

  it('should fail decoding an invalid value', () => {
    const T = t.UnknownArray
    assertFailure(T, 's', ['Invalid value "s" supplied to : UnknownArray'])
    assertFailure(T, 1, ['Invalid value 1 supplied to : UnknownArray'])
    assertFailure(T, true, ['Invalid value true supplied to : UnknownArray'])
    assertFailure(T, null, ['Invalid value null supplied to : UnknownArray'])
    assertFailure(T, undefined, ['Invalid value undefined supplied to : UnknownArray'])
  })
})

describe('null', () => {
  it('should succeed decoding a valid value', () => {
    assertSuccess(t.null.decode(null))
  })
  it('should fail decoding an invalid value', () => {
    const T = t.null
    assertFailure(T, 1, ['Invalid value 1 supplied to : null'])
  })
})

describe('undefined', () => {
  it('should succeed decoding a valid value', () => {
    assertSuccess(t.undefined.decode(undefined))
  })
  it('should fail decoding an invalid value', () => {
    const T = t.undefined
    assertFailure(T, 1, ['Invalid value 1 supplied to : undefined'])
  })
})

describe('unknown', () => {
  it('should decode any value', () => {
    assertSuccess(t.unknown.decode(null))
    assertSuccess(t.unknown.decode(undefined))
    assertSuccess(t.unknown.decode('foo'))
    assertSuccess(t.unknown.decode(1))
    assertSuccess(t.unknown.decode(true))
    assertSuccess(t.unknown.decode({}))
    assertSuccess(t.unknown.decode([]))
    assertSuccess(t.unknown.decode(/a/))
  })

  it('should accept any value', () => {
    assert.ok(t.unknown.is(null))
    assert.ok(t.unknown.is(undefined))
    assert.ok(t.unknown.is('foo'))
    assert.ok(t.unknown.is(1))
    assert.ok(t.unknown.is(true))
    assert.ok(t.unknown.is({}))
    assert.ok(t.unknown.is([]))
    assert.ok(t.unknown.is(/a/))
  })
})

describe('boolean', () => {
  it('should decode boolean values', () => {
    const T = t.boolean
    assertSuccess(T.decode(true))
    assertSuccess(T.decode(false))
  })

  it('should not decode non-boolean values', () => {
    const T = t.boolean
    assertFailure(T, 1, ['Invalid value 1 supplied to : boolean'])
  })
})

describe('bigint', () => {
  const T = t.bigint
  it('should decode bigint values', () => {
    assertSuccess(T.decode(BigInt(0)))
    assertSuccess(T.decode(BigInt(15)))
    const decodedBigNumber = T.decode(BigInt(Number.MAX_SAFE_INTEGER) + BigInt(4))
    assertSuccess(decodedBigNumber)
    if (decodedBigNumber._tag === 'Right') {
      assert.equal(decodedBigNumber.right.toString(), '9007199254740995')
    }
  })

  it('should not decode non-bigint values', () => {
    assertFailure(T, true, ['Invalid value true supplied to : bigint'])
    assertFailure(T, 'test', ['Invalid value "test" supplied to : bigint'])
    assertFailure(T, 123, ['Invalid value 123 supplied to : bigint'])
    assertFailure(T, {}, ['Invalid value {} supplied to : bigint'])
    assertFailure(T, [], ['Invalid value [] supplied to : bigint'])
    assertFailure(T, null, ['Invalid value null supplied to : bigint'])
    assertFailure(T, undefined, ['Invalid value undefined supplied to : bigint'])
  })
})

describe('Integer', () => {
  it('should validate integers', () => {
    // tslint:disable-next-line: deprecation
    const T = t.Integer
    assertSuccess(T.decode(1))
    assertFailure(T, 0.5, ['Invalid value 0.5 supplied to : Integer'])
    assertFailure(T, 'foo', ['Invalid value "foo" supplied to : Integer'])
    assertFailure(T, Infinity, ['Invalid value Infinity supplied to : Integer'])
    assertFailure(T, -Infinity, ['Invalid value -Infinity supplied to : Integer'])
  })
})

describe('void', () => {
  it('should support the alias `voidType`', () => {
    const T = t.void
    assertSuccess(t.voidType.decode(undefined))
    assertFailure(T, 1, ['Invalid value 1 supplied to : void'])
  })
})

describe('object', () => {
  it('should decode arrays', () => {
    // tslint:disable-next-line: deprecation
    assertSuccess(t.object.decode([]))
  })

  it('should decode objects', () => {
    // tslint:disable-next-line: deprecation
    assertSuccess(t.object.decode({}))
  })

  it('should fail with primitives', () => {
    // tslint:disable-next-line: deprecation
    const T = t.object
    assertFailure(T, 's', ['Invalid value "s" supplied to : object'])
    assertFailure(T, 1, ['Invalid value 1 supplied to : object'])
    assertFailure(T, true, ['Invalid value true supplied to : object'])
  })

  it('should fail with null and undefined', () => {
    // tslint:disable-next-line: deprecation
    const T = t.object
    assertFailure(T, null, ['Invalid value null supplied to : object'])
    assertFailure(T, undefined, ['Invalid value undefined supplied to : object'])
  })
})

describe('Function', () => {
  it('should decode functions', () => {
    // tslint:disable-next-line: deprecation
    assertSuccess(t.Function.decode(t.identity))
  })

  it('should not decode non-functions', () => {
    // tslint:disable-next-line: deprecation
    const T = t.Function
    assertFailure(T, 1, ['Invalid value 1 supplied to : Function'])
  })
})

describe('any', () => {
  it('should decode any value', () => {
    // tslint:disable-next-line: deprecation
    assertSuccess(t.any.decode(null))
    // tslint:disable-next-line: deprecation
    assertSuccess(t.any.decode(undefined))
    // tslint:disable-next-line: deprecation
    assertSuccess(t.any.decode('foo'))
    // tslint:disable-next-line: deprecation
    assertSuccess(t.any.decode(1))
    // tslint:disable-next-line: deprecation
    assertSuccess(t.any.decode(true))
    // tslint:disable-next-line: deprecation
    assertSuccess(t.any.decode(t.identity))
    // tslint:disable-next-line: deprecation
    assertSuccess(t.any.decode({}))
    // tslint:disable-next-line: deprecation
    assertSuccess(t.any.decode([]))
    // tslint:disable-next-line: deprecation
    assertSuccess(t.any.decode(/a/))
  })

  it('should accept any value', () => {
    // tslint:disable-next-line: deprecation
    assert.ok(t.any.is(null))
    // tslint:disable-next-line: deprecation
    assert.ok(t.any.is(undefined))
    // tslint:disable-next-line: deprecation
    assert.ok(t.any.is('foo'))
    // tslint:disable-next-line: deprecation
    assert.ok(t.any.is(1))
    // tslint:disable-next-line: deprecation
    assert.ok(t.any.is(true))
    // tslint:disable-next-line: deprecation
    assert.ok(t.any.is(t.identity))
    // tslint:disable-next-line: deprecation
    assert.ok(t.any.is({}))
    // tslint:disable-next-line: deprecation
    assert.ok(t.any.is([]))
    // tslint:disable-next-line: deprecation
    assert.ok(t.any.is(/a/))
  })
})

describe('never', () => {
  it('should not decode any value', () => {
    // tslint:disable-next-line: deprecation
    const T = (t.never as any) as t.Any
    assertFailure(T, null, ['Invalid value null supplied to : never'])
    assertFailure(T, undefined, ['Invalid value undefined supplied to : never'])
    assertFailure(T, 'foo', ['Invalid value "foo" supplied to : never'])
    assertFailure(T, 1, ['Invalid value 1 supplied to : never'])
    assertFailure(T, true, ['Invalid value true supplied to : never'])
    assertFailure(T, t.identity, ['Invalid value identity supplied to : never'])
    assertFailure(T, {}, ['Invalid value {} supplied to : never'])
    assertFailure(T, [], ['Invalid value [] supplied to : never'])
    assertFailure(T, /a/, ['Invalid value {} supplied to : never'])
  })

  it('should not accept any value', () => {
    // tslint:disable-next-line: deprecation
    assert.ok(!t.never.is(null))
    // tslint:disable-next-line: deprecation
    assert.ok(!t.never.is(undefined))
    // tslint:disable-next-line: deprecation
    assert.ok(!t.never.is('foo'))
    // tslint:disable-next-line: deprecation
    assert.ok(!t.never.is(1))
    // tslint:disable-next-line: deprecation
    assert.ok(!t.never.is(true))
    // tslint:disable-next-line: deprecation
    assert.ok(!t.never.is(t.identity))
    // tslint:disable-next-line: deprecation
    assert.ok(!t.never.is({}))
    // tslint:disable-next-line: deprecation
    assert.ok(!t.never.is([]))
    // tslint:disable-next-line: deprecation
    assert.ok(!t.never.is(/a/))
  })
})


text:
title: Ciburial Cyber Village
date: 2014-01-27 11:08:00 +07:00
nohibah: '032'
nama: Ayi Sumarna
lokasi: Bandung, Jawa Barat
lama: 6 Bulan
target: Semua Warga Desa Ciburial
keberhasilan: Semua warga Desa Ciburial, di wilayah Desa Ciburial dapat mengakses
  internet secara gratis.
tipe: Perangkat Jaringan Internet Nirkabel
strategi: Melalui sosialisasi, kegiatan roadshow, dan pelatihan-pelatihan. Pendampingan
  intensif.
dana: Rp. 500 Juta
deskripsi: Pembangunan Jaringan Wifi Desa di Wilayah Desa Ciburial untuk mendukung
  pemberdayaan masyarakat Desa Ciburial sebagai Desa Wisata
masalah: Menyediakan akses internet gratis di seluruh wilayah Desa Ciburial
solusi: Membangun titik-titik hostpot (wifi) gratis di seluruh wilayah Desa Ciburial
judul: Ciburial Cyber Village
organisasi: NA
kuantitas: NA
layout: hibah
---

![032](/static/img/hibahcms/032.png){: .img-responsive }{: width="350" }

### {{ page.nohibah }} - {{ page.title }}

{{ page.deskripsi }}


text:
@class TTGTextTagCollectionView;

@interface TTGExample4TableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet TTGTextTagCollectionView *tagView;
@property (weak, nonatomic) IBOutlet UILabel *label;

- (void)setTags:(NSArray <NSString *> *)tags;

@end


text:
import ece454750s15a1.*;
import org.apache.thrift.TProcessorFactory;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TServer.Args;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportFactory;

import java.lang.*;
import java.lang.Exception;
import java.lang.Integer;
import java.lang.NumberFormatException;
import java.lang.Override;
import java.lang.Runnable;
import java.lang.String;
import java.lang.System;
import java.lang.Thread;
import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class FEServer {

    public static FEPasswordHandler handler_password;
    public static FEPassword.Processor processor_password;

    public static FEManagementHandler handler_management;
    public static FEManagement.Processor processor_management;

    public static FEManagementHandler handler_sync_with_seed;
    public static FEManagement.Processor processor_sync_with_seed;

    public static FEManagementHandler handler_heartbeat;
    public static FEManagement.Processor processor_heartbeat;

    public static ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    public static String host;
    public static Integer pport;
    public static Integer mport;
    public static Integer ncores;
    public static String seed_string;

    public static Long uptime;
    public static PerfCounters perfManager = new PerfCounters();

    public static class SeedEntity {
        public String seedHostName;
        public Integer seedPort;

        public SeedEntity() {
            this.seedHostName = "UNSET";
            this.seedPort = null;
        }

        public void setEntityFields(String seedHostName, int port) {
            this.seedHostName = seedHostName;
            this.seedPort = port;
        }

        public String[] getEntityFields() {
            String[] seedArrRet = {this.seedHostName, this.seedPort.toString()};
            return seedArrRet;
        }

        public String getSeedHostName() {
            return this.seedHostName;
        }

        public int getSeedPortNumber() {
            return this.seedPort;
        }

        public void __debug_showInfo() {
            System.out.println("seedHostName = " + this.seedHostName);
            System.out.println("seedPort = " + this.seedPort);
        }
    }

    public static class FEServerEntity {
        public String nodeName;
        public Integer numCores;
        public String host;
        public Integer passwordPort;
        public Integer managementPort;

        public FEServerEntity() {
            this.nodeName = "UNSET";
            this.numCores = null;
            this.host = "UNSET";
            this.passwordPort = null;
            this.managementPort = null;
        }

        public FEServerEntity(String nodeName, Integer numCores, Integer passwordPort, Integer managementPort, String host) {
            this.nodeName = nodeName;
            this.numCores = numCores;
            this.passwordPort = passwordPort;
            this.managementPort = managementPort;
            this.host = host;
        }

        public void setEntityFields(String nodeName, String host, int pport, int mport, int numCores) {
            this.nodeName = nodeName;
            this.numCores = numCores;
            this.passwordPort = pport;
            this.managementPort = mport;
            this.host = host;
        }
        public String[] getEntityFields() {
            String[] FEServerArrRet = {this.nodeName, this.passwordPort.toString(), this.managementPort.toString()};
            return FEServerArrRet;
        }

        public String getFEServerHostName() {
            return this.host;
        }

        public void __debug_showInfo() {
            System.out.println("FEServerHostName = " + this.host);
            System.out.println("FEServerManagementPort = " + this.managementPort);
            System.out.println("FEServerPasswordPort = " + this.passwordPort);
        }
    }

    public static CopyOnWriteArrayList<FEServer.SeedEntity> seedEntityList = new CopyOnWriteArrayList<FEServer.SeedEntity>();
    public static CopyOnWriteArrayList<BEServer.BEServerEntity> BEServerList = new CopyOnWriteArrayList<BEServer.BEServerEntity>();
    public static CopyOnWriteArrayList<FEServer.FEServerEntity> FEServerList = new CopyOnWriteArrayList<FEServer.FEServerEntity>();

    public static List<String> getAllSeedPorts() {
        List<String> seedPortList = new ArrayList<String>();
        for(int i = 0; i < seedEntityList.size(); i++) {
            //System.out.println("[FEDEBUG] seedportlist = " + Integer.toString(seedEntityList.get(i).getSeedPortNumber()));
            seedPortList.add(Integer.toString(seedEntityList.get(i).getSeedPortNumber()));
        }
        return seedPortList;
    }

    public static boolean checkIfSeedOrNot(Integer mport) {
        List<String> seedPortList = getAllSeedPorts();
        // System.out.println("mport = " + mport);

        if(seedPortList.contains(Integer.toString(mport))) {
            // System.out.println("its a seeeeed!");
            return true;
        }
        else {
            // System.out.println("its NOT a seeeeed!");
            return false;
        }
    }

    private static void helpMenu() {
        System.out.println("java ece454750s15a1.FEServer");
        System.out.println("-host: name of the host on which this process will run");
        System.out.println("-pport: port number for A1Password Service");
        System.out.println("-mport: port number for A1Management Service");
        System.out.println("-ncores: number of cores available to the process");
        System.out.println("-seeds: CSV list of host:port pairs in FE nodes that are seeds.");
        System.out.println("Seed ports are in A1Management service");
    }

    public static void parseArgs(String[] args) {
        for (int i = 0; i < args.length - 1; i++) {
            //System.out.println("[FEServer] args[" + i + "] = " + args[i]);
            String args_to_check = args[i];
            if (args_to_check.equals("-host")) {
                host = args[i + 1];
            } else if (args_to_check.equals("-pport")) {
                pport = Integer.parseInt(args[i + 1]);
            } else if (args_to_check.equals("-mport")) {
                mport = Integer.parseInt(args[i + 1]);
            } else if (args_to_check.equals("-ncores")) {
                ncores = Integer.parseInt(args[i + 1]);
            } else if (args_to_check.equals("-seeds")) {
                seed_string = args[i + 1];
                String[] seeds_comma_delim = seed_string.split(",");
                for (String seed_pair : seeds_comma_delim) {
                    String[] seeds_colon_delim = seed_pair.split(":");
                    for (int j = 0; j < seeds_colon_delim.length - 1; j = j + 2) {
                        String seedHostName = seeds_colon_delim[j];
                        int seedPortNumber = Integer.parseInt(seeds_colon_delim[j + 1]);
                        SeedEntity seed = new SeedEntity();
                        seed.setEntityFields(seedHostName, seedPortNumber);
                        seedEntityList.add(seed);
                    }
                }
            }
        }
    }

    public static void printCurrentListOfBEs(CopyOnWriteArrayList<BEServer.BEServerEntity> listOfBEs) {
        for (BEServer.BEServerEntity BEServerNode : listOfBEs) {
            BEServerNode.__debug_showInfo();
        }
    }

    public static void main(String[] args) {
        try {
            if (args.length == 0) {
                System.out.print("Usage:");
                helpMenu();
            } else {
                FEServer.parseArgs(args);
            }

            // Uncomment this line to connect to FESeed.
            /*if (!checkIfSeedOrNot(mport)) {
                contactFESeed();
            }*/

            uptime = System.currentTimeMillis();

            // TODO: Do we actually need a Management port for FEServers?
            handler_management = new FEManagementHandler(BEServerList, FEServerList, perfManager, uptime);
            processor_management = new FEManagement.Processor(handler_management);
            Runnable simple_management = new Runnable() {
                @Override
                public void run() {
                    simple_management(processor_management);
                }
            };

            handler_password = new FEPasswordHandler(BEServerList, perfManager);
            processor_password = new FEPassword.Processor(handler_password);
            Runnable simple_password = new Runnable() {
                @Override
                public void run() {
                    simple_password(processor_password);
                }
            };

            new Thread(simple_management).start();
            new Thread(simple_password).start();

            // Thread to sync FEServers with FESeed to get all the BEServer information.
            handler_sync_with_seed = new FEManagementHandler(BEServerList, FEServerList, perfManager, uptime);
            processor_sync_with_seed = new FEManagement.Processor(handler_sync_with_seed);
            Runnable simple_sync_with_seed = new Runnable() {
                @Override
                public void run() {
                    simple_sync_with_seed(processor_sync_with_seed);
                }
            };

            if (checkIfSeedOrNot(mport)) {
                System.out.println("[FESeed] Running the sync_with_seed thread...");
            }
            else {
                System.out.println("[FEServer] Running the sync_with_seed thread...");
            }

            handler_heartbeat = new FEManagementHandler(BEServerList, FEServerList, perfManager, uptime);
            processor_heartbeat = new FEManagement.Processor(handler_heartbeat);
            Runnable simple_heartbeat = new Runnable() {
                @Override
                public void run() {
                    simple_heartbeat(processor_heartbeat);
                }
            };

            executor.scheduleAtFixedRate(simple_sync_with_seed, 0, 50, TimeUnit.MILLISECONDS);
            executor.scheduleAtFixedRate(simple_heartbeat, 0, 500, TimeUnit.MILLISECONDS);

        } catch (Exception x) {
            x.printStackTrace();
        }
    }

    public static void simple_management(FEManagement.Processor processor_management) {
        try {

            // This is FESeed
            // FIXME: Change the check condition from this to mport == seedlist.
            if (checkIfSeedOrNot(mport)) {
                System.out.println("[FESeed] Starting the FESeed management iface at mport = " + mport);
            } else { // TODO: Do we really need a management port for Non FESeed nodes?
                System.out.println("[FEServer] Starting the FEServer management iface at mport = " + mport);
            }

            // This is FESeed
            // Need this for other BEServers to register to the FESeed.
            if (checkIfSeedOrNot(mport)) {
                // Experiment 1: TThreadedPoolServer
                TServerTransport serverTransport = new TServerSocket(mport);

                TThreadPoolServer.Args args = new TThreadPoolServer.Args(serverTransport);
                args.protocolFactory(new TBinaryProtocol.Factory());
                args.transportFactory(new TTransportFactory());
                args.processorFactory(new TProcessorFactory(processor_management));
                args.minWorkerThreads(ncores);

                TThreadPoolServer server = new TThreadPoolServer(args);
                server.serve();
            }

            // This is FEServer
            if (!checkIfSeedOrNot(mport)) {
                // Experiment 1: TThreadedPoolServer
                TServerTransport serverTransport = new TServerSocket(mport);

                TThreadPoolServer.Args args = new TThreadPoolServer.Args(serverTransport);
                args.protocolFactory(new TBinaryProtocol.Factory());
                args.transportFactory(new TTransportFactory());
                args.processorFactory(new TProcessorFactory(processor_management));
                args.minWorkerThreads(ncores);

                TThreadPoolServer server = new TThreadPoolServer(args);
                server.serve();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Only executed if it's a FEServer. Not run for FESeeds.
    public static void simple_password(FEPassword.Processor processor_password) {
        try {
            // This is FEServer
            if (!checkIfSeedOrNot(mport)) {
                // Part 0: Open a server socket to receive requests from the client.
                System.out.println("[FEServer] Now listening to client requests on pport = " + pport);

                // Experiment 1: TThreadedPoolServer
                TServerTransport serverTransport = new TServerSocket(pport);
                TServer server = new TThreadPoolServer(
                        new TThreadPoolServer.Args(serverTransport).processor(processor_password));

                TThreadPoolServer.Args args = new TThreadPoolServer.Args(serverTransport);
                args.protocolFactory(new TBinaryProtocol.Factory());
                args.transportFactory(new TTransportFactory());
                args.processorFactory(new TProcessorFactory(processor_password));
                args.minWorkerThreads(ncores);

                server.serve();
            } else { // This is FESeed
                System.out.println("[FESeed] Password port in FESeed is not programmed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void simple_sync_with_seed(FEManagement.Processor processor_sync_with_seed) {
        try {
            // Get a random server to connect to each time.
            Random rand = new Random();
            int randomSeedIndex = rand.nextInt(seedEntityList.size());
            FEServer.SeedEntity seedEntity = seedEntityList.get(randomSeedIndex);

            // Connect to the randomly picked seed.
            // Only connect from this FE entity to another if it's different.
            if(seedEntity.getSeedPortNumber() != mport) {
                TTransport transport_sync_with_seed;
                if(checkIfSeedOrNot(mport)){
                    System.out.println("[FESeed] Gossiping with a seed on port = " + seedEntity.getSeedPortNumber());
                }
                else {
                    System.out.println("[FEServer] Gossiping with a seed on port = " + seedEntity.getSeedPortNumber());

                }
                transport_sync_with_seed = new TSocket(seedEntity.getSeedHostName(), seedEntity.getSeedPortNumber());
                transport_sync_with_seed.open();

                TProtocol protocol_sync_with_seed = new TBinaryProtocol(transport_sync_with_seed);
                FEManagement.Client client_management_sync_with_seed = new FEManagement.Client(protocol_sync_with_seed);

                List<String> newBEServersToAdd = client_management_sync_with_seed.getBEServerList();

                for (int i = 0; i < newBEServersToAdd.size(); i = i + 5) {
                    BEServer.BEServerEntity BEServerEntityToAdd = new BEServer.BEServerEntity(newBEServersToAdd.get(i), Integer.parseInt(newBEServersToAdd.get(i + 1)), Integer.parseInt(newBEServersToAdd.get(i + 2)), Integer.parseInt(newBEServersToAdd.get(i + 3)), newBEServersToAdd.get(i + 4));
                    if (!BEServerList.contains(BEServerEntityToAdd)) {
                        BEServerList.add(BEServerEntityToAdd);
                    }
                }

                // Print the updated list of members in the BEServerList
                if(checkIfSeedOrNot(mport)){
                    System.out.println("[FESeed] This FESeed is currently aware of [" + BEServerList.size() + "] BEServers");
                }
                else {
                    System.out.println("[FEServer] This FEServer is currently aware of [" + BEServerList.size() + "] BEServers");
                }

                transport_sync_with_seed.close();
            }
        }  catch (Exception e) {
            // We currently get here if the other seeds have not started yet...
            System.out.println("[FESeed] Waiting for other seeds in the system to start...");
            //e.printStackTrace();
        }
        // Add logic to catch ServiceUnavailableException.
    }

    public static void simple_heartbeat(FEManagement.Processor processor_heartbeat) {
        int BEServerIterator = 0;
        try {

            TTransport transport_simple_heartbeat;
            for (; BEServerIterator < BEServerList.size(); BEServerIterator = BEServerIterator + 1) {

                BEServer.BEServerEntity BEServerToCheck = BEServerList.get(BEServerIterator);

                if (checkIfSeedOrNot(mport)) {
                    System.out.println("[FESeed] Checking if BEServer at pport = " + BEServerToCheck.getBEPasswordPortNumber());
                } else {
                    System.out.println("[FEServer] Checking if BEServer at pport = " + BEServerToCheck.getBEPasswordPortNumber());
                }

                transport_simple_heartbeat = new TSocket(BEServerToCheck.getBEHostName(), BEServerToCheck.getBEPasswordPortNumber());
                transport_simple_heartbeat.open();

                // If we get this far, it means that the BEServer is still alive!
                transport_simple_heartbeat.close();

            }
        } catch (Exception e) { // Oh no! A BEServer was killed! :(
            BEServerList.remove(BEServerIterator);
        }
    }

    // TODO: Evaluate the need for this. Don't think we need this.
    // Only used if this is an actual FEServer and NOT a seed.
    private static void contactFESeed() throws TException {
        try {
            Random rand = new Random();
            int randomSeedIndex = rand.nextInt(seedEntityList.size());
            FEServer.SeedEntity seedEntity = seedEntityList.get(randomSeedIndex);

            TTransport transport;
            transport = new TSocket(seedEntity.getSeedHostName(), seedEntity.getSeedPortNumber());
            transport.open();

            TProtocol protocol = new TBinaryProtocol(transport);
            FEManagement.Client client_management = new FEManagement.Client(protocol);

            boolean joinResult = client_management.joinCluster("FEServer", "localhost", pport, mport, ncores);

            if (joinResult) {
                System.out.println("The FE Server was added to the cluster.");
            } else {
                System.out.println("The FE Server was NOT added to the cluster.");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}


text:
package org.rioproject.url.artifact;

import org.rioproject.resolver.RemoteRepository;

import java.util.ArrayList;
import java.util.List;

/**
 * Holds the attributes of a URL of type artifact.
 *
 *
The URL scheme that the {@code ArtifactURLConfiguration} decomposes is as follows:

 *
artifact:groupId/artifactId/version[/type[/classifier]][;[repository[@repositoryId]]

 *
 * @author Dennis Reedy
 */
public class ArtifactURLConfiguration {
    private String artifact;
    private final List<RemoteRepository> repositories = new ArrayList<RemoteRepository>();

    public ArtifactURLConfiguration(final String path) {
        String pathToUse = path;
        int index = pathToUse.indexOf(";");
        if(index!=-1) {
            String repositoryString = pathToUse.substring(index+1, pathToUse.length());
            pathToUse = pathToUse.substring(0, index);
            String[] parts = repositoryString.split(";");
            for(String s : parts) {
                String url;
                String id = null;
                String[] subParts = s.split("@");
                if(subParts.length>1) {
                    url = subParts[0];
                    id = subParts[1];
                } else {
                    url = subParts[0];
                }
                RemoteRepository r = new RemoteRepository();
                r.setUrl(url);
                r.setId(id);
                repositories.add(r);
            }
        }
        artifact = pathToUse.replaceAll("/", ":");
    }

    public String getArtifact() {
        return artifact;
    }

    public RemoteRepository[] getRepositories() {
        return repositories.toArray(new RemoteRepository[repositories.size()]);
    }
}


text:
<?php

require 'getallheaders.php';

header('Content-Type: application/json');

$data = array(
    'headers' => getallheaders(),
    'path' => $_SERVER['REQUEST_URI'],
    'request_method' => $_SERVER['REQUEST_METHOD'],
    'get' => $_GET,
    'post' => $_POST,
    'put' => $_POST,
);

//If the request is a put then get the file contents and try to parse the string into an array
if ($data['request_method'] == 'PUT') {
    parse_str(file_get_contents("php://input"), $put_data);
    $data['put'] = $put_data;
}
echo json_encode($data);


text:
* Test-driven development https://zh.wikipedia.org/wiki/%E6%B5%8B%E8%AF%95%E9%A9%B1%E5%8A%A8%E5%BC%80%E5%8F%91
* Add support for custom compiler version · Issue #265 · trufflesuite/truffle  https://github.com/trufflesuite/truffle/issues/265

log details

```
$ cd multisig && truffle init
$ curl -sL https://raw.githubusercontent.com/ConsenSys/MultiSigWallet/master/contracts/solidity/MultiSigWallet.sol -o contracts/MultiSigWallet.sol
$ truffle test

/home/dltdojo/smb/courses/ethereum/truffle/multisig/contracts/MultiSigWallet.sol:1:1: SyntaxError: Source file requires different compiler version (current compiler is 0.4.13+commit.0fb4cb1a.Emscripten.clang - note that nightly builds are considered to be strictly less than the released version
pragma solidity 0.4.4;
^---------------------^
,/home/dltdojo/smb/courses/ethereum/truffle/multisig/contracts/MultiSigWallet.sol:36:13: Warning: "throw" is deprecated in favour of "revert()", "require()" and "assert()".
            throw;
            ^---^
,/home/dltdojo/smb/courses/ethereum/truffle/multisig/contracts/MultiSigWallet.sol:42:13: Warning: "throw" is deprecated in favour of "revert()", "require()" and "assert()".
            throw;
            ^---^
,/home/dltdojo/smb/courses/ethereum/truffle/multisig/contracts/MultiSigWallet.sol:48:13: Warning: "throw" is deprecated in favour of "revert()", "require()" and "assert()".
            throw;
            ^---^
,/home/dltdojo/smb/courses/ethereum/truffle/multisig/contracts/MultiSigWallet.sol:54:13: Warning: "throw" is deprecated in favour of "revert()", "require()" and "assert()".
            throw;
            ^---^
,/home/dltdojo/smb/courses/ethereum/truffle/multisig/contracts/MultiSigWallet.sol:60:13: Warning: "throw" is deprecated in favour of "revert()", "require()" and "assert()".
            throw;
            ^---^
,/home/dltdojo/smb/courses/ethereum/truffle/multisig/contracts/MultiSigWallet.sol:66:13: Warning: "throw" is deprecated in favour of "revert()", "require()" and "assert()".
            throw;
            ^---^
,/home/dltdojo/smb/courses/ethereum/truffle/multisig/contracts/MultiSigWallet.sol:72:13: Warning: "throw" is deprecated in favour of "revert()", "require()" and "assert()".
            throw;
            ^---^
,/home/dltdojo/smb/courses/ethereum/truffle/multisig/contracts/MultiSigWallet.sol:78:13: Warning: "throw" is deprecated in favour of "revert()", "require()" and "assert()".
            throw;
            ^---^
,/home/dltdojo/smb/courses/ethereum/truffle/multisig/contracts/MultiSigWallet.sol:87:13: Warning: "throw" is deprecated in favour of "revert()", "require()" and "assert()".
            throw;
            ^---^
,/home/dltdojo/smb/courses/ethereum/truffle/multisig/contracts/MultiSigWallet.sol:111:17: Warning: "throw" is deprecated in favour of "revert()", "require()" and "assert()".
                throw;
                ^---^
,/home/dltdojo/smb/courses/ethereum/truffle/multisig/contracts/MultiSigWallet.sol:30:9: Warning: Variable is declared as a storage pointer. Use an explicit "storage" keyword to silence this warning.
        bytes data;
        ^--------^
,/home/dltdojo/smb/courses/ethereum/truffle/multisig/contracts/MultiSigWallet.sol:227:13: Warning: Variable is declared as a storage pointer. Use an explicit "storage" keyword to silence this warning.
            Transaction tx = transactions[transactionId];
            ^------------^
Compiliation failed. See above.

```

### upgrade MultiSigWallet.sol

* Type Checker: Fix invalid "specify storage keyword" warning for reference members of structs. https://github.com/ethereum/solidity/blob/develop/Changelog.md#0414-2017-07-31
* Upgrade to solidity 0.4.13 · Issue #484 · trufflesuite/truffle https://github.com/trufflesuite/truffle/issues/484

```
$ truffle test
```

### LogoVote TestCase

LogoVote2017/taipei-eth-logovote/test at master · EtherTW/LogoVote2017  https://github.com/EtherTW/LogoVote2017/tree/master/taipei-eth-logovote/test


text:
module Shipit
  class UndeployedCommit < DelegateClass(Commit)
    attr_reader :index

    def initialize(commit, index)
      super(commit)
      @index = index
    end

    def deploy_state(bypass_safeties = false)
      state = deployable? ? 'allowed' : status.state
      unless bypass_safeties
        state = 'deploying' if stack.active_task?
        state = 'locked' if locked?
      end
      state
    end

    def redeploy_state(bypass_safeties = false)
      state = 'allowed'
      unless bypass_safeties
        state = 'deploying' if stack.active_task?
      end
      state
    end

    def deploy_disallowed?
      !deployable? || !stack.deployable?
    end

    def deploy_discouraged?
      stack.maximum_commits_per_deploy && index >= stack.maximum_commits_per_deploy
    end
  end
end


text:
package Paws::ELBv2::ModifyRuleOutput;
  use Moose;
  has Rules => (is => 'ro', isa => 'ArrayRef[Paws::ELBv2::Rule]');

  has _request_id => (is => 'ro', isa => 'Str');
1;

### main pod documentation begin ###

=head1 NAME

Paws::ELBv2::ModifyRuleOutput

=head1 ATTRIBUTES

=head2 Rules => ArrayRef[L<Paws::ELBv2::Rule>]

Information about the rule.

=head2 _request_id => Str

=cut


text:
package org.kuali.rice.krad.uif.lifecycle.finalize;

import org.kuali.rice.krad.uif.lifecycle.FinalizeComponentPhase;
import org.kuali.rice.krad.uif.lifecycle.ViewLifecycle;
import org.kuali.rice.krad.uif.lifecycle.ViewLifecycleTaskBase;
import org.kuali.rice.krad.uif.util.LifecycleElement;

/**
 * Perform custom finalize behavior for the component defined by the helper.
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class HelperCustomFinalizeTask extends ViewLifecycleTaskBase<LifecycleElement> {

    /**
     * Constructor.
     *
     * @param phase The finalize phase for the component.
     */
    public HelperCustomFinalizeTask() {
        super(LifecycleElement.class);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public FinalizeComponentPhase getElementState() {
        return (FinalizeComponentPhase) super.getElementState();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void performLifecycleTask() {
        // invoke service override hook
        ViewLifecycle.getHelper().performCustomFinalize(getElementState().getElement(),
                ViewLifecycle.getModel(),
                getElementState().getParent());
    }

}


text:
<?php

namespace Novuso\Component\Service\Api;

use Closure;

interface ContainerInterface
{
    const UNDEFINED_NULL = 0;
    const UNDEFINED_EXCEPTION = 1;

    public function factory($name, Closure $callback);
    public function set($name, Closure $callback);
    public function get($name, $undefined = self::UNDEFINED_EXCEPTION);
    public function has($name);
    public function remove($name);
    public function setParameter($key, $value);
    public function getParameter($key, $default = null);
    public function hasParameter($key);
    public function removeParameter($key);
    public function isFrozen();
    public function freeze();
}


text:
#include <thrift/lib/cpp/concurrency/Mutex.h>

#include <thrift/lib/cpp/concurrency/Exception.h>
#include <thrift/lib/cpp/concurrency/Mutex-impl.h>
#include <thrift/lib/cpp/concurrency/ProfiledMutex.h>
#include <thrift/lib/cpp/concurrency/Util.h>

#include <assert.h>
#include <pthread.h>
#include <signal.h>
#include <errno.h>

using std::shared_ptr;

namespace apache { namespace thrift { namespace concurrency {

int Mutex::DEFAULT_INITIALIZER = PTHREAD_MUTEX_NORMAL;
int Mutex::RECURSIVE_INITIALIZER = PTHREAD_MUTEX_RECURSIVE;

class ProfiledPthreadMutex : public ProfiledTimedMutex<PthreadMutex> {
 public:
  explicit ProfiledPthreadMutex(int type)
    : ProfiledTimedMutex<PthreadMutex>(type) {}
};

class ProfiledPthreadRWMutex : public ProfiledSharedTimedMutex<PthreadRWMutex> {
};

Mutex::Mutex(int type) : impl_(std::make_shared<ProfiledPthreadMutex>(type)) {}

void* Mutex::getUnderlyingImpl() const {
  return impl_->getImpl().getUnderlyingImpl();
}

void Mutex::lock() const { impl_->lock(); }

bool Mutex::trylock() const { return impl_->try_lock(); }

bool Mutex::timedlock(int64_t ms) const {
  return impl_->try_lock_for(std::chrono::milliseconds {ms});
}

void Mutex::unlock() const { impl_->unlock(); }

bool Mutex::isLocked() const { return impl_->getImpl().isLocked(); }

ReadWriteMutex::ReadWriteMutex()
  : impl_(std::make_shared<ProfiledPthreadRWMutex>()) {}

void ReadWriteMutex::acquireRead() const { impl_->lock_shared(); }

void ReadWriteMutex::acquireWrite() const { impl_->lock(); }

bool ReadWriteMutex::timedRead(int64_t milliseconds) const {
  return impl_->try_lock_shared_for(std::chrono::milliseconds {milliseconds});
}

bool ReadWriteMutex::timedWrite(int64_t milliseconds) const {
  return impl_->try_lock_for(std::chrono::milliseconds {milliseconds});
}

bool ReadWriteMutex::attemptRead() const { return impl_->try_lock_shared(); }

bool ReadWriteMutex::attemptWrite() const { return impl_->try_lock(); }

void ReadWriteMutex::release() const { impl_->unlock(); }

NoStarveReadWriteMutex::NoStarveReadWriteMutex() : writerWaiting_(false) {}

void NoStarveReadWriteMutex::acquireRead() const
{
  if (writerWaiting_) {
    // writer is waiting, block on the writer's mutex until he's done with it
    mutex_.lock();
    mutex_.unlock();
  }

  ReadWriteMutex::acquireRead();
}

void NoStarveReadWriteMutex::acquireWrite() const
{
  // if we can acquire the rwlock the easy way, we're done
  if (attemptWrite()) {
    return;
  }

  // failed to get the rwlock, do it the hard way:
  // locking the mutex and setting writerWaiting will cause all new readers to
  // block on the mutex rather than on the rwlock.
  mutex_.lock();
  writerWaiting_ = true;
  ReadWriteMutex::acquireWrite();
  writerWaiting_ = false;
  mutex_.unlock();
}

bool NoStarveReadWriteMutex::timedRead(int64_t milliseconds) const
{
  if (writerWaiting_) {
    // writer is waiting, block on the writer's mutex until he's done with it
    if (!mutex_.timedlock(milliseconds)) {
      return false;
    }
    mutex_.unlock();
  }

  return ReadWriteMutex::timedRead(milliseconds);
}

bool NoStarveReadWriteMutex::timedWrite(int64_t milliseconds) const
{
  // if we can acquire the rwlock the easy way, we're done
  if (attemptWrite()) {
    return true;
  }

  // failed to get the rwlock, do it the hard way:
  // locking the mutex and setting writerWaiting will cause all new readers to
  // block on the mutex rather than on the rwlock.
  if (!mutex_.timedlock(milliseconds)) {
    return false;
  }
  writerWaiting_ = true;
  int ret = ReadWriteMutex::timedWrite(milliseconds);
  writerWaiting_ = false;
  mutex_.unlock();
  return ret == 0;
}

}}} // apache::thrift::concurrency