text:
package middlewares

import (
	"context"
	"net/http"

	"github.com/containous/mux"
	"github.com/containous/traefik/old/log"
)

// StripPrefixRegex is a middleware used to strip prefix from an URL request
type StripPrefixRegex struct {
	Handler http.Handler
	router  *mux.Router
}

// NewStripPrefixRegex builds a new StripPrefixRegex given a handler and prefixes
func NewStripPrefixRegex(handler http.Handler, prefixes []string) *StripPrefixRegex {
	stripPrefix := StripPrefixRegex{Handler: handler, router: mux.NewRouter()}

	for _, prefix := range prefixes {
		stripPrefix.router.PathPrefix(prefix)
	}

	return &stripPrefix
}

func (s *StripPrefixRegex) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	var match mux.RouteMatch
	if s.router.Match(r, &match) {
		params := make([]string, 0, len(match.Vars)*2)
		for key, val := range match.Vars {
			params = append(params, key)
			params = append(params, val)
		}

		prefix, err := match.Route.URL(params...)
		if err != nil || len(prefix.Path) > len(r.URL.Path) {
			log.Error("Error in stripPrefix middleware", err)
			return
		}
		rawReqPath := r.URL.Path
		r.URL.Path = r.URL.Path[len(prefix.Path):]
		if r.URL.RawPath != "" {
			r.URL.RawPath = r.URL.RawPath[len(prefix.Path):]
		}
		r = r.WithContext(context.WithValue(r.Context(), StripPrefixKey, rawReqPath))
		r.Header.Add(ForwardedPrefixHeader, prefix.Path)
		r.RequestURI = ensureLeadingSlash(r.URL.RequestURI())
		s.Handler.ServeHTTP(w, r)
		return
	}
	http.NotFound(w, r)
}

// SetHandler sets handler
func (s *StripPrefixRegex) SetHandler(Handler http.Handler) {
	s.Handler = Handler
}


text:
//
//  ========================================================================
//  Copyright (c) 1995-2013 Mort Bay Consulting Pty. Ltd.
//  ------------------------------------------------------------------------
//  All rights reserved. This program and the accompanying materials
//  are made available under the terms of the Eclipse Public License v1.0
//  and Apache License v2.0 which accompanies this distribution.
//
//      The Eclipse Public License is available at
//      http://www.eclipse.org/legal/epl-v10.html
//
//      The Apache License v2.0 is available at
//      http://www.opensource.org/licenses/apache2.0.php
//
//  You may elect to redistribute this code under either of these licenses.
//  ========================================================================
//

package org.eclipse.jetty.http;

import java.io.IOException;

/**
 * Abstract interface for a connection Parser for use by Jetty.
 */
public interface Parser
{
    void returnBuffers();
    void reset();

    boolean isComplete();

    /**
     * @return True if progress made
     * @throws IOException
     */
    boolean parseAvailable() throws IOException;

    boolean isMoreInBuffer() throws IOException;

    boolean isIdle();

    boolean isPersistent();

    void setPersistent(boolean persistent);

}

redpajama_set_name: RedPajamaGithub


text:
package handler

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"reflect"
	"strconv"
	"strings"
)

//buep base_url_embeded_params
func parseParams(r *http.Request, buep map[string]string) (params map[string]interface{}, err error) {

	if err = r.ParseForm(); err != nil {
		return
	}

	if strings.Contains(r.UserAgent(), "(Dart)") {
		params, err = jsonParams(r)
	} else {
		ctype := r.Header.Get("Content-Type")
		//fmt.Println(ctype)
		switch {
		case strings.Contains(ctype, "application/json"):
			data := make([]byte, r.ContentLength)
			if _, err = r.Body.Read(data); err != nil {
				return
			}
			var values url.Values
			values, err = url.ParseQuery(string(data))
			if err != nil {
				return
			}
			params, err = encodedParams(values)
		case strings.Contains(ctype, "application/x-www-form-urlencoded"):
			params, err = encodedParams(r.Form)
		// case strings.Contains(ctype, "multipart/form-data"):
		// 	params, err = encodedParams(r.Form)
		// case strings.Contains(ctype, "application/xml"):
		// 	params, err = encodedParams(r.Form)
		default:
			params, err = encodedParams(r.Form)
		}
	}
	if err != nil {
		return
	}
	for k, v := range buep {
		params[k] = v
	}
	return
}

func jsonParams(r *http.Request) (map[string]interface{}, error) {
	if r.ContentLength < 1 {
		return map[string]interface{}{}, nil
	}
	data := make([]byte, r.ContentLength)

	if _, err := r.Body.Read(data); err != nil && err != io.EOF {
		return nil, err
	}

	//fmt.Println(string(data))

	var params map[string]interface{}
	if err := json.Unmarshal(data, &params); err != nil {
		return nil, err
	}
	return params, nil
}
func encodedParams(Values map[string][]string) (map[string]interface{}, error) {
	r := map[string]interface{}{}
	for k, v := range Values {
		var value interface{}
		if len(v) == 1 {
			value = v[0]
		} else {
			return nil, fmt.Errorf("%s has multiple[%d] values (%v)", k, len(v), v)
		}
		if strings.Contains(k, "]") {
			strs := strings.SplitN(strings.Replace(k, "]", "", -1), "[", -1)
			lastKey := strs[len(strs)-1]
			rr := r
			strs = strs[:len(strs)-1]
			for _, e := range strs {
				if rr[e] == nil {
					rr[e] = make(map[string]interface{})
				}
				rr = rr[e].(map[string]interface{})
			}
			rr[lastKey] = value
		} else {
			r[k] = value
		}
	}
	return r, nil
}

func parseArgsFromParams(t reflect.Type, args []string, p map[string]interface{}) ([]reflect.Value, error) {
	if len(args) == 0 {
		return nil, nil
	}
	res := make([]reflect.Value, t.NumIn())
	for i := 0; i < t.NumIn(); i++ {
		kind := t.In(i).Kind().String()
		inp := t.In(i).String()
		switch kind {
		case "map":
			if reflectValue, err := makeMapParam(args[i], inp, p); err != nil {
				return res, err
			} else {
				res[i] = reflectValue
			}
		case "array", "slice":
			if reflectValue, err := makeArrayParam(args[i], inp, p); err != nil {
				return res, err
			} else {
				res[i] = reflectValue
			}

		default:
			if reflectValue, err := makeBuiltinParam(args[i], inp, p); err != nil {
				return res, err
			} else {
				res[i] = reflectValue
			}
		}
	}
	return res, nil
}
func makeArrayParam(name, typ string, p map[string]interface{}) (rv reflect.Value, err error) {
	var value interface{}
	if v, ok := p[name]; ok {
		value = v
	} else {
		return rv, fmt.Errorf("argument '%s' is not set by client ", name)
	}
	switch typ {
	case "[]string":
		if res, ok := value.([]string); ok {
			return reflect.ValueOf(res), nil
		} else {
			return rv, fmt.Errorf("argument '%s' is not matching the expected type %s ", name, typ)
		}
	}
	return rv, fmt.Errorf("argument '%s' format '%s' is not matching the basic types (like int,string,map slice,etc)", name, typ)
}

func makeMapParam(name, typ string, p map[string]interface{}) (rv reflect.Value, err error) {
	var value map[string]interface{}
	if v, ok := p[name]; ok {
		if v0, ok0 := v.(map[string]interface{}); ok0 {
			value = v0
		} else {
			return rv, fmt.Errorf("argument '%s' is not matching the expected type %s ", name, typ)
		}
	} else {
		return rv, fmt.Errorf("argument '%s' is not set by client ", name)
	}

	switch typ {
	case "map[string]string":
		res := map[string]string{}
		for k, v := range value {
			res[k] = v.(string)
		}
		return reflect.ValueOf(res), nil
	case "map[string]interface {}":
		return reflect.ValueOf(value), nil
	}
	return rv, fmt.Errorf("argument '%s' format '%s' is not matching the basic types (like int,string,map slice,etc)", name, typ)
}

func makeBuiltinParam(name, typ string, p map[string]interface{}) (rv reflect.Value, err error) {
	var value string
	if v, ok := p[name]; ok {
		if v0, ok0 := v.(string); ok0 {
			value = v0
		} else {
			return rv, fmt.Errorf("argument '%s' is not matching the expected type %s ", name, typ)
		}
	} else {
		return rv, fmt.Errorf("argument '%s' is not set by client ", name)
	}

	switch typ {
	case "int":
		if v, err := strconv.ParseInt(value, 10, 0); err != nil {
			return rv, err
		} else {
			return reflect.ValueOf(int(v)), nil
		}
	case "int8":
		if v, err := strconv.ParseInt(value, 10, 8); err != nil {
			return rv, err
		} else {
			return reflect.ValueOf(int8(v)), nil
		}

	case "int16":
		if v, err := strconv.ParseInt(value, 10, 16); err != nil {
			return rv, err
		} else {
			return reflect.ValueOf(int16(v)), nil
		}
	case "int32":
		if v, err := strconv.ParseInt(value, 10, 32); err != nil {
			return rv, err
		} else {
			return reflect.ValueOf(int32(v)), nil
		}
	case "int64":
		if v, err := strconv.ParseInt(value, 10, 64); err != nil {
			return rv, err
		} else {
			return reflect.ValueOf(int64(v)), nil
		}
	case "uint":
		if v, err := strconv.ParseUint(value, 10, 0); err != nil {
			return rv, err
		} else {
			return reflect.ValueOf(uint(v)), nil
		}
	case "uint8":
		if v, err := strconv.ParseUint(value, 10, 8); err != nil {
			return rv, err
		} else {
			return reflect.ValueOf(uint8(v)), nil
		}

	case "uint16":
		if v, err := strconv.ParseUint(value, 10, 16); err != nil {
			return rv, err
		} else {
			return reflect.ValueOf(uint16(v)), nil
		}
	case "uint32":
		if v, err := strconv.ParseUint(value, 10, 32); err != nil {
			return rv, err
		} else {
			return reflect.ValueOf(uint32(v)), nil
		}
	case "uint64":
		if v, err := strconv.ParseUint(value, 10, 64); err != nil {
			return rv, err
		} else {
			return reflect.ValueOf(uint64(v)), nil
		}
	case "float32":
		if v, err := strconv.ParseFloat(value, 32); err != nil {
			return rv, err
		} else {
			return reflect.ValueOf(float32(v)), nil
		}
	case "float64":
		if v, err := strconv.ParseFloat(value, 64); err != nil {
			return rv, err
		} else {
			return reflect.ValueOf(float64(v)), nil
		}
	case "bool":
		if v, err := strconv.ParseBool(value); err != nil {
			return rv, err
		} else {
			return reflect.ValueOf(v), nil
		}
	case "string":
		return reflect.ValueOf(value), nil
	default:
		//return reflect.ValueOf(value), nil
	}
	return rv, fmt.Errorf("format '%s' is not matching the basic types (like int,string,map slice,etc)", typ)
}


text:
layout: project
title:  "Structure for Unifying Multiple Modeling Alternatives (SUMMA)"
ref: SUMMA
date:   2016-08-03 16:55:00
categories:
- models
img: summa.jpg
img2: summa.png
sponsors: National Science Foundation, U.S. Army Corps of Engineers, Bureau of Reclamation, NOAA, NASA (check)
modelhomepage: https://www.ral.ucar.edu/projects/summa
projectlink: hydrologic_modeling
teamline1: "NCAR: Martyn Clark (PI), Grey Nearing, Andy Newman, Naoki Mizukami, Nans Addor, Andy Wood, Ethan Gutmann"
teamline2: "University of Washington: Bart Nijssen, Jessica Lundquist, Michael Ou"
teamline3: "U.S. Army Corps of Engineers: Jeff Arnold"
teamline4: "Bureau of Reclamation: Levi Brekke"
contacts: "Contact: Martyn Clark - mclark@ucar.edu | Julie Vano – jvano@ucar.edu"
tags: [models]
---

SUMMA is a hydrologic modeling approach that is built on a common set of conservation equations and a common numerical solver, which together constitute the structural core of the model. Different modeling approaches can then be implemented within the structural core, enabling a controlled and systematic analysis of alternative modeling options, and providing insight for future model development.


text:
module Geminabox
  class HttpDummy < HttpAdapter

    attr_accessor :default_response

    def get_content(*args)
      default_response
    end

    def get(*args)
      Response.new default_response
    end

    def post(*args)
      Response.new default_response
    end

    def set_auth(*args)
      true
    end

    class Response
      attr_reader :default
      def initialize(default)
        @default = default
      end

      def body
        default
      end

      def status
        default
      end

      def code
        default
      end
    end

  end
end


text:
angular.module('services')
.factory('getData', function() {
  return {
    groups: [],
    sites: []
  }
})


text:
class YellowBlockBmp : public WoopsiGfx::BitmapWrapper {
public:
	YellowBlockBmp();
};

#endif


text:
from django.views.generic import TemplateView
from tarifas.core import PackageSet

class Home(TemplateView):

    template_name = 'tarifas/home.html'

    def get_params(self):
        def parse_param(attrname, default=0):
            try:
                return int(self.request.GET.get(attrname, default))
            except Exception:
                return default
        return {
            'min_minutes': parse_param('min_minutes'),
            'min_mb': parse_param('min_mb'),
            'min_sms': parse_param('min_sms'),
        }

    def get_data(self, **kwargs):
        pset = PackageSet(**kwargs)
        cheapests = pset.get_cheapest_packages()
        return {
            'cheapest': cheapests[0] if cheapests else None,
            'other_options': cheapests[1:4]
        }

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        params = self.get_params()
        context['params'] = params
        context['data'] = self.get_data(**params)
        return context


text:
.todo {
  margin-bottom: 15px;
}

.completed span {
  text-decoration: line-through;
  color: lightgray;
}


text:
@interface TestVersionComparison : SenTestCase
{}

- (void) testSVNVersionNewerThanSVNVersion;
- (void) testSVNVersionEqualToSVNVersion;

- (void) testDevelopmentVersionNewerThanDevelopmentVersion;
- (void) testDevelopmentVersionEqualToDevelopmentVersion;

- (void) testAlphaNewerThanAlpha;
- (void) testAlphaEqualToAlpha;

- (void) testBetaNewerThanBeta;
- (void) testBetaEqualToBeta;

- (void) testReleaseNewerThanRelease;
- (void) testReleaseEqualToRelease;

#pragma mark -

- (void) testReleaseNewerThanBeta;
- (void) testReleaseNewerThanAlpha;
- (void) testReleaseNewerThanDevelopmentVersion;
- (void) testReleaseNewerThanSVNVersion;

- (void) testBetaNewerThanAlpha;
- (void) testBetaNewerThanDevelopmentVersion;
- (void) testBetaNewerThanSVNVersion;

- (void) testAlphaNewerThanDevelopmentVersion;
- (void) testAlphaNewerThanSVNVersion;

- (void) testDevelopmentVersionNewerThanSVNVersion;

@end


text:
<!--

    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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.

-->

![logo](site/img/pulsar.png)

Pulsar is a distributed pub-sub messaging platform with a very
flexible messaging model and an intuitive client API.

https://pulsar.apache.org

## Main features
* Horizontally scalable (Millions of independent topics and millions
  of messages published per second)
* Strong ordering and consistency guarantees
* Low latency durable storage
* Topic and queue semantics
* Load balancer
* Designed for being deployed as a hosted service:
  * Multi-tenant
  * Authentication
  * Authorization
  * Quotas
  * Support mixing very different workloads
  * Optional hardware isolation
* Keeps track of consumer cursor position
* REST API for provisioning, admin and stats
* Geo replication
* Transparent handling of partitioned topics
* Transparent batching of messages

## Build Pulsar

Requirements:
 * Java JDK 1.8
 * Maven

Compile and install:

```bash
$ mvn install -DskipTests
```

Start standalone Pulsar service:

```bash
$ bin/pulsar standalone
```

Check https://pulsar.apache.org for documentation and examples.

## Build Pulsar docs

Refer to the docs [README](site2/README.md).

## Contact

##### Mailing lists

| Name                                                                          | Scope                           |                                                                 |                                                                     |                                                                              |
|:------------------------------------------------------------------------------|:--------------------------------|:----------------------------------------------------------------|:--------------------------------------------------------------------|:-----------------------------------------------------------------------------|
| [users@pulsar.apache.org](mailto:users@pulsar.apache.org) | User-related discussions        | [Subscribe](mailto:users-subscribe@pulsar.apache.org) | [Unsubscribe](mailto:users-unsubscribe@pulsar.apache.org) | [Archives](http://mail-archives.apache.org/mod_mbox/pulsar-users/) |
| [dev@pulsar.apache.org](mailto:dev@pulsar.apache.org)     | Development-related discussions | [Subscribe](mailto:dev-subscribe@pulsar.apache.org)   | [Unsubscribe](mailto:dev-unsubscribe@pulsar.apache.org)   | [Archives](http://mail-archives.apache.org/mod_mbox/pulsar-dev/)   |

##### Slack

Pulsar slack channel at https://apache-pulsar.slack.com/

You can self-register at https://apache-pulsar.herokuapp.com/

## License

Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0

## Crypto Notice

This distribution includes cryptographic software. The country in which you currently reside may have restrictions on the import, possession, use, and/or re-export to another country, of encryption software. BEFORE using any encryption software, please check your country's laws, regulations and policies concerning the import, possession, or use, and re-export of encryption software, to see if this is permitted. See <http://www.wassenaar.org/> for more information.

The U.S. Government Department of Commerce, Bureau of Industry and Security (BIS), has classified this software as Export Commodity Control Number (ECCN) 5D002.C.1, which includes information security software using or performing cryptographic functions with asymmetric algorithms. The form and manner of this Apache Software Foundation distribution makes it eligible for export under the License Exception ENC Technology Software Unrestricted (TSU) exception (see the BIS Export Administration Regulations, Section 740.13) for both object code and source code.

The following provides more details on the included cryptographic software: Pulsar uses the SSL library from Bouncy Castle written by http://www.bouncycastle.org.


text:
/*
 * Do not modify this file. This file is generated from the config-2014-11-12.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;

using Amazon.ConfigService.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;

namespace Amazon.ConfigService.Model.Internal.MarshallTransformations
{
    /// <summary>
    /// Response Unmarshaller for DeliveryChannel Object
    /// </summary>
    public class DeliveryChannelUnmarshaller : IUnmarshaller<DeliveryChannel, XmlUnmarshallerContext>, IUnmarshaller<DeliveryChannel, JsonUnmarshallerContext>
    {
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        DeliveryChannel IUnmarshaller<DeliveryChannel, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public DeliveryChannel Unmarshall(JsonUnmarshallerContext context)
        {
            context.Read();
            if (context.CurrentTokenType == JsonToken.Null)
                return null;

            DeliveryChannel unmarshalledObject = new DeliveryChannel();

            int targetDepth = context.CurrentDepth;
            while (context.ReadAtDepth(targetDepth))
            {
                if (context.TestExpression("configSnapshotDeliveryProperties", targetDepth))
                {
                    var unmarshaller = ConfigSnapshotDeliveryPropertiesUnmarshaller.Instance;
                    unmarshalledObject.ConfigSnapshotDeliveryProperties = unmarshaller.Unmarshall(context);
                    continue;
                }
                if (context.TestExpression("name", targetDepth))
                {
                    var unmarshaller = StringUnmarshaller.Instance;
                    unmarshalledObject.Name = unmarshaller.Unmarshall(context);
                    continue;
                }
                if (context.TestExpression("s3BucketName", targetDepth))
                {
                    var unmarshaller = StringUnmarshaller.Instance;
                    unmarshalledObject.S3BucketName = unmarshaller.Unmarshall(context);
                    continue;
                }
                if (context.TestExpression("s3KeyPrefix", targetDepth))
                {
                    var unmarshaller = StringUnmarshaller.Instance;
                    unmarshalledObject.S3KeyPrefix = unmarshaller.Unmarshall(context);
                    continue;
                }
                if (context.TestExpression("snsTopicARN", targetDepth))
                {
                    var unmarshaller = StringUnmarshaller.Instance;
                    unmarshalledObject.SnsTopicARN = unmarshaller.Unmarshall(context);
                    continue;
                }
            }

            return unmarshalledObject;
        }

        private static DeliveryChannelUnmarshaller _instance = new DeliveryChannelUnmarshaller();

        /// <summary>
        /// Gets the singleton.
        /// </summary>
        public static DeliveryChannelUnmarshaller Instance
        {
            get
            {
                return _instance;
            }
        }
    }
}


text:
CREATE TABLE SS_DAILY_RAW_HEMA AS
WITH ss_raw_hema as (
  SELECT
    icud.subject_id,
    icud.icustay_id,
    icud.seq as icustay_day,
    case
      when le.value < 20 then 4
      when le.value < 50 then 3
      when le.value < 100 then 2
      when le.value < 150 then 1
      else 0
    end as hematologic_score
  from
    icustay_population icud,
    mimic2v30.labevents le
  where le.subject_id = icud.subject_id
  AND le.charttime >= icud.icustay_day_intime
  AND le.charttime <= icud.icustay_day_outtime
  AND le.itemid in (51278)
)
--select * from ss_raw_hema;

,ss_daily_raw_hema as (
  SELECT
    subject_id,
    icustay_id,
    icustay_day,
    max(hematologic_score) as hematologic_score
  from
    ss_raw_hema
  GROUP BY subject_id, icustay_id, icustay_day
)

SELECT * FROM ss_daily_raw_hema;


text: Exercises and such from Types and Programming Languages book (Pierce)


text:
<?php

namespace vxPHP\Tests\Http\File;

use vxPHP\File\FilesystemFile;

class FakeFile extends FilesystemFile
{
    private $realpath;

    public function __construct($realpath)
    {
        $this->realpath = $realpath;
        $this->fileInfo = new FakeFileInfo();
    }

    public function getPath(): string
    {
        return $this->realpath;
    }

    public function getFilename(): string
    {
        return pathinfo($this->realpath, PATHINFO_BASENAME);
    }
}

class FakeFileInfo extends \SplFileInfo
{
    public function __construct()
    {

    }
    public function getSize(): int
    {
        return 42;
    }

    public function getMTime(): int
    {
        return time();
    }

    public function isReadable(): bool
    {
        return true;
    }
}


text:
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace ZE.UI.WPF.Spy.Common.Converter
{
  /// <summary>
  /// Converts an object to a value of type <see cref="Visibility"/>
  /// object == null: Visibility.Collapsed
  /// object != null: Visibility.Visible
  /// By providing a parameter with boolean value "true", the return values
  /// are inverted.
  /// </summary>
  public class NullToVisibilityConverter : ValueConverterMarkupExtensionBase, IValueConverter
  {
    #region IValueConverter Members

    /// <summary>
    /// See <see cref="IValueConverter.Convert"/>.
    /// </summary>
    /// <param name="value">The value produced by the binding source.</param>
    /// <param name="targetType">The type of the binding target property.</param>
    /// <param name="parameter">The converter parameter to use.</param>
    /// <param name="culture">The culture to use in the converter.</param>
    /// <returns>
    /// A converted value. If the method returns null, the valid null value is used.
    /// </returns>
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
      if (targetType != typeof(Visibility))
      {
        throw new NotSupportedException("Only target type Visibility supported!");
      }

      var invert = false;
      if (parameter != null)
      {
        if (parameter is string)
        {
          invert = bool.Parse(parameter.ToString());
        }
        else
        {
          invert = (bool)parameter;
        }
      }

      bool visible = value != null;

      if (invert)
      {
        visible = !visible;
      }

      return visible ? Visibility.Visible : Visibility.Collapsed;
    }

    /// <summary>
    /// See <see cref="IValueConverter.ConvertBack"/>.
    /// </summary>
    /// <param name="value">The value that is produced by the binding target.</param>
    /// <param name="targetType">The type to convert to.</param>
    /// <param name="parameter">The converter parameter to use.</param>
    /// <param name="culture">The culture to use in the converter.</param>
    /// <returns>
    /// A converted value. If the method returns null, the valid null value is used.
    /// </returns>
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
      throw new NotImplementedException();
    }

    #endregion
  }
}


text:
using System;

namespace nMqtt.SampleApp.ViewModels
{
	public class ShellViewModel
	{
		public ShellViewModel()
		{
		}

		public string WindowTitle
		{
			get
			{
				return "nMqtt Sample Test Application";
			}
		}
	}
}


text:
package designpattern.singleton;

/**
 * Created by joybar on 29/05/17.
 */
public class Singleton5 {
    private static class SingletonHolder {
        private static final Singleton5 INSTANCE = new Singleton5();
    }

    private Singleton5() {
    }

    public static final Singleton5 getInstance() {
        return SingletonHolder.INSTANCE;
    }
}


text:
IBOID afCreateIndexBuffer(const AFIndex* indi, int numIndi)
{
	IBOID indexBuffer;
	D3D11_SUBRESOURCE_DATA subresData = { indi, 0, 0 };
	deviceMan11.GetDevice()->CreateBuffer(&CD3D11_BUFFER_DESC(numIndi * sizeof(AFIndex), D3D11_BIND_INDEX_BUFFER), &subresData, &indexBuffer);
	return indexBuffer;
}

VBOID afCreateVertexBuffer(int size, const void* data)
{
	VBOID vbo;
	D3D11_SUBRESOURCE_DATA subresData = { data, 0, 0 };
	deviceMan11.GetDevice()->CreateBuffer(&CD3D11_BUFFER_DESC(size, D3D11_BIND_VERTEX_BUFFER), &subresData, &vbo);
	return vbo;
}

VBOID afCreateDynamicVertexBuffer(int size)
{
	VBOID vbo;
	deviceMan11.GetDevice()->CreateBuffer(&CD3D11_BUFFER_DESC(size, D3D11_BIND_VERTEX_BUFFER, D3D11_USAGE_DYNAMIC, D3D11_CPU_ACCESS_WRITE), nullptr, &vbo);
	return vbo;
}

UBOID afCreateUBO(int size)
{
	UBOID ubo;
	deviceMan11.GetDevice()->CreateBuffer(&CD3D11_BUFFER_DESC(size, D3D11_BIND_CONSTANT_BUFFER, D3D11_USAGE_DYNAMIC, D3D11_CPU_ACCESS_WRITE), nullptr, &ubo);
	return ubo;
}

SRVID afCreateTexture2D(AFDTFormat format, const IVec2& size, void *image)
{
	CD3D11_TEXTURE2D_DESC desc(format, size.x, size.y, 1, 1, D3D11_BIND_SHADER_RESOURCE);
	D3D11_SUBRESOURCE_DATA r = { image, (uint32_t)size.x * 4, 0 };
	ComPtr<ID3D11Texture2D> tex;
	ComPtr<ID3D11ShaderResourceView> srv;
	deviceMan11.GetDevice()->CreateTexture2D(&desc, &r, &tex);
	deviceMan11.GetDevice()->CreateShaderResourceView(tex.Get(), nullptr, &srv);
	return srv;
}

SRVID afCreateTexture2D(AFDTFormat format, const TexDesc& afDesc, int mipCount, const AFTexSubresourceData datas[])
{
	ComPtr<ID3D11Texture2D> tex;
	CD3D11_TEXTURE2D_DESC desc(format, afDesc.size.x, afDesc.size.y, afDesc.arraySize, mipCount, D3D11_BIND_SHADER_RESOURCE, D3D11_USAGE_DEFAULT, 0, 1, 0, afDesc.isCubeMap ? D3D11_RESOURCE_MISC_TEXTURECUBE : 0);
	deviceMan11.GetDevice()->CreateTexture2D(&desc, datas, &tex);
	CD3D11_SHADER_RESOURCE_VIEW_DESC srvDesc(afDesc.isCubeMap ? D3D_SRV_DIMENSION_TEXTURECUBE : D3D_SRV_DIMENSION_TEXTURE2D, desc.Format, 0, -1);
	ComPtr<ID3D11ShaderResourceView> srv;
	deviceMan11.GetDevice()->CreateShaderResourceView(tex.Get(), &srvDesc, &srv);
	return srv;
}

SRVID afCreateDynamicTexture(AFDTFormat format, const IVec2& size)
{
	CD3D11_TEXTURE2D_DESC desc(format, size.x, size.y, 1, 1, D3D11_BIND_SHADER_RESOURCE, D3D11_USAGE_DYNAMIC, D3D11_CPU_ACCESS_WRITE);
	ComPtr<ID3D11Texture2D> tex;
	ComPtr<ID3D11ShaderResourceView> srv;
	deviceMan11.GetDevice()->CreateTexture2D(&desc, nullptr, &tex);
	deviceMan11.GetDevice()->CreateShaderResourceView(tex.Get(), nullptr, &srv);
	return srv;
}

SAMPLERID afCreateSampler(SamplerFilter filter, SamplerWrap wrap)
{
	D3D11_SAMPLER_DESC  desc;
	ZeroMemory(&desc, sizeof(desc));
	desc.AddressU = wrap;
	desc.AddressV = wrap;
	desc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
	desc.MaxAnisotropy = 1;
	desc.Filter = filter;
	desc.ComparisonFunc = D3D11_COMPARISON_NEVER;
	desc.MaxLOD = D3D11_FLOAT32_MAX;
	ComPtr<ID3D11SamplerState> sampler;
	deviceMan11.GetDevice()->CreateSamplerState(&desc, &sampler);
	return sampler;
}

void afBindBufferToBindingPoint(UBOID ubo, UINT uniformBlockBinding)
{
	deviceMan11.GetContext()->VSSetConstantBuffers(uniformBlockBinding, 1, ubo.GetAddressOf());
	deviceMan11.GetContext()->PSSetConstantBuffers(uniformBlockBinding, 1, ubo.GetAddressOf());
}

void afBindTextureToBindingPoint(SRVID srv, UINT textureBindingPoint)
{
	deviceMan11.GetContext()->PSSetShaderResources(textureBindingPoint, 1, srv.GetAddressOf());
}

void afBindSamplerToBindingPoint(SAMPLERID sampler, UINT textureBindingPoint)
{
	deviceMan11.GetContext()->PSSetSamplers(textureBindingPoint, 1, sampler.GetAddressOf());
}

void afWriteBuffer(const IBOID p, const void* buf, int size)
{
	assert(p);
#ifdef _DEBUG
	D3D11_BUFFER_DESC desc;
	p->GetDesc(&desc);
	if (size > (int)desc.ByteWidth) {
		return;
	}
#endif
	D3D11_MAPPED_SUBRESOURCE m;
	HRESULT hr = deviceMan11.GetContext()->Map(p.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &m);
	memcpy(m.pData, buf, size);
	deviceMan11.GetContext()->Unmap(p.Get(), 0);
}

void afWriteTexture(SRVID srv, const TexDesc& desc, const void* buf)
{
	ComPtr<ID3D11Resource> res;
	srv->GetResource(&res);
	assert(res);
	ComPtr<ID3D11Texture2D> tx;
	res.As(&tx);
	assert(tx);

//	D3D11_TEXTURE2D_DESC desc;
//	tx->GetDesc(&desc);

	D3D11_MAPPED_SUBRESOURCE m;
	HRESULT hr = deviceMan11.GetContext()->Map(tx.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &m);
	memcpy(m.pData, buf, desc.size.x * desc.size.y * 4);
	deviceMan11.GetContext()->Unmap(tx.Get(), 0);
}

IBOID afCreateQuadListIndexBuffer(int numQuads)
{
	std::vector<AFIndex> indi;
	int numIndi = numQuads * 6;
	indi.resize(numIndi);
	for (int i = 0; i < numIndi; i++)
	{
		static int tbl[] = { 0, 1, 2, 1, 3, 2 };
		int rectIdx = i / 6;
		int vertIdx = i % 6;
		indi[i] = rectIdx * 4 + tbl[vertIdx];
	}
	return afCreateIndexBuffer(&indi[0], numIndi);
}

void afDrawIndexedTriangleStrip(int numIndices, int start)
{
	deviceMan11.GetContext()->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
	deviceMan11.GetContext()->DrawIndexed(numIndices, start, 0);
}

void afDrawIndexedTriangleList(int numIndices, int start)
{
	deviceMan11.GetContext()->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
	deviceMan11.GetContext()->DrawIndexed(numIndices, start, 0);
}

void afDrawTriangleStrip(int numVertices, int start)
{
	deviceMan11.GetContext()->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
	deviceMan11.GetContext()->Draw(numVertices, start);
}

void afDrawLineList(int numVertices, int start)
{
	deviceMan11.GetContext()->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_LINELIST);
	deviceMan11.GetContext()->Draw(numVertices, start);
}

void afDrawIndexedInstancedTriangleList(int instanceCount, int numIndices, int start)
{
	deviceMan11.GetContext()->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
	deviceMan11.GetContext()->DrawIndexedInstanced(numIndices, instanceCount, start, 0, 0);
}

void afCullMode(CullMode cullMode)
{
	ID3D11RasterizerState* rs;
	CD3D11_RASTERIZER_DESC rasterDesc(D3D11_DEFAULT);
	switch (cullMode) {
	case CM_DISABLE:
		rasterDesc.CullMode = D3D11_CULL_NONE;
		break;
	case CM_CCW:
		rasterDesc.CullMode = D3D11_CULL_BACK;
		rasterDesc.FrontCounterClockwise = TRUE;
		break;
	case CM_CW:
		rasterDesc.CullMode = D3D11_CULL_BACK;
		rasterDesc.FrontCounterClockwise = FALSE;
		break;
	}
	deviceMan11.GetDevice()->CreateRasterizerState(&rasterDesc, &rs);
	deviceMan11.GetContext()->RSSetState(rs);
	SAFE_RELEASE(rs);
}

void afBlendMode(BlendMode mode)
{
	if (mode == BM_NONE) {
		deviceMan11.GetContext()->OMSetBlendState(nullptr, nullptr, 0xffffffff);
		return;
	}

	CD3D11_BLEND_DESC bdesc(D3D11_DEFAULT);
	bdesc.RenderTarget[0].BlendEnable = TRUE;
	bdesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
	bdesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
	bdesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
	bdesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
	bdesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
	bdesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
	bdesc.RenderTarget[0].RenderTargetWriteMask = D3D10_COLOR_WRITE_ENABLE_ALL;
	ID3D11BlendState* bs;
	deviceMan11.GetDevice()->CreateBlendState(&bdesc, &bs);
	FLOAT factor[] = {0, 0, 0, 0};
	deviceMan11.GetContext()->OMSetBlendState(bs, factor, 0xffffffff);
	SAFE_RELEASE(bs);
}

void afDepthStencilMode(DepthStencilMode mode)
{
	ComPtr<ID3D11DepthStencilState> ds;
	D3D11_DEPTH_STENCIL_DESC desc = CD3D11_DEPTH_STENCIL_DESC(CD3D11_DEFAULT());
	switch(mode) {
	case DSM_DISABLE:
		desc.DepthEnable = FALSE;
		break;
	case DSM_DEPTH_ENABLE:
		break;	// same as default
	case DSM_DEPTH_CLOSEREQUAL_READONLY:
		desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO;
		desc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL;
		break;
	}
	deviceMan11.GetDevice()->CreateDepthStencilState(&desc, &ds);
	deviceMan11.GetContext()->OMSetDepthStencilState(ds.Get(), 1);
}

IVec2 afGetTextureSize(SRVID srv)
{
	ComPtr<ID3D11Resource> res;
	srv->GetResource(&res);
	assert(res);
	ComPtr<ID3D11Texture2D> tx;
	res.As(&tx);
	assert(tx);

	D3D11_TEXTURE2D_DESC desc;
	tx->GetDesc(&desc);
	return IVec2((int)desc.Width, (int)desc.Height);
}

VAOID afCreateVAO(const InputElement elements[], int numElements, int numBuffers, VBOID* const vertexBufferIds, const int* strides, IBOID ibo)
{
	(void)elements;
	(void)numElements;
	return new FakeVAO(numBuffers, vertexBufferIds, strides, nullptr, ibo);
}

void AFRenderTarget::InitForDefaultRenderTarget()
{
	Destroy();
	renderTargetView = deviceMan11.GetDefaultRenderTarget();
	renderTargetView->AddRef();
	depthStencilView = deviceMan11.GetDefaultDepthStencil();
	depthStencilView->AddRef();
}

void AFRenderTarget::Init(IVec2 size, DXGI_FORMAT colorFormat, DXGI_FORMAT depthStencilFormat)
{
	(void)depthStencilFormat;

	Destroy();
	texSize = size;
	CD3D11_TEXTURE2D_DESC tDesc(colorFormat, size.x, size.y, 1, 1, D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS);
	ID3D11Texture2D* tex;
	HRESULT hr = deviceMan11.GetDevice()->CreateTexture2D(&tDesc, NULL, &tex);
	CD3D11_RENDER_TARGET_VIEW_DESC rDesc(D3D11_RTV_DIMENSION_TEXTURE2D, tDesc.Format);
	hr = deviceMan11.GetDevice()->CreateRenderTargetView(tex, &rDesc, &renderTargetView);
	CD3D11_SHADER_RESOURCE_VIEW_DESC sDesc(D3D11_SRV_DIMENSION_TEXTURE2D, tDesc.Format);
	hr = deviceMan11.GetDevice()->CreateShaderResourceView(tex, &sDesc, &shaderResourceView);
	CD3D11_UNORDERED_ACCESS_VIEW_DESC uDesc(D3D11_UAV_DIMENSION_TEXTURE2D, tDesc.Format);
	hr = deviceMan11.GetDevice()->CreateUnorderedAccessView(tex, &uDesc, &unorderedAccessView);
	SAFE_RELEASE(tex);

	depthStencilView = deviceMan11.GetDefaultDepthStencil();
	depthStencilView->AddRef();
}

void AFRenderTarget::Destroy()
{
	SAFE_RELEASE(renderTargetView);
	SAFE_RELEASE(shaderResourceView);
	SAFE_RELEASE(unorderedAccessView);
	SAFE_RELEASE(depthStencilView);
}

void AFRenderTarget::BeginRenderToThis()
{
	deviceMan11.GetContext()->OMSetRenderTargets(1, &renderTargetView, depthStencilView);
	float clearColor[4] = { 0.0f, 0.2f, 0.0f, 0.0f };
	deviceMan11.GetContext()->ClearRenderTargetView(renderTargetView, clearColor);
	deviceMan11.GetContext()->ClearDepthStencilView(depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
}
#endif


text:
"""
Python Photoshop
~~~~~~~~~~~~~~~~~~~~~

:copyright: (c) 2015 by Brett Dixon
:license: MIT, see LICENSE for more details
"""

"""A python TCP socket connection to Photoshop CS5.5.  This is a simple
wrapper class to facilitate sending arbitrary JavaScript to Photoshop and
receiving the result of the script.  The Connection objet also has a
thumbnail method to write the a JPEG to a file-like object of the current doc
open in Photoshop.

There is a EventListener class to subscribe to events in Photoshop.
"""

import sys
import socket
import struct
import logging
from threading import Thread, Event

import six
from six.moves import queue as Queue

try:
    # PyCrypto is much faster, but requires a built binary
    from Crypto.Cipher import DES3
    PYCRYPTO = True
except ImportError:
    # py_des is pure python, but slower.  Should be ok for sending scripts
    from ._des import triple_des, PAD_PKCS5, CBC
    PYCRYPTO = False

from pbkdf2 import PBKDF2

# PYTHON_MAJOR_VERSION is used to handle Python2 and Python3 differences.
PYTHON_MAJOR_VERSION = sys.version_info[0]

logging.basicConfig()
LOGGER = logging.getLogger('PSLIB')
HOST = socket.gethostbyname(socket.gethostname())
SUBSCRIBE = """
var idNS = stringIDToTypeID( 'networkEventSubscribe' );
var desc1 = new ActionDescriptor();
desc1.putClass( stringIDToTypeID( 'eventIDAttr' ), stringIDToTypeID( '%s' ) );
executeAction( idNS, desc1, DialogModes.NO );
'';
"""

def enum(*sequential, **named):
    enums = dict(zip(sequential, range(len(sequential))), **named)
    return type('Enum', (), enums)

class ConnectionError(Exception):
    """Could not connect to Photoshop"""

class Connection(object):
    """Main connection class to Photoshop.  Handles sending/receving and
    encrypting/decrypting the bytes.
    """
    PORT = 49494
    PROTOCOL_VERSION = 1
    PROTOCOL_LENGTH = 4 + 4 + 4
    COMM_LENGTH = 4
    NO_COMM_ERROR = 0
    COMM_ERROR = 1

    def __init__(self):
        self._host = None
        self._isconnected = False
        self._socket = socket.socket()
        self._crypt = None
        self._id = 0

    @property
    def isConnected(self):
        """Whether the connection is connected or not"""
        return self._isconnected

    def connect(self, passwd='', host=None):
        host = host or HOST
        try:
            self._socket.connect((host, self.PORT))
            self._socket.settimeout(0.2)
            self._isconnected = True
            LOGGER.debug('Connected')
        except socket.error as err:
            self._socket = None
            self._isconnected = False
            LOGGER.error('Could not connect: %s', str(err))

            raise ConnectionError(err)

        self._crypt = EncryptDecrypt(passwd)

    def close(self):
        self._socket.close()
        self._socket = None
        self._isconnected = False
        LOGGER.debug('Disconnected')

    def recv(self):
        """Receives a message from PS and decrypts it and returns a Message"""
        LOGGER.debug('Receiving')
        try:
            message_length = struct.unpack('>i', self._socket.recv(4))[0]
            message_length -= Connection.COMM_LENGTH
            LOGGER.debug('Length: %i', message_length)
        except socket.timeout:
            return None

        comm_status = struct.unpack('>i', self._socket.recv(4))[0]
        LOGGER.debug('Status: %i', comm_status)
        bytes_received = 0
        message = b""

        while bytes_received < message_length:
            if message_length - bytes_received >= 1024:
                recv_len = 1024
            else:
                recv_len = message_length - bytes_received
            bytes_received += recv_len
            LOGGER.debug('Received %i', bytes_received)
            message += self._socket.recv(recv_len)

        if comm_status == 0:
            message = self._crypt.decrypt(message)
        else:
            return Message(len(message), Connection.COMM_ERROR, message)

        msg = Message(message_length, comm_status, message)

        return msg

    def send(self, content):
        """Sends a JavaScript command to PS

        :param content: Script content
        :type content: str
        :yields: :class:`.Message`
        """
        LOGGER.debug('Sending: %s', content)
        all_bytes = struct.pack('>i', Connection.PROTOCOL_VERSION)
        all_bytes += struct.pack('>i', self._id)
        all_bytes += struct.pack('>i', 2)
        self._id += 1
        for char in content:
            all_bytes += struct.pack('>c', char.encode('utf8'))

        encrypted_bytes = self._crypt.encrypt(all_bytes)

        message_length = Connection.COMM_LENGTH + len(encrypted_bytes)

        self._socket.send(struct.pack('>i', message_length))
        self._socket.send(struct.pack('>i', Connection.NO_COMM_ERROR))
        self._socket.send(encrypted_bytes)
        LOGGER.debug('Sent')

        message = self.recv()
        while message is None:
            message = self.recv()
            yield message

        yield message

    def send_sync(self, content):
        """Sends a JavaScript command to Photoshop and blocks until it resutrns a value

        :param content: Script content
        """

        for result in self.send(content):
            if result:
                return result

class EventListener(Thread):
    """Event thread to handle event messages from Photoshop"""
    def __init__(self, connection, interval=0.1, *args, **kwargs):
        super(EventListener, self).__init__(*args, **kwargs)
        self.deamon = True

        self._connection = connection
        self._sub = Queue.Queue()
        self._unsub = Queue.Queue()
        self._ids = {}
        self._interval = interval
        self._stop = Event()

    @classmethod
    def connect(cls, passwd, host=None, *args, **kwargs):
        connection = Connection()
        connection.connect(passwd, host)

        return cls(connection, *args, **kwargs)

    def subscribe(self, eventName, callback, args=()):
        self._sub.put({'eventName': eventName, 'func': callback, 'args': args})

    def unsubscribe(self, eventName, callback):
        self._unsub.put({'eventName': eventName, 'func': callback})

    def stop(self):
        self._stop.set()
        self._connection.close()

    def run(self):
        while not self._stop.is_set():
            ## -- Add any subs
            while self._sub.qsize():
                item = self._sub.get()
                LOGGER.debug('Subscribing %s', item)
                msg = self._connection.send(SUBSCRIBE % item['eventName'], True)
                if msg is not None:
                    try:
                        self._ids[msg.id] = item
                    except:
                        LOGGER.error(msg)

            ## -- Remove subs
            while self._unsub.qsize():
                item = self._unsub.get()
                LOGGER.debug('Unsubscribing %s', item)
                for id_, sub in six.iteritems(self._ids):
                    if sub['eventName'] == item['eventName'] and \
                    sub['func'] == item['func']:
                        del self._ids[id_]
                        break

            ## -- Receive bytes from PS
            message = self._connection.recv()
            if message is None:
                continue

            obj = self._ids.get(message.id)
            if obj:
                obj['func'](message, *obj['args'])

            if self._interval:
                self._stop.wait(self._interval)

class EncryptDecrypt(object):
    """Handles the encrypting and dectrypting of bytes"""
    SALT = 'Adobe Photoshop'
    ITERACTIONCOUNT = 1000
    KEY_LENGTH = 24
    def __init__(self, passPhrase):
        key = PBKDF2(
            six.b(passPhrase),
            six.b(EncryptDecrypt.SALT),
            iterations=EncryptDecrypt.ITERACTIONCOUNT
        ).read(EncryptDecrypt.KEY_LENGTH)
        iv = '\0\0\0\0\0\0\0\0'
        self.block_size = 8

        if PYCRYPTO:
            self.enc = DES3.new(key, DES3.MODE_CBC, iv)
            self.dec = DES3.new(key, DES3.MODE_CBC, iv)
        else:
            self.enc = triple_des(
                key,
                CBC,
                iv,
                padmode=PAD_PKCS5
            )
            self.dec = triple_des(
                key,
                CBC,
                iv,
                padmode=PAD_PKCS5
            )

    def encrypt(self, b):
        data = self._padData(b) if PYCRYPTO else b
        return self.enc.encrypt(data)

    def decrypt(self, byteString):
        data = self.dec.decrypt(byteString)
        return self._unpadData(data) if PYCRYPTO else data

    # Stolen from py_des for PKCS5 padding when using PyCrypto
    def _padData(self, data):
        pad_len = 8 - (len(data) % self.block_size)
        if PYTHON_MAJOR_VERSION < 3:
            data += pad_len * chr(pad_len)
        else:
            data += bytes([pad_len] * pad_len)

        return data

    def _unpadData(self, data):
        # Unpad data depending on the mode.
        if not data:
            return data

        if PYTHON_MAJOR_VERSION < 3:
            pad_len = ord(data[-1])
        else:
            pad_len = data[-1]
        data = data[:-pad_len]

        return data

    def _guardAgainstUnicode(self, data):
        # Only accept byte strings or ascii unicode values, otherwise
        # there is no way to correctly decode the data into bytes.
        if PYTHON_MAJOR_VERSION < 3:
            if not isinstance(data, six.text_type):
                raise ValueError("py_des can only work with bytes, not Unicode \
                    strings.")
        else:
            if isinstance(data, str):
                # Only accept ascii unicode values.
                try:
                    return data.encode('ascii')
                except UnicodeEncodeError:
                    pass
                raise ValueError("py_des can only work with encoded strings,\
                 not Unicode.")
        return data

class Message(object):
    """Simple object to present Photoshop messages nicely"""
    ContentType = enum('ERROR', 'JAVASCRIPT', 'IMAGE', 'ICC', 'DATA')
    Status = enum('OK', 'ERROR')
    def __init__(self, length, status, message):
        self.length = length
        self.status = status
        self._message = message
        if status == Connection.COMM_ERROR:
            self.command = 'ERROR'
            self.content = message[12:]
            if b'decrypting' in self.content:
                raise ConnectionError('Incorrect password')

            return

        message_head = 4 * 3 # 4 bytes for each of the following
        self.version = struct.unpack('>i', message[:4])[0]
        self.id = struct.unpack('>i', message[4:8])[0]
        self.type = struct.unpack('>i', message[8:12])[0]

        # The rest is the message
        splits = message[message_head:].split(b'\r', 2)
        if len(splits) < 2:
            self.command = splits[0]
            self.content = ''
        else:
            self.command = splits[0]
            self.content = splits[1]

    def __repr__(self):
        return '<%s:%s>' % (self.command, self.content)


text:
layout: post
title: Installing the Abominade IDE.
date: 2015-12-13 23:53:50
---

I had some trouble installing the Abominade IDE from several sources. Luckily, it's simple to build yourself.
Once you've found yourself in the directory where you want your code to live, you'll need to get the source from github.

    $ git clone https://github.com/aliafshar/a8/

Once that's done cd into the directory where your code is located and run make.

    $ cd a8
    $ make

Make will create several new files and folders and open an abominade window. Close the window, and cd into the directory where a8's startup script is located. You can then create a symbolic link to it from anywhere on your $PATH.

    cd test-ve/bin/
    ln -s a8 ~/bin

Now you should be able to invoke the editor from anywhere, and still edit the source code.


text:
<?php namespace October\Sample;

use System\Classes\PluginBase;

class Plugin extends PluginBase
{

    public function pluginDetails()
    {
        return [
            'name' => 'October Sample Plugin',
            'description' => 'Sample plugin used by unit tests.',
            'author' => 'Alexey Bobkov, Samuel Georges'
        ];
    }

}


text:
                Character Name
                <input name = "attr_character_name">

                Character Points
                <input name = "attr_cp" type = "number" value = "0">

                Character Types
                <fieldset class = "repeating_chartypes">
                    <select name = "attr_chartype">
                        <option value = ""></option>
                        <option value = "Robotic">Robotic</option>
                        <option value = "Hype Man">Hype Man</option>
                        <option value = "Hamon">Hamon</option>
                        <option value = "Vampire">Vampire</option>
                        <option value = "Spin">Spin</option>
                        <option value = "No Stand">No Stand</option>
                    </select>

                        Rank 1 <input type = "radio" name = "attr_typerank">
                        Rank 2 <input type = "radio" name = "attr_typerank">
                        Rank 3 <input type = "radio" name = "attr_typerank">

                </fieldset>

<button type='roll' value='/roll 1d6 + @{brains}'>Brains</button>

<button type='roll' value='/roll 1d6 + @{brawns}'>Brawns</button>

<button type='roll' value='/roll 1d6 + @{bravery}'>Bravery</button>

                    <input name = "attr_brains" type = "number" value = "0">

                    <input name = "attr_brawns" type = "number" value = "0">

                    <input name = "attr_bravery" type = "number" value = "0">

Real Health

Resolve Health

Bizarre Points

                    <input name = "attr_health" type = "number" value = "0">

                    <input name = "attr_resolve" type = "number" value = "0">

                    <input name = "attr_bp" type = "number" value = "0">

        <input name = "attr_hasstand" type = "checkbox" class = "has_stand hidden" checked = "checked" value = "1">

                    Stand Name <input name = "attr_stand_name" type = "text">

                    Stand Types
                    <fieldset class = "repeating_standtypes">
                        <select name = "attr_standtype">
                            <option value = ""></option>
                            <option disabled>DISTANCE</option>
                            <option value = "Close Distance Power">Close Distance Power</option>
                            <option value = "Long Distance Manipulation">Long Distance Manipulation</option>
                            <option value = "Far Distance Autopilot">Far Distance Autopilot</option>
                            <option disabled>FORM</option>
                            <option value = "Substance Assimilation">Substance Assimilation</option>
                            <option value = "Integrated">Integrated</option>
                            <option value = "Wearable">Wearable</option>
                            <option value = "Colony">Colony</option>
                            <option disabled>MISC.</option>
                            <option value = "ACT Stand">ACT Stand</option>
                            <option value = "Universal Range">Universal Range</option>
                        </select>
                    </fieldset>

Stat

Rank

Dice

Modifier

<button type='roll' value='/roll @{power_dice}'>Power</button>

                        <select name = "attr_power_val">
                            <option>A</option>
                            <option>B</option>
                            <option selected>C</option>
                            <option>D</option>
                            <option>E</option>
                        </select>

2d6

+1

<button type='roll' value='/roll @{speed_dice}'>Speed</button>

                        <select name = "attr_speed_val">
                            <option>A</option>
                            <option>B</option>
                            <option selected>C</option>
                            <option>D</option>
                            <option>E</option>
                        </select>

2d6

+1

<button type='roll' value='/roll @{range_dice}'>Range</button>

                        <select name = "attr_range_val">
                            <option>A</option>
                            <option>B</option>
                            <option selected>C</option>
                            <option>D</option>
                            <option>E</option>
                        </select>

2d6

+1

<button type='roll' value='/roll @{durability_dice}'>Durability</button>

                        <select name = "attr_durability_val">
                            <option>A</option>
                            <option>B</option>
                            <option selected>C</option>
                            <option>D</option>
                            <option>E</option>
                        </select>

2d6

+1

<button type='roll' value='/roll @{precision_dice}'>Precision</button>

                        <select name = "attr_precision_val">
                            <option>A</option>
                            <option>B</option>
                            <option selected>C</option>
                            <option>D</option>
                            <option>E</option>
                        </select>

2d6

+1

<button type='roll' value='/roll @{learning_dice}'>Learning</button>

                        <select name = "attr_learning_val">
                            <option>A</option>
                            <option>B</option>
                            <option selected>C</option>
                            <option>D</option>
                            <option>E</option>
                        </select>

2d6

+1

Critical Weaknesses

                    <input name = "attr_power_cw" class = "hidden" type = "checkbox" checked = "" value = "1">

Power

<textarea name = "attr_power_cw_input"></textarea>

                    <input name = "attr_speed_cw" class = "hidden" type = "checkbox" checked = "" value = "1">

Speed

<textarea name = "attr_speed_cw_input"></textarea>

                    <input name = "attr_range_cw" class = "hidden" type = "checkbox" checked = "" value = "1">

Range

<textarea name = "attr_range_cw_input"></textarea>

                    <input name = "attr_durability_cw" class = "hidden" type = "checkbox" checked = "" value = "1">

Durability

<textarea name = "attr_durability_cw_input"></textarea>

                    <input name = "attr_precision_cw" class = "hidden" type = "checkbox" checked = "" value = "1">

Precision

<textarea name = "attr_precision_cw_input"></textarea>

                    <input name = "attr_learning_cw" class = "hidden" type = "checkbox" checked = "" value = "1">

Learning

<textarea name = "attr_learning_cw_input"></textarea>

Abilities

Name

Roll

Range

Effect

Condition

                <fieldset class = "repeating_abilities">

                            <button type='roll' value='/roll @{abilityroll}'>F</button>
                            <input name = "attr_abilityname" type = "text">

                            <select name = "attr_abilityroll">
                                <option>1d6</option>
                                <option>2d6k1</option>
                                <option selected>2d6</option>
                                <option>3d6k2</option>
                                <option>3d6</option>
                            </select>

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

<textarea name = "attr_abilityeffect"></textarea>

<textarea name = "attr_abilitycondition"></textarea>

                </fieldset>

Inventory

<textarea name = "attr_item"></textarea>

Secret Actions

Name

Roll

Description

            <fieldset class = "repeating_actions">

                        <button type='roll' value='/roll @{actionroll}'>F</button>
                        <input name = "attr_actionname" type = "text">

                        <select name = "attr_actionroll">
                            <option>1d6</option>
                            <option>2d6k1</option>
                            <option selected>2d6</option>
                            <option>3d6k2</option>
                            <option>3d6</option>
                        </select>

                        <textarea name = "attr_actiondesc"></textarea>

            </fieldset>

Traits

Name

Description

            <fieldset class = "repeating_traits">

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

                        <textarea class = "item tr-desc" name = "attr_tr_desc"></textarea>

            </fieldset>

Flaws

Name

Description

            <fieldset class = "repeating_flaws">

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

                        <textarea class = "item fl-desc" name = "attr_fl_desc"></textarea>

            </fieldset>

Permanent Flaws

Name

Description

            <fieldset class = "repeating_flaws2">

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

                        <textarea class = "item fl2-desc" name = "attr_fl2_desc"></textarea>

            </fieldset>

Conditions

Name

Description

            <fieldset class = "repeating_conds">

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

                        <textarea class = "item fl2-desc" name = "attr_cond_desc"></textarea>

            </fieldset>

Character Details

Age

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

Nationality

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

Birthday

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

Eye Color

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

Zodiac Sign

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

Favorite Movie

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

Gender

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

Favorite Food

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

Height

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

Favorite Actor

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

Weight

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

Favorite Musician

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

Blood Type

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

Favorite Athlete

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

Occupation

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

<input type = "text" name = "attr_chr16" value = "...">

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

Character Bio

<textarea name = "attr_charbio"></textarea>

            <input name = "attr_power_dice" value = "2d6">
            <input name = "attr_power_mod" value = "1">
            <input name = "attr_speed_dice" value = "2d6">
            <input name = "attr_speed_mod" value = "1">
            <input name = "attr_range_dice" value = "2d6">
            <input name = "attr_range_mod" value = "1">
            <input name = "attr_durability_dice" value = "2d6">
            <input name = "attr_durability_mod" value = "1">
            <input name = "attr_precision_dice" value = "2d6">
            <input name = "attr_precision_mod" value = "1">
            <input name = "attr_learning_dice" value = "2d6">
            <input name = "attr_learning_mod" value = "1">

    <rolltemplate class="sheet-rolltemplate-jjba">

    </rolltemplate>


text:
<?php
declare(strict_types=1);

namespace CrudView\Test\TestCase\Dashboard;

use Cake\Http\Response;
use Cake\Http\ServerRequest;
use Cake\TestSuite\TestCase;
use CrudView\Dashboard\Dashboard;
use CrudView\View\Cell\DashboardTableCell;

/**
 * DashboardTest class
 */
class DashboardTest extends TestCase
{
    public function testConstruct()
    {
        $dashboard = new Dashboard();
        $expected = __d('CrudView', 'Dashboard');
        $this->assertEquals($expected, $dashboard->get('title'));

        $expected = [];
        $this->assertEquals($expected, $dashboard->get('children'));

        $expected = 1;
        $this->assertEquals($expected, $dashboard->get('columns'));

        $dashboard = new Dashboard('Test Title');
        $expected = 'Test Title';
        $this->assertEquals($expected, $dashboard->get('title'));
    }

    public function testInvalidConstruct()
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage('Valid columns value must be one of [1, 2, 3, 4, 6, 12]');

        new Dashboard(null, 0);
    }

    public function testColumnChildren()
    {
        $dashboard = new Dashboard();
        $expected = [];
        $this->assertEquals($expected, $dashboard->getColumnChildren(1));

        $cell = new DashboardTableCell(new ServerRequest(), new Response());
        $return = $dashboard->addToColumn($cell);
        $this->assertEquals($dashboard, $return);
        $this->assertEquals([$cell], $dashboard->getColumnChildren(1));

        $expected = [];
        $this->assertEquals($expected, $dashboard->getColumnChildren(2));
    }
}


text:
<?php

namespace Behat\SahiClient;

use Buzz;

use Behat\SahiClient\Exception;

/**
 * Sahi Connection Driver.
 *
 * @author Konstantin Kudryashov <ever.zet@gmail.com>
 */
class Connection
{
    /**
     * Sahi SID
     *
     * @var     integer
     */
    private     $sid;
    /**
     * Is custom SID provided to connection
     *
     * @var     Boolean
     */
    private     $customSidProvided = false;
    /**
     * Sahi proxy hostname
     *
     * @var     string
     */
    private     $host;
    /**
     * Sahi proxy port number
     *
     * @var     integer
     */
    private     $port;
    /**
     * Time limit to connection.
     *
     * @var     integer
     */
    private     $limit;

    /**
     * HTTP Browser instance.
     *
     * @var     BrowserInterface
     */
    protected   $browser;

    /**
     * Initialize Sahi Driver.
     *
     * @param   string      $sid        Sahi SID
     * @param   string      $host       Sahi proxy host
     * @param   integer     $port       Sahi proxy port
     * @param   BuzzBrowser $browser    HTTP browser instance
     * @param   integer     $limit      Time limit to connection
     */
    public function __construct($sid = null, $host = 'localhost', $port = 9999, Buzz\Browser $browser = null, $limit = 600)
    {
        $this->limit = $limit;

        if (null !== $sid) {
            $this->customSidProvided = true;
        }

        $this->sid  = $sid;
        $this->host = $host;
        $this->port = $port;

        if (null === $browser) {
            $client = new Buzz\Client\Curl();
            $this->browser = new Buzz\Browser($client);
        } else {
            $this->browser = $browser;
        }
    }

    /**
     * Checks that connection used custom SID.
     *
     * @return  Boolean
     */
    public function isCustomSidProvided()
    {
        return $this->customSidProvided;
    }

    /**
     * Returns current connection SID.
     *
     * @return  string
     */
    public function getSid()
    {
        return $this->sid;
    }

    /**
     * Starts browser.
     *
     * @param   string  $browserName    (firefox, ie, safari, chrome, opera)
     */
    public function start($browserName)
    {
        if (!$this->customSidProvided) {
            $this->sid = uniqid();
            $this->executeCommand('launchPreconfiguredBrowser', array('browserType' => $browserName));
        }
    }

    /**
     * Stop browser.
     */
    public function stop()
    {
        if (!$this->customSidProvided) {
            $this->executeCommand('kill');

            // sometimes, firefox is not fast enought at closing
            // and next instance can't be created since previous
            // still running. So - wait 1 second.
            sleep(1);
        }
    }

    /**
     * Checks whether Sahi proxy were started.
     *
     * @return  Boolean
     */
    public function isProxyStarted()
    {
        return 200 === $this->post(
            sprintf('http://%s:%d/_s_/spr/blank.htm', $this->host, $this->port)
        )->getStatusCode();
    }

    /**
     * Checks whether connection is ready.
     *
     * @return  Boolean
     */
    public function isReady()
    {
        return 'true' === $this->executeCommand('isReady');
    }

    /**
     * Return HTTP Browser instance.
     *
     * @return  Browser
     */
    public function getBrowser()
    {
        return $this->browser;
    }

    /**
     * Execute Sahi command & returns its response.
     *
     * @param   string  $command        Sahi command
     * @param   array   $parameters     parameters
     *
     * @return  string                  command response
     */
    public function executeCommand($command, array $parameters = array())
    {
        $content = $this->post(
            sprintf('http://%s:%d/_s_/dyn/Driver_%s', $this->host, $this->port, $command),
            array_merge($parameters, array('sahisid' => $this->sid))
        )->getContent();

        if (false !== strpos($content, 'SAHI_ERROR')) {
            throw new Exception\ConnectionException('Sahi proxy error');
        }

        return $content;
    }

    /**
     * Execute Sahi step.
     *
     * @param   string  $step       step command
     * @param   integer $limit      time limit (value of 10 === 1 second)
     *
     * @throws  BrowserException    if step execution has errors
     */
    public function executeStep($step, $limit = null)
    {
        $this->executeCommand('setStep', array('step' => $step));

        $limit = $limit ?: $this->limit;
        $check = 'false';
        while ('true' !== $check) {
            usleep(100000);
            if (--$limit <= 0) {
                throw new Exception\ConnectionException(
                    'Command execution time limit reached: `' . $step . '`'
                );
            }

            $check = $this->executeCommand('doneStep');
            if (0 === mb_strpos($check, 'error:')) {
                throw new Exception\ConnectionException($check);
            }
        }
    }

    /**
     * Evaluates JS expression on the browser and returns it's value.
     *
     * @param   string  $expression JS expression
     * @param   integer $limit      time limit (value of 10 === 1 second)
     *
     * @return  string|null
     */
    public function evaluateJavascript($expression, $limit = null)
    {
        $key = '___lastValue___' . uniqid();
        $this->executeStep(
            sprintf("_sahi.setServerVarPlain(%s, %s)", "'" . $key . "'", $expression), $limit
        );

        $resp = $this->executeCommand('getVariable', array('key' => $key));

        return 'null' === $resp ? null : $resp;
    }

    /**
     * Execute JS expression on the browser.
     *
     * @param   string  $expression JS expression
     */
    public function executeJavascript($expression, $limit = null)
    {
        $this->executeStep(sprintf("_sahi._call(%s)", $expression), $limit);
    }

    /**
     * Send POST request to specified URL.
     *
     * @param   string  $url    URL
     * @param   array   $query  POST query parameters
     *
     * @return  string          response
     */
    private function post($url, array $query = array())
    {
        return $this->browser->post($url, array(), $this->prepareQueryString($query));
    }

    /**
     * Convert array parameters to POST parameters.
     *
     * @param   array   $query  parameters
     *
     * @return  string          query string (key1=val1&key2=val2)
     */
    private function prepareQueryString(array $query)
    {
        $items = array();
        foreach ($query as $key => $val) {
            $items[] = $key . '=' . urlencode($val);
        }

        return implode('&', $items);
    }
}


text:
var knife = require('../knife'),
    proc = require('../process_option');

module.exports = {
    name: 'directive-cml',
    on: ['tag'],
    options: [{
      name: 'cml-directives',
      desc: 'This option holds all the directives that Chameleon framework has.',
      process: proc.arrayOfStr
    }]
};

module.exports.lint = function(element, opts) {
    var subs = this.subscribers,
        as = element.attribs,
        issues = [];

    Object.keys(as).filter(function(name) {
      return ~opts['cml-directives'].indexOf(name);
    }).forEach(function(name) {
        var a = as[name];
        a.name = name;

        var matcher = knife.matchFilter.bind(knife, name);
        var s = subs.filter(matcher);

        issues = issues.concat(knife.applyRules(s, a, opts));
    });

    return issues;
};


text:
@interface SignInViewController : UIViewController
<
    UITextFieldDelegate
>

@end


text:
import { gravityLoader } from "./gravity"
import { positronLoader } from "./positron"
import { googleCSELoader } from "./google_cse"
import { totalLoader } from "./total"

export default {
  loaders: {
    gravity: gravityLoader,
    positron: positronLoader,
    google: googleCSELoader,
    total: totalLoader,
  },

  clearAll: () => {
    gravityLoader.clearAll()
    positronLoader.clearAll()
    googleCSELoader.clearAll()
    totalLoader.clearAll()
  },
}


text:
CKEDITOR.plugins.setLang( 'a11yhelp', 'vi',
{
	accessibilityHelp :
	{
		title : 'Accessibility Instructions', // MISSING
		contents : 'Nội dung Hỗ trợ. Nhấn ESC để đóng hộp thoại.',
		legend :
		[
			{
				name : 'Chung',
				items :
						[
							{
								name : 'Thanh công cụ soạn th',
								legend:
									'Nhấn ${toolbarFocus} để điều hướng đến thanh công cụ. Nhấn TAB và SHIFT-TAB để chuyển đến nhóm thanh công cụ khác. Nhấn MŨI TÊN PHẢI hoặc MŨI TÊN TRÁI để chuyển sang nút khác trên thanh công cụ. Nhấn PHÍM CÁCH hoặc ENTER để kích hoạt nút trên thanh công c.'
							},

							{
								name : 'Hộp thoại Biên t',
								legend :
									'Inside a dialog, press TAB to navigate to next dialog field, press SHIFT + TAB to move to previous field, press ENTER to submit dialog, press ESC to cancel dialog. For dialogs that have multiple tab pages, press ALT + F10 to navigate to tab-list. Then move to next tab with TAB OR RIGTH ARROW. Move to previous tab with SHIFT + TAB or LEFT ARROW. Press SPACE or ENTER to select the tab page.'  // MISSING
							},

							{
								name : 'Trình đơn Ngữ cảnh cBộ soạn thảo',
								legend :
									'Press ${contextMenu} or APPLICATION KEY to open context-menu. Then move to next menu option with TAB or DOWN ARROW. Move to previous option with SHIFT+TAB or UP ARROW. Press SPACE or ENTER to select the menu option. Open sub-menu of current option with SPACE or ENTER or RIGHT ARROW. Go back to parent menu item with ESC or LEFT ARROW. Close context menu with ESC.'  // MISSING
							},

							{
								name : 'Editor List Box', // MISSING
								legend :
									'Inside a list-box, move to next list item with TAB OR DOWN ARROW. Move to previous list item with SHIFT + TAB or UP ARROW. Press SPACE or ENTER to select the list option. Press ESC to close the list-box.'  // MISSING
							},

							{
								name : 'Editor Element Path Bar', // MISSING
								legend :
									'Press ${elementsPathFocus} to navigate to the elements path bar. Move to next element button with TAB or RIGHT ARROW. Move to previous button with  SHIFT+TAB or LEFT ARROW. Press SPACE or ENTER to select the element in editor.'  // MISSING
							}
						]
			},
			{
				name : 'Commands', // MISSING
				items :
						[
							{
								name : ' Undo command', // MISSING
								legend : 'Press ${undo}' // MISSING
							},
							{
								name : ' Redo command', // MISSING
								legend : 'Press ${redo}' // MISSING
							},
							{
								name : ' Bold command', // MISSING
								legend : 'Press ${bold}' // MISSING
							},
							{
								name : ' Italic command', // MISSING
								legend : 'Press ${italic}' // MISSING
							},
							{
								name : ' Underline command', // MISSING
								legend : 'Press ${underline}' // MISSING
							},
							{
								name : ' Link command', // MISSING
								legend : 'Press ${link}' // MISSING
							},
							{
								name : ' Toolbar Collapse command', // MISSING
								legend : 'Press ${toolbarCollapse}' // MISSING
							},
							{
								name : ' Accessibility Help', // MISSING
								legend : 'Press ${a11yHelp}' // MISSING
							}
						]
			}
		]
	}
});


text:
package com.jetbrains.python.testing.attest;

import org.jdom.Element;
import javax.annotation.Nonnull;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.Executor;
import com.intellij.execution.configurations.ConfigurationFactory;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.configurations.RunProfileState;
import com.intellij.execution.configurations.RuntimeConfigurationException;
import com.intellij.execution.configurations.RuntimeConfigurationWarning;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.jetbrains.python.PyBundle;
import com.jetbrains.python.sdk.PythonSdkType;
import com.jetbrains.python.testing.AbstractPythonTestRunConfiguration;
import com.jetbrains.python.testing.VFSTestFrameworkListener;

/**
 * User: catherine
 */
public class PythonAtTestRunConfiguration extends AbstractPythonTestRunConfiguration implements PythonAtTestRunConfigurationParams
{
	protected String myTitle = "Attest";
	protected String myPluralTitle = "Attests";

	public PythonAtTestRunConfiguration(Project project, ConfigurationFactory configurationFactory)
	{
		super(project, configurationFactory);
	}

	@Override
	protected SettingsEditor<? extends RunConfiguration> createConfigurationEditor()
	{
		return new PythonAtTestRunConfigurationEditor(getProject(), this);
	}

	@Override
	public RunProfileState getState(@Nonnull final Executor executor, @Nonnull final ExecutionEnvironment env) throws ExecutionException
	{
		return new PythonAtTestCommandLineState(this, env);
	}

	@Override
	public void readExternal(Element element) throws InvalidDataException
	{
		super.readExternal(element);
	}

	@Override
	public void writeExternal(Element element) throws WriteExternalException
	{
		super.writeExternal(element);
	}

	@Override
	protected String getTitle()
	{
		return myTitle;
	}

	@Override
	protected String getPluralTitle()
	{
		return myPluralTitle;
	}

	public static void copyParams(PythonAtTestRunConfigurationParams source, PythonAtTestRunConfigurationParams target)
	{
		copyParams(source.getTestRunConfigurationParams(), target.getTestRunConfigurationParams());
	}

	@Override
	public void checkConfiguration() throws RuntimeConfigurationException
	{
		super.checkConfiguration();
		Sdk sdkPath = PythonSdkType.findSdkByPath(getInterpreterPath());
		if(sdkPath != null && !VFSTestFrameworkListener.getInstance().isAtTestInstalled(sdkPath))
		{
			throw new RuntimeConfigurationWarning(PyBundle.message("runcfg.testing.no.test.framework", "attest"));
		}
	}
}


text:
package net.avalara.avatax.rest.client.models;

import net.avalara.avatax.rest.client.enums.*;
import net.avalara.avatax.rest.client.serializer.JsonSerializer;

import java.lang.Override;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

/**
 * An input model for executing a report detailed to the document line level
 */
public class ExportDocumentLineModel {

    private ReportFormat format;

    /**
     * Getter for format
     *
     * The file format.
     */
    public ReportFormat getFormat() {
        return this.format;
    }

    /**
     * Setter for format
     *
     * The file format.
     */
    public void setFormat(ReportFormat value) {
        this.format = value;
    }

    private Date startDate;

    /**
     * Getter for startDate
     *
     * The start date filter for report execution. If no date provided, same date of last month will be used as the startDate.
    * Accepts date in short format yyyy-mm-dd as well as date time stamp
     */
    public Date getStartDate() {
        return this.startDate;
    }

    /**
     * Setter for startDate
     *
     * The start date filter for report execution. If no date provided, same date of last month will be used as the startDate.
    * Accepts date in short format yyyy-mm-dd as well as date time stamp
     */
    public void setStartDate(Date value) {
        this.startDate = value;
    }

    private Date endDate;

    /**
     * Getter for endDate
     *
     * The end date filter for report execution. If no date provided, today's date will be used as the endDate.
    * Accepts date in short format yyyy-mm-dd as well as date time stamp
     */
    public Date getEndDate() {
        return this.endDate;
    }

    /**
     * Setter for endDate
     *
     * The end date filter for report execution. If no date provided, today's date will be used as the endDate.
    * Accepts date in short format yyyy-mm-dd as well as date time stamp
     */
    public void setEndDate(Date value) {
        this.endDate = value;
    }

    private String country;

    /**
     * Getter for country
     *
     * The transactions in the country you wish to run a report.
    * Use "ALL" for all countries
    * Use "ALL Non-US" for all international countries
    * Or use a single 2-char ISO country code
     */
    public String getCountry() {
        return this.country;
    }

    /**
     * Setter for country
     *
     * The transactions in the country you wish to run a report.
    * Use "ALL" for all countries
    * Use "ALL Non-US" for all international countries
    * Or use a single 2-char ISO country code
     */
    public void setCountry(String value) {
        this.country = value;
    }

    private String state;

    /**
     * Getter for state
     *
     * The state associated with the transactions you wish to run a report.
    * Use "ALL" for all states or 2-char state code.
     */
    public String getState() {
        return this.state;
    }

    /**
     * Setter for state
     *
     * The state associated with the transactions you wish to run a report.
    * Use "ALL" for all states or 2-char state code.
     */
    public void setState(String value) {
        this.state = value;
    }

    private ReportDateFilter dateFilter;

    /**
     * Getter for dateFilter
     *
     * The type of date to filter your transactions
     */
    public ReportDateFilter getDateFilter() {
        return this.dateFilter;
    }

    /**
     * Setter for dateFilter
     *
     * The type of date to filter your transactions
     */
    public void setDateFilter(ReportDateFilter value) {
        this.dateFilter = value;
    }

    private ReportDocType docType;

    /**
     * Getter for docType
     *
     * The transaction type you want to run a report on
     */
    public ReportDocType getDocType() {
        return this.docType;
    }

    /**
     * Setter for docType
     *
     * The transaction type you want to run a report on
     */
    public void setDocType(ReportDocType value) {
        this.docType = value;
    }

    private String currencyCode;

    /**
     * Getter for currencyCode
     *
     * The currency your report is displayed in.
    * Accepts "USD" or leave this blank to get all the documents with all the currencies
     */
    public String getCurrencyCode() {
        return this.currencyCode;
    }

    /**
     * Setter for currencyCode
     *
     * The currency your report is displayed in.
    * Accepts "USD" or leave this blank to get all the documents with all the currencies
     */
    public void setCurrencyCode(String value) {
        this.currencyCode = value;
    }

    private Integer numberOfPartitions;

    /**
     * Getter for numberOfPartitions
     *
     * Number of partitions (2 - 250) to split the report into.
    * If a value is provided for this property, a value must also be provided for the partition property.
     */
    public Integer getNumberOfPartitions() {
        return this.numberOfPartitions;
    }

    /**
     * Setter for numberOfPartitions
     *
     * Number of partitions (2 - 250) to split the report into.
    * If a value is provided for this property, a value must also be provided for the partition property.
     */
    public void setNumberOfPartitions(Integer value) {
        this.numberOfPartitions = value;
    }

    private Integer partition;

    /**
     * Getter for partition
     *
     * The zero-based partition number to retrieve in this export request.
    * If a value is provided for this property, a value must also be provided for the numberOfPartitions property.
     */
    public Integer getPartition() {
        return this.partition;
    }

    /**
     * Setter for partition
     *
     * The zero-based partition number to retrieve in this export request.
    * If a value is provided for this property, a value must also be provided for the numberOfPartitions property.
     */
    public void setPartition(Integer value) {
        this.partition = value;
    }

    private Boolean isLocked;

    /**
     * Getter for isLocked
     *
     * If true, include only documents that are locked.
    * If false, include only documents that are not locked.
    * Defaults to false if not specified.
     */
    public Boolean getIsLocked() {
        return this.isLocked;
    }

    /**
     * Setter for isLocked
     *
     * If true, include only documents that are locked.
    * If false, include only documents that are not locked.
    * Defaults to false if not specified.
     */
    public void setIsLocked(Boolean value) {
        this.isLocked = value;
    }

    private String merchantSellerIdentifier;

    /**
     * Getter for merchantSellerIdentifier
     *
     * If set, include only documents associated with these merchantSellerIds.Multiple merchantSellerIds should be sent by comma separated values.
     */
    public String getMerchantSellerIdentifier() {
        return this.merchantSellerIdentifier;
    }

    /**
     * Setter for merchantSellerIdentifier
     *
     * If set, include only documents associated with these merchantSellerIds.Multiple merchantSellerIds should be sent by comma separated values.
     */
    public void setMerchantSellerIdentifier(String value) {
        this.merchantSellerIdentifier = value;
    }

    private DocumentStatus documentStatus;

    /**
     * Getter for documentStatus
     *
     * DocumentStatus
    * For documentStatus, accepted values are: Saved, Posted, Committed, Cancelled
     */
    public DocumentStatus getDocumentStatus() {
        return this.documentStatus;
    }

    /**
     * Setter for documentStatus
     *
     * DocumentStatus
    * For documentStatus, accepted values are: Saved, Posted, Committed, Cancelled
     */
    public void setDocumentStatus(DocumentStatus value) {
        this.documentStatus = value;
    }

    private Boolean isModifiedDateSameAsDocumentDate;

    /**
     * Getter for isModifiedDateSameAsDocumentDate
     *
     * Use this parameter when dateFilter = ModifiedDate.
    * For dateFilter = DocumentDate, PaymentDate, TaxDate or ReportingDate, the isModifiedDateSameAsDocumentDate parameter is ignored.
    * Set this parameter to true when you would like to get Documents which have the Document Date same as Modified Date.
    * Defaults to false if not specified.
     */
    public Boolean getIsModifiedDateSameAsDocumentDate() {
        return this.isModifiedDateSameAsDocumentDate;
    }

    /**
     * Setter for isModifiedDateSameAsDocumentDate
     *
     * Use this parameter when dateFilter = ModifiedDate.
    * For dateFilter = DocumentDate, PaymentDate, TaxDate or ReportingDate, the isModifiedDateSameAsDocumentDate parameter is ignored.
    * Set this parameter to true when you would like to get Documents which have the Document Date same as Modified Date.
    * Defaults to false if not specified.
     */
    public void setIsModifiedDateSameAsDocumentDate(Boolean value) {
        this.isModifiedDateSameAsDocumentDate = value;
    }

    private String taxGroup;

    /**
     * Getter for taxGroup
     *
     * TaxGroup is required to support Sales tax (Sales + SellersUse) and VAT (Input+ Output).
    * TaxTypes, such as Lodging, Bottle, LandedCost, Ewaste, BevAlc, etc
     */
    public String getTaxGroup() {
        return this.taxGroup;
    }

    /**
     * Setter for taxGroup
     *
     * TaxGroup is required to support Sales tax (Sales + SellersUse) and VAT (Input+ Output).
    * TaxTypes, such as Lodging, Bottle, LandedCost, Ewaste, BevAlc, etc
     */
    public void setTaxGroup(String value) {
        this.taxGroup = value;
    }

    private String taxName;

    /**
     * Getter for taxName
     *
     * The description of the tax
     */
    public String getTaxName() {
        return this.taxName;
    }

    /**
     * Setter for taxName
     *
     * The description of the tax
     */
    public void setTaxName(String value) {
        this.taxName = value;
    }

    private String taxCode;

    /**
     * Getter for taxCode
     *
     * The AvaTax tax code or customer tax code associated with the item or SKU in the transaction
     */
    public String getTaxCode() {
        return this.taxCode;
    }

    /**
     * Setter for taxCode
     *
     * The AvaTax tax code or customer tax code associated with the item or SKU in the transaction
     */
    public void setTaxCode(String value) {
        this.taxCode = value;
    }

    private String customerVendorCode;

    /**
     * Getter for customerVendorCode
     *
     * The code your business application uses to identify a customer or vendor
     */
    public String getCustomerVendorCode() {
        return this.customerVendorCode;
    }

    /**
     * Setter for customerVendorCode
     *
     * The code your business application uses to identify a customer or vendor
     */
    public void setCustomerVendorCode(String value) {
        this.customerVendorCode = value;
    }

    private String taxSubType;

    /**
     * Getter for taxSubType
     *
     * Defines the individual taxes associated with a TaxType category, such as Lodging TaxType which supports numerous TaxSubTypes, including Hotel, Occupancy, ConventionCenter, Accommotations, etc.
     */
    public String getTaxSubType() {
        return this.taxSubType;
    }

    /**
     * Setter for taxSubType
     *
     * Defines the individual taxes associated with a TaxType category, such as Lodging TaxType which supports numerous TaxSubTypes, including Hotel, Occupancy, ConventionCenter, Accommotations, etc.
     */
    public void setTaxSubType(String value) {
        this.taxSubType = value;
    }

    private ReportSource reportSource;

    /**
     * Getter for reportSource
     *
     * Defines report source.
     */
    public ReportSource getReportSource() {
        return this.reportSource;
    }

    /**
     * Setter for reportSource
     *
     * Defines report source.
     */
    public void setReportSource(ReportSource value) {
        this.reportSource = value;
    }

    /**
     * Returns a JSON string representation of ExportDocumentLineModel
     */
    @Override
    public String toString() {
        return JsonSerializer.SerializeObject(this);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="140dp">

        <com.leandom.banner.CycleViewPager
            android:id="@+id/banner"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:autoScrollInterval="4000"
            app:pageSwitchDuration="800" />

        <com.leandom.banner.ViewPagerIndicator
            android:id="@+id/viewpager_indicator"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:background="#30ffffff"
            android:gravity="center"
            android:paddingBottom="10dp"
            android:paddingLeft="10dp"
            android:paddingTop="10dp" />
    </FrameLayout>

</LinearLayout>


text:
package org.openqa.grid.internal;

import static org.openqa.grid.common.RegistrationRequest.APP;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.grid.internal.listeners.Prioritizer;
import org.openqa.grid.internal.mock.GridHelper;
import org.openqa.grid.web.servlet.handler.RequestHandler;

public class PriorityTest {

  private static Registry registry;

  // priority rule : the request with the highest priority goes first.
  private static Prioritizer highestNumberHasPriority = new Prioritizer() {
    public int compareTo(Map<String, Object> a, Map<String, Object> b) {
      int priorityA = Integer.parseInt(a.get("_priority").toString());
      int priorityB = Integer.parseInt(b.get("_priority").toString());
      return priorityB - priorityA;
    }
  };

  static Map<String, Object> ff = new HashMap<String, Object>();
  static RemoteProxy p1;

  static RequestHandler newSessionRequest1;
  static RequestHandler newSessionRequest2;
  static RequestHandler newSessionRequest3;
  static RequestHandler newSessionRequest4;
  static RequestHandler newSessionRequest5;

  static List<RequestHandler> requests = new ArrayList<RequestHandler>();

  /**
   * create a hub with 1 FF
   *
   * @throws InterruptedException
   */
  @BeforeClass
  public static void setup() throws InterruptedException {
    registry = Registry.newInstance();
    registry.setPrioritizer(highestNumberHasPriority);
    ff.put(APP, "FF");
    p1 = RemoteProxyFactory.getNewBasicRemoteProxy(ff, "http://machine1:4444", registry);
    registry.add(p1);

    // create 5 sessionRequest, with priority =1 .. 5
    Map<String, Object> ff1 = new HashMap<String, Object>();
    ff1.put(APP, "FF");
    ff1.put("_priority", 1);

    Map<String, Object> ff2 = new HashMap<String, Object>();
    ff2.put(APP, "FF");
    ff2.put("_priority", 2);

    Map<String, Object> ff3 = new HashMap<String, Object>();
    ff3.put(APP, "FF");
    ff3.put("_priority", 3);

    Map<String, Object> ff4 = new HashMap<String, Object>();
    ff4.put(APP, "FF");
    ff4.put("_priority", 4);

    Map<String, Object> ff5 = new HashMap<String, Object>();
    ff5.put(APP, "FF");
    ff5.put("_priority", 5);

    newSessionRequest1 = GridHelper.createNewSessionHandler(registry, ff1);
    newSessionRequest2 = GridHelper.createNewSessionHandler(registry, ff2);
    newSessionRequest3 = GridHelper.createNewSessionHandler(registry, ff3);
    newSessionRequest4 = GridHelper.createNewSessionHandler(registry, ff4);
    newSessionRequest5 = GridHelper.createNewSessionHandler(registry, ff5);

    requests.add(newSessionRequest1);
    requests.add(newSessionRequest2);
    requests.add(newSessionRequest5);
    requests.add(newSessionRequest3);
    requests.add(newSessionRequest4);

    RequestHandler newSessionRequest = GridHelper.createNewSessionHandler(registry, ff);
    newSessionRequest.process();
    TestSession session = newSessionRequest.getSession();

    // fill the queue with 5 requests.
    for (RequestHandler h : requests) {
      final RequestHandler req = h;
      new Thread(new Runnable() { // Thread safety reviewed
            public void run() {
              req.process();
            }
          }).start();
    }

    while (registry.getNewSessionRequestCount() != 5) {
      Thread.sleep(100);
    }

    // free the grid : the queue is consumed, and the test with the highest
    // priority should be processed.
    registry.terminateSynchronousFOR_TEST_ONLY(session);

  }

  // validate that the one with priority 5 has been assigned a proxy
  @Test
  public void validate() throws InterruptedException {
    Thread.sleep(250);
    Assert.assertNotNull(newSessionRequest5.getSession());
  }

  @AfterClass
  public static void teardown() {
    registry.stop();
  }

}


text:
package main

import (
	"os"
	"fmt"
	"time"
	"strconv"
	"github.com/op/go-logging"
)

var log = logging.MustGetLogger("dynct")

// Example format string. Everything except the message has a custom color
// which is dependent on the log level. Many fields have a custom output
// formatting too, eg. the time returns the hour down to the milli second.
var format = logging.MustStringFormatter(
	`%{time:15:04:05.000} %{shortfunc} ▶ %{level:.4s} %{id:03x} %{message}`,
)

func main() {
	configureLogging()
	writeThroughput := envToInt("WRITE_THROUGHPUT")
	defaultBuffers := writeThroughput * 20
	configuration := &Configuration{
		BufferSize:envToIntWithDefault("BUFFER_SIZE", defaultBuffers),
		QueueUrl:os.Getenv("QUEUE_URL"),
		TableName:os.Getenv("TABLE_NAME"),
	}
	log.Infof("Starting dynct with configuration", configuration)
	sqsClient, err := NewSqsClient(configuration)
	writer := NewDynamo(configuration)
	if (err != nil) {
		fmt.Println("failed to create puller,", err)
		panic(err)
	}
	writingChannel := make(chan *WriteEntry, defaultBuffers)
	deletingChannel := make(chan *WriteEntry, defaultBuffers)
	go writer.pipeThrough(writingChannel, deletingChannel)
	go sqsClient.HandleDeletes(deletingChannel)
	start(writeThroughput, writingChannel, sqsClient.messagesBuffer)
}

func start(writeThroughput int, writingChannel chan *WriteEntry, incomingChannel chan *WriteEntry) {
	ticker := time.NewTicker(1 * time.Second)
	for {
		select {
		case <-ticker.C:
			transferWrites(writeThroughput, writingChannel, incomingChannel)
		}
	}
}

func configureLogging() {
	defaultLogging := logging.NewLogBackend(os.Stdout, "", 0)
	formattedBackend := logging.NewBackendFormatter(defaultLogging, format)
	leveledBackend := logging.AddModuleLevel(formattedBackend)
	leveledBackend.SetLevel(logging.DEBUG, "")
	logging.SetBackend(leveledBackend)
}
//TODO move this to own file and structure and improve logic by spreading the writes across a second and only exceed capacity with one item if it's just one item
//TODO add another inner buffer which is optimizes the way we write the items by rearranging them in the most optimum way possible (should also ensure a maximum ttl in memory for an item before it takes precedence)
func transferWrites(throughput int, writingChannel chan *WriteEntry, messages chan *WriteEntry) {
	for i := 0; i < throughput; {
		message := <-messages
		writingChannel <- message
		i += message.WriteUnitesConsumed
	}
}
func envToInt(envName string) int {
	result, err := strconv.Atoi(os.Getenv(envName))
	if (err != nil) {
		panic("failed to parse value for config " + envName)
	}
	return result
}

func envToIntWithDefault(envName string, defaultValue int) int {
	propertyValue := os.Getenv(envName)
	if (propertyValue == "") {
		return defaultValue
	}
	result, err := strconv.Atoi(propertyValue)
	if (err != nil) {
		fmt.Println("failed to parse value for config " + envName + ", using default value")
	}
	return result
}

type Configuration struct {
	TableName  string
	BufferSize int //number of messages to keep in buffer, does not guarantee is write units size. Should change in the future to set write units size
	QueueUrl   string
}


text:
package gologin

const VERSION = "0.1.0"

// request context variable names
const (
	CV_CURRENTUSER = "currentuser" // currently logged-in user (User)
)

// session cookie variable names
const (
	SESSION_NAME = "user"     // gorilla sessions session name
	SV_USERID    = "userid"   // stored user id (string)
	SV_LOGGEDIN  = "loggedin" // logged in status (bool)
)