text:
//------------------------------------------------------------------------------
// <auto-generated>This code was generated by LLBLGen Pro v5.9.</auto-generated>
//------------------------------------------------------------------------------
#nullable enable
using System;
using System.Collections.Generic;

namespace EFCore.Bencher.EntityClasses
{
	/// Class which represents the entity 'ProductInventory'.
	public partial class ProductInventory : CommonEntityBase
	{
		/// Method called from the constructor
		partial void OnCreated();

		/// Initializes a new instance of the <see cref="ProductInventory"/> class.
		public ProductInventory() : base()
		{
			this.Shelf = string.Empty;
			OnCreated();
		}

		/// Gets or sets the Bin field.
		public System.Byte Bin { get; set; }
		/// Gets or sets the LocationId field.
		public System.Int16 LocationId { get; set; }
		/// Gets or sets the ModifiedDate field.
		public System.DateTime ModifiedDate { get; set; }
		/// Gets or sets the ProductId field.
		public System.Int32 ProductId { get; set; }
		/// Gets or sets the Quantity field.
		public System.Int16 Quantity { get; set; }
		/// Gets or sets the Rowguid field.
		public System.Guid Rowguid { get; set; }
		/// Gets or sets the Shelf field.
		public System.String Shelf { get; set; }
		/// Represents the navigator which is mapped onto the association 'ProductInventory.Location - Location.ProductInventories (m:1)'
		public virtual Location Location { get; set; } = null!;
		/// Represents the navigator which is mapped onto the association 'ProductInventory.Product - Product.ProductInventories (m:1)'
		public virtual Product Product { get; set; } = null!;
	}
}


text:
.class final Lmf/org/apache/xerces/impl/dv/xs/XSSimpleTypeDecl$XSMVFacetImpl;
.super Ljava/lang/Object;
.source "XSSimpleTypeDecl.java"

# interfaces
.implements Lmf/org/apache/xerces/xs/XSMultiValueFacet;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lmf/org/apache/xerces/impl/dv/xs/XSSimpleTypeDecl;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x1a
    name = "XSMVFacetImpl"
.end annotation

# instance fields
.field final annotations:Lmf/org/apache/xerces/xs/XSObjectList;

.field final avalues:Lmf/org/apache/xerces/xs/datatypes/ObjectList;

.field final kind:S

.field final svalues:Lmf/org/apache/xerces/xs/StringList;

# direct methods
.method public constructor <init>(SLmf/org/apache/xerces/xs/StringList;Lmf/org/apache/xerces/xs/datatypes/ObjectList;Lmf/org/apache/xerces/xs/XSObjectList;)V
    .locals 1

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    int-to-short v0, p1

    iput-short v0, p0, Lmf/org/apache/xerces/impl/dv/xs/XSSimpleTypeDecl$XSMVFacetImpl;->kind:S

    iput-object p2, p0, Lmf/org/apache/xerces/impl/dv/xs/XSSimpleTypeDecl$XSMVFacetImpl;->svalues:Lmf/org/apache/xerces/xs/StringList;

    iput-object p3, p0, Lmf/org/apache/xerces/impl/dv/xs/XSSimpleTypeDecl$XSMVFacetImpl;->avalues:Lmf/org/apache/xerces/xs/datatypes/ObjectList;

    if-nez p4, :cond_0

    sget-object p4, Lmf/org/apache/xerces/impl/xs/util/XSObjectListImpl;->EMPTY_LIST:Lmf/org/apache/xerces/impl/xs/util/XSObjectListImpl;

    :cond_0
    iput-object p4, p0, Lmf/org/apache/xerces/impl/dv/xs/XSSimpleTypeDecl$XSMVFacetImpl;->annotations:Lmf/org/apache/xerces/xs/XSObjectList;

    return-void
.end method

# virtual methods
.method public getAnnotations()Lmf/org/apache/xerces/xs/XSObjectList;
    .locals 1

    iget-object v0, p0, Lmf/org/apache/xerces/impl/dv/xs/XSSimpleTypeDecl$XSMVFacetImpl;->annotations:Lmf/org/apache/xerces/xs/XSObjectList;

    return-object v0
.end method

.method public getEnumerationValues()Lmf/org/apache/xerces/xs/datatypes/ObjectList;
    .locals 1

    iget-object v0, p0, Lmf/org/apache/xerces/impl/dv/xs/XSSimpleTypeDecl$XSMVFacetImpl;->avalues:Lmf/org/apache/xerces/xs/datatypes/ObjectList;

    return-object v0
.end method

.method public getFacetKind()S
    .locals 1

    iget-short v0, p0, Lmf/org/apache/xerces/impl/dv/xs/XSSimpleTypeDecl$XSMVFacetImpl;->kind:S

    return v0
.end method

.method public getLexicalFacetValues()Lmf/org/apache/xerces/xs/StringList;
    .locals 1

    iget-object v0, p0, Lmf/org/apache/xerces/impl/dv/xs/XSSimpleTypeDecl$XSMVFacetImpl;->svalues:Lmf/org/apache/xerces/xs/StringList;

    return-object v0
.end method

.method public getName()Ljava/lang/String;
    .locals 1

    const/4 v0, 0x0

    return-object v0
.end method

.method public getNamespace()Ljava/lang/String;
    .locals 1

    const/4 v0, 0x0

    return-object v0
.end method

.method public getNamespaceItem()Lmf/org/apache/xerces/xs/XSNamespaceItem;
    .locals 1

    const/4 v0, 0x0

    return-object v0
.end method

.method public getType()S
    .locals 1

    const/16 v0, 0xe

    return v0
.end method

redpajama_set_name: RedPajamaGithub


text:
namespace Grappachu.Core.Lang.Text
{
    /// <summary>
    ///     Defines representations for binary data
    /// </summary>
    public enum BinaryRepresentation
    {
        /// <summary>
        ///     Hexadecimal format
        /// </summary>
        Hex = 0,

        /// <summary>
        ///     Base64 format
        /// </summary>
        Base64
    }
}


text:
import { ItIsBase } from './ItIsBase';
import { ItIsAny } from './ItIsAny';

export class ItIsRegex extends ItIsBase {
  constructor(public regExp: RegExp) {
    super();
  }

  public match(argument: any): boolean {
    if (!this._isString(argument)) {
      return false;
    }

    return this.regExp.test(argument);
  }

  private _isString(argument: any): boolean {
    var isString = new ItIsAny(String);

    return isString.match(argument);
  }
}


text:
"""
Example showing how to use Qiskit-Terra at level 0 (novice).

This example shows the most basic way to user Terra. It builds some circuits
and runs them on both the BasicAer (local Qiskit provider) or IBMQ (remote IBMQ provider).

To control the compile parameters we have provided a transpile function which can be used
as a level 1 user.

"""

# Import the Qiskit modules
from qiskit import QuantumCircuit
from qiskit import execute, BasicAer

# making first circuit: bell state
qc1 = QuantumCircuit(2, 2)
qc1.h(0)
qc1.cx(0, 1)
qc1.measure([0, 1], [0, 1])

# making another circuit: superpositions
qc2 = QuantumCircuit(2, 2)
qc2.h([0, 1])
qc2.measure([0, 1], [0, 1])

# setting up the backend
print("(BasicAER Backends)")
print(BasicAer.backends())

# running the job
job_sim = execute([qc1, qc2], BasicAer.get_backend("qasm_simulator"))
sim_result = job_sim.result()

# Show the results
print(sim_result.get_counts(qc1))
print(sim_result.get_counts(qc2))


text:
module Waggle
  module ApplicationHelper

    def display_flash_messages
      Waggle::DisplayFlashMessage.new(flash).display
    end

  end
end


text:
from threading import Lock

import re
import logging

from bagpipe.bgp.vpn.ipvpn import VRF
from bagpipe.bgp.vpn.evpn import EVI

import bagpipe.bgp.common.exceptions as exc

from bagpipe.bgp.common.looking_glass import LookingGlass, LGMap
from bagpipe.bgp.common import utils
from bagpipe.bgp.common import logDecorator
from bagpipe.bgp.common.run_command import runCommand

from bagpipe.bgp.vpn.label_allocator import LabelAllocator

from bagpipe.exabgp.message.update.attribute.communities import RouteTarget

log = logging.getLogger(__name__)

def convertRouteTargets(orig_list):
    assert(isinstance(orig_list, list))
    list_ = []
    for rt in orig_list:
        if rt == '':
            continue
        try:
            asn, nn = rt.split(':')
            list_.append(RouteTarget(int(asn), None, int(nn)))
        except Exception:
            raise Exception("Malformed route target: '%s'" % rt)
    return list_

class VPNManager(LookingGlass):

    """
    Creates, and keeps track of, VPN instances (VRFs and EVIs) and passes
    plug/unplug calls to the right VPN instance.
    """

    type2class = {"ipvpn": VRF,
                  "evpn": EVI
                  }

    @logDecorator.log
    def __init__(self, bgpManager, dataplaneDrivers):
        '''
        dataplaneDrivers is a dict from vpn type to each dataplane driver,
        e.g. { "ipvpn": driverA, "evpn": driverB }
        '''

        self.bgpManager = bgpManager

        self.dataplaneDrivers = dataplaneDrivers

        # Init VPN instance identifiers
        self.instanceId = 1

        # VPN instance dict
        self.vpnInstances = {}

        logging.debug("Creating label allocator")
        self.labelAllocator = LabelAllocator()

        # dict containing info how an ipvpn is plugged
        # from an evpn  (keys: ipvpn instances)
        self._evpn_ipvpn_ifs = {}

        self.lock = Lock()

    def _formatIpAddressPrefix(self, ipAddress):
        if re.match(r'([12]?\d?\d\.){3}[12]?\d?\d\/[123]?\d', ipAddress):
            address = ipAddress
        elif re.match(r'([12]?\d?\d\.){3}[12]?\d?\d', ipAddress):
            address = ipAddress + "/32"
        else:
            raise exc.MalformedIPAddress

        return address

    @utils.synchronized
    def getInstanceId(self):
        iid = self.instanceId
        self.instanceId += 1
        return iid

    @logDecorator.logInfo
    def _attach_evpn2ipvpn(self, localPort, ipvpnInstance):
        """ Assuming localPort indicates no real interface but only
        an EVPN, this method will create a pair of twin interfaces, one
        to plug in the EVPN, the other to plug in the IPVPN.

        The localPort dict will be modified so that the 'linuxif' indicates
        the name of the interface to plug in the IPVPN.

        The EVPN instance will be notified so that it forwards traffic
        destinated to the gateway on the interface toward the IPVPN.
        """
        assert('evpn' in localPort)

        if 'id' not in localPort['evpn']:
            raise Exception("Missing parameter 'id' :an external EVPN "
                            "instance id must be specified for an EVPN "
                            "attachment")

        try:
            evpn = self.vpnInstances[localPort['evpn']['id']]
        except:
            raise Exception("The specified evpn instance does not exist (%s)"
                            % localPort['evpn'])

        if (evpn.type != "evpn"):
            raise Exception("The specified instance to plug is not an epnv"
                            "instance (is %s instead)" % evpn.type)

        if ipvpnInstance in self._evpn_ipvpn_ifs:
            (evpn_if, ipvpn_if, evpn, managed) = \
                self._evpn_ipvpn_ifs[ipvpnInstance]

            if not (localPort['evpn']['id'] == evpn.externalInstanceId):
                raise Exception('Trying to plug into an IPVPN a new E-VPN '
                                'while one is already plugged in')
            else:
                # do nothing
                log.warning('Trying to plug an E-VPN into an IPVPN, but it was'
                            'already done')
                localPort['linuxif'] = ipvpn_if
                return

        #  detect if this evpn is already plugged into an IPVPN
        if evpn.hasGatewayPort():
            raise Exception("Trying to plug E-VPN into an IPVPN, but this EVPN"
                            " is already plugged into an IPVPN")

        if ('linuxif' in localPort and localPort['linuxif']):
            raise Exception("Cannot specify an attachment with both a linuxif "
                            "and an evpn")

        if 'ovs_port_name' in localPort['evpn']:
            try:
                assert(localPort['ovs']['plugged'])
                assert(localPort['ovs']['port_name'] or
                       localPort['ovs']['port_number'])
            except:
                raise Exception("Using ovs_port_name in EVPN/IPVPN attachment"
                                " requires specifying the corresponding OVS"
                                " port, which must also be pre-plugged")

            evpn_if = localPort['evpn']['ovs_port_name']

            # we assume in this case that the E-VPN interface is already
            # plugged into the E-VPN bridge
            managed = False
        else:
            evpn_if = "evpn%d-ipvpn%d" % (
                evpn.instanceId, ipvpnInstance.instanceId)
            ipvpn_if = "ipvpn%d-evpn%d" % (
                ipvpnInstance.instanceId, evpn.instanceId)

            # FIXME: do it only if not existing already...
            log.info("Creating veth pair %s %s ", evpn_if, ipvpn_if)

            # delete the interfaces if they exist already
            runCommand(log, "ip link delete %s" %
                       evpn_if, acceptableReturnCodes=[0, 1])
            runCommand(log, "ip link delete %s" %
                       ipvpn_if, acceptableReturnCodes=[0, 1])

            runCommand(log, "ip link add %s type veth peer name %s" %
                       (evpn_if, ipvpn_if))

            runCommand(log, "ip link set %s up" % evpn_if)
            runCommand(log, "ip link set %s up" % ipvpn_if)
            managed = True

        localPort['linuxif'] = ipvpn_if

        evpn.setGatewayPort(evpn_if, ipvpnInstance)

        self._evpn_ipvpn_ifs[ipvpnInstance] = (
            evpn_if, ipvpn_if, evpn, managed)

    @logDecorator.logInfo
    def _detach_evpn2ipvpn(self, ipvpn):
        """
        Symmetric to _attach_evpn2ipvpn
        """
        (evpn_if, ipvpn_if, evpnInstance,
         managed) = self._evpn_ipvpn_ifs[ipvpn]

        if not ipvpn.hasEnpoint(ipvpn_if):
            # TODO: check that this evpn instance is still up and running
            evpnInstance.gatewayPortDown(evpn_if)

            # cleanup veth pair
            if managed:
                runCommand(log, "ip link delete %s" % evpn_if)

            del self._evpn_ipvpn_ifs[ipvpn]

    def _cleanup_evpn2ipvpn(self, ipvpn):
        (_, ipvpn_if, _, managed) = self._evpn_ipvpn_ifs[ipvpn]

        # cleanup veth pair
        if managed:
            runCommand(log, "ovs-vsctl del-port %s" % ipvpn_if)
            runCommand(log, "ip link delete %s" % ipvpn_if)

    @logDecorator.logInfo
    def plugVifToVPN(self, externalInstanceId, instanceType, importRTs,
                     exportRTs, macAddress, ipAddress, gatewayIP,
                     localPort, linuxbr, advertiseSubnet, readvertise):

        # Verify and format IP address with prefix if necessary
        try:
            ipAddressPrefix = self._formatIpAddressPrefix(ipAddress)
        except exc.MalformedIPAddress:
            raise

        # Convert route target string to RouteTarget dictionary
        importRTs = convertRouteTargets(importRTs)
        exportRTs = convertRouteTargets(exportRTs)

        if readvertise:
            try:
                readvertise = {k: convertRouteTargets(readvertise[k])
                               for k in ['from_rt', 'to_rt']}
            except KeyError as e:
                raise Exception("Wrong 'readvertise' parameters: %s" % e)

        # retrieve network mask
        mask = int(ipAddressPrefix.split('/')[1])

        # Retrieve VPN instance or create new one if does not exist
        try:
            vpnInstance = self.vpnInstances[externalInstanceId]
            if (vpnInstance.type != instanceType):
                raise Exception("Trying to plug port on an existing instance "
                                "of a different type (existing: %s, asked: %s)"
                                % (vpnInstance.type, instanceType))
        except KeyError:
            instanceId = self.getInstanceId()
            log.info("Create and start new VPN instance %d for external "
                     "network instance identifier %s", instanceId,
                     externalInstanceId)
            try:
                vpnInstanceFactory = VPNManager.type2class[instanceType]
            except KeyError:
                log.error("Unsupported instanceType for VPNInstance: %s",
                          instanceType)
                raise Exception("Unsupported instance type: %s" % instanceType)

            try:
                dataplaneDriver = self.dataplaneDrivers[instanceType]
            except KeyError:
                log.error("No dataplane driver for VPN type %s",
                          instanceType)
                raise Exception("No dataplane driver for VPN type %s" %
                                instanceType)

            if instanceType == "evpn" and linuxbr:
                kwargs = {'linuxbr': linuxbr}
            else:
                kwargs = {}

            vpnInstance = vpnInstanceFactory(
                self.bgpManager, self.labelAllocator, dataplaneDriver,
                externalInstanceId, instanceId, importRTs, exportRTs,
                gatewayIP, mask, readvertise, **kwargs)

            # Update VPN instance list
            self.vpnInstances[externalInstanceId] = vpnInstance

            vpnInstance.start()

        # Check if new route target import/export must be updated
        if not ((set(vpnInstance.importRTs) == set(importRTs)) and
                (set(vpnInstance.exportRTs) == set(exportRTs))):
            vpnInstance.updateRouteTargets(importRTs, exportRTs)

        if instanceType == "ipvpn" and 'evpn' in localPort:
            # special processing for the case where what we plug into
            # the ipvpn is not an existing interface but an interface
            # to create, connected to an existing evpn instance
            self._attach_evpn2ipvpn(localPort, vpnInstance)

        # Plug VIF to VPN instance
        vpnInstance.vifPlugged(macAddress, ipAddressPrefix, localPort,
                               advertiseSubnet)

    @logDecorator.logInfo
    def unplugVifFromVPN(self, externalInstanceId, macAddress, ipAddress,
                         localPort, readvertise):

        # Verify and format IP address with prefix if necessary
        try:
            ipAddressPrefix = self._formatIpAddressPrefix(ipAddress)
        except exc.MalformedIPAddress:
            raise

        # Retrieve VPN instance or raise exception if does not exist
        try:
            vpnInstance = self.vpnInstances[externalInstanceId]
        except KeyError:
            log.error("Try to unplug VIF from non existing VPN instance %s",
                      externalInstanceId)
            raise exc.VPNNotFound(externalInstanceId)

        # Unplug VIF from VPN instance
        vpnInstance.vifUnplugged(macAddress, ipAddressPrefix, readvertise)

        if vpnInstance.type == "ipvpn" and 'evpn' in localPort:
            self._detach_evpn2ipvpn(vpnInstance)

        if vpnInstance.stopIfEmpty():
            del self.vpnInstances[externalInstanceId]

    @logDecorator.logInfo
    def stop(self):
        for vpnInstance in self.vpnInstances.itervalues():
            vpnInstance.stop()
            # Cleanup veth pair
            if (vpnInstance.type == "ipvpn" and
                    self._evpn_ipvpn_ifs.get(vpnInstance)):
                self._cleanup_evpn2ipvpn(vpnInstance)
        for vpnInstance in self.vpnInstances.itervalues():
            vpnInstance.join()

    # Looking Glass hooks ####

    def getLGMap(self):
        class DataplaneLGHook(LookingGlass):

            def __init__(self, vpnManager):
                self.vpnManager = vpnManager

            def getLGMap(self):
                return {
                    "drivers": (LGMap.COLLECTION, (
                        self.vpnManager.getLGDataplanesList,
                        self.vpnManager.getLGDataplaneFromPathItem)),
                    "ids": (LGMap.DELEGATE, self.vpnManager.labelAllocator)
                }
        dataplaneHook = DataplaneLGHook(self)
        return {
            "instances": (LGMap.COLLECTION, (self.getLGVPNList,
                                             self.getLGVPNFromPathItem)),
            "dataplane": (LGMap.DELEGATE, dataplaneHook)
        }

    def getLGVPNList(self):
        return [{"id": i} for i in self.vpnInstances.iterkeys()]

    def getLGVPNFromPathItem(self, pathItem):
        return self.vpnInstances[pathItem]

    def getVPNInstancesCount(self):
        return len(self.vpnInstances)

    # LookingGLass ########

    def getLGDataplanesList(self):
        return [{"id": i} for i in self.dataplaneDrivers.iterkeys()]

    def getLGDataplaneFromPathItem(self, pathItem):
        return self.dataplaneDrivers[pathItem]


text:
import stream from 'stream'
import { EOL } from 'os'

import {
  BUFFER_SIZE,
  PARTIAL_SECRET_FLAG,
  BATCH_SIZE,
  MAINTENANCE_MODE_AUTO,
  MAINTENANCE_MODE_MANUAL,
} from './constants'

import { ResourceNotExistError } from './resource-errors'
import { AdapterBoundPool, ImportSecretsOptions } from './types'

type ImportStreamContext = {
  pool: any
  maintenanceMode: ImportSecretsOptions['maintenanceMode']
}

const SecretsStream = function (
  this: any,
  { pool, maintenanceMode }: ImportStreamContext
): void {
  stream.Writable.call(this, { objectMode: true })

  this.pool = pool
  this.byteOffset = 0
  this.buffer = Buffer.allocUnsafe(BUFFER_SIZE)
  this.beginPosition = 0
  this.endPosition = 0
  this.vacantSize = BUFFER_SIZE
  this.injectSecretPromiseSet = new Set()
  this.savedErrors = []
  this.maxIdx = 0
  this.maintenanceMode = maintenanceMode
  this.isMaintenanceInProgress = false
  this.parsedRecordCount = 0
  this.bypassMode = false

  this.on('timeout', () => {
    this.externalTimeout = true
  })
}

SecretsStream.prototype = Object.create(stream.Writable.prototype)
SecretsStream.prototype.constructor = stream.Writable

SecretsStream.prototype._write = async function (
  chunk: any,
  encoding: any,
  callback: any
): Promise<void> {
  if (this.bypassMode) {
    await new Promise((resolve) => setImmediate(resolve))
    callback()
    return
  }

  try {
    const { dropSecrets, initSecrets, freeze, injectSecret }: any = this.pool

    if (
      this.maintenanceMode === MAINTENANCE_MODE_AUTO &&
      this.isMaintenanceInProgress === false
    ) {
      this.isMaintenanceInProgress = true
      try {
        await dropSecrets()
      } catch (error) {
        if (!ResourceNotExistError.is(error)) {
          throw error
        }
      }
      await initSecrets()
      await freeze()
    }

    if (this.encoding == null) {
      this.encoding = encoding
    } else if (this.encoding !== encoding) {
      throw new Error('Multiple encodings not supported')
    }
    if (chunk.byteLength > this.vacantSize) {
      throw new Error('Buffer overflow')
    }

    if (chunk.byteLength + this.endPosition <= BUFFER_SIZE) {
      chunk.copy(this.buffer, this.endPosition)
    } else {
      chunk.copy(
        this.buffer,
        this.endPosition,
        0,
        BUFFER_SIZE - this.endPosition
      )
      chunk.copy(
        this.buffer,
        0,
        BUFFER_SIZE - this.endPosition,
        chunk.byteLength
      )
    }
    this.endPosition = (this.endPosition + chunk.byteLength) % BUFFER_SIZE
    this.vacantSize -= chunk.byteLength

    if (this.vacantSize === BUFFER_SIZE) {
      callback()
      return
    }

    let eolPosition = 0
    while (true) {
      eolPosition = chunk.indexOf('\n', eolPosition, this.encoding)
      if (eolPosition < 0) {
        break
      } else {
        eolPosition++
      }

      const endRecordPosition: number =
        (BUFFER_SIZE + this.endPosition - chunk.byteLength + eolPosition) %
        BUFFER_SIZE
      let stringifiedRecord = null
      let recordByteLength = 0

      if (this.beginPosition < endRecordPosition) {
        stringifiedRecord = this.buffer
          .slice(this.beginPosition, endRecordPosition)
          .toString(this.encoding)

        recordByteLength += endRecordPosition - this.beginPosition
      } else {
        stringifiedRecord = this.buffer
          .slice(this.beginPosition, BUFFER_SIZE)
          .toString(this.encoding)
        stringifiedRecord += this.buffer
          .slice(0, endRecordPosition)
          .toString(this.encoding)

        recordByteLength += BUFFER_SIZE - this.beginPosition + endRecordPosition
      }

      this.vacantSize += recordByteLength
      this.beginPosition = endRecordPosition
      this.byteOffset += recordByteLength

      const secret: any = JSON.parse(stringifiedRecord)

      this.maxIdx = Math.max(this.maxIdx, secret.idx)

      const injectSecretPromise = injectSecret(secret).catch(
        this.savedErrors.push.bind(this.savedErrors)
      )
      void injectSecretPromise.then(
        this.injectSecretPromiseSet.delete.bind(
          this.injectSecretPromiseSet,
          injectSecretPromise
        )
      )
      this.injectSecretPromiseSet.add(injectSecretPromise)

      if (this.parsedRecordCount++ >= BATCH_SIZE) {
        await Promise.all([...this.injectSecretPromiseSet])
        if (this.externalTimeout === true) {
          this.bypassMode = true
        }
        this.parsedRecordCount = 0
      }
    }

    callback()
  } catch (error) {
    callback(error)
  }
}

SecretsStream.prototype._final = async function (callback: any): Promise<void> {
  if (this.bypassMode) {
    try {
      await Promise.all([...this.injectSecretPromiseSet])
      callback()
    } catch (err) {
      callback(err)
    } finally {
      this.buffer = null
    }
    return
  }

  try {
    const { unfreeze, injectSecret } = this.pool

    if (this.vacantSize !== BUFFER_SIZE) {
      let stringifiedRecord = null
      let recordByteLength = 0

      if (this.beginPosition < this.endPosition) {
        stringifiedRecord = this.buffer
          .slice(this.beginPosition, this.endPosition)
          .toString(this.encoding)

        recordByteLength += this.endPosition - this.beginPosition
      } else {
        stringifiedRecord = this.buffer
          .slice(this.beginPosition, BUFFER_SIZE)
          .toString(this.encoding)
        stringifiedRecord += this.buffer
          .slice(0, this.endPosition)
          .toString(this.encoding)

        recordByteLength += BUFFER_SIZE - this.beginPosition + this.endPosition
      }

      let secret: any = PARTIAL_SECRET_FLAG
      try {
        secret = JSON.parse(stringifiedRecord)
      } catch {}

      if (secret !== PARTIAL_SECRET_FLAG) {
        this.maxIdx = Math.max(this.maxIdx, secret.idx)

        this.byteOffset += recordByteLength

        const injectSecretPromise: any = injectSecret(secret).catch(
          this.savedErrors.push.bind(this.savedErrors)
        )
        void injectSecretPromise.then(
          this.injectSecretPromiseSet.delete.bind(
            this.injectSecretPromiseSet,
            injectSecretPromise
          )
        )
        this.injectSecretPromiseSet.add(injectSecretPromise)
      }
    }

    await Promise.all([...this.injectSecretPromiseSet])

    if (
      this.maintenanceMode === MAINTENANCE_MODE_AUTO &&
      this.isMaintenanceInProgress === true
    ) {
      this.isMaintenanceInProgress = false
      await unfreeze()
    }

    if (this.savedErrors.length > 0) {
      const error = new Error(
        this.savedErrors.map(({ message }: any) => message).join(EOL)
      )
      error.stack = this.savedErrors.map(({ stack }: any) => stack).join(EOL)
      throw error
    }

    callback()
  } catch (error) {
    callback(error)
  } finally {
    this.buffer = null
  }
}

const importSecretsStream = <ConfiguredProps extends {}>(
  pool: AdapterBoundPool<ConfiguredProps>,
  {
    maintenanceMode = MAINTENANCE_MODE_AUTO,
  }: Partial<ImportSecretsOptions> = {}
): stream.Writable => {
  if (pool.injectSecret === undefined)
    throw new Error('injectSecret is not defined for this adapter')

  switch (maintenanceMode) {
    case MAINTENANCE_MODE_AUTO:
    case MAINTENANCE_MODE_MANUAL:
      return new (SecretsStream as any)({
        pool,
        maintenanceMode,
      })
    default:
      throw new Error(`Wrong maintenance mode ${String(maintenanceMode)}`)
  }
}

export default importSecretsStream


text:
/**
 */
package com.rockwellcollins.atc.resolute.resolute.impl;

import com.rockwellcollins.atc.resolute.resolute.ClaimBody;
import com.rockwellcollins.atc.resolute.resolute.ClaimText;
import com.rockwellcollins.atc.resolute.resolute.ResolutePackage;

import java.util.Collection;

import org.eclipse.emf.common.notify.NotificationChain;

import org.eclipse.emf.common.util.EList;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;

import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;

/**
 *
 * An implementation of the model object 'Claim Body'.
 *
 *

 * The following features are implemented:
 *

 *

 *
{@link com.rockwellcollins.atc.resolute.resolute.impl.ClaimBodyImpl#getClaim Claim}

 *

 *
 * @generated
 */
public class ClaimBodyImpl extends DefinitionBodyImpl implements ClaimBody
{
  /**
   * The cached value of the '{@link #getClaim() Claim}' containment reference list.
   *
   *
   * @see #getClaim()
   * @generated
   * @ordered
   */
  protected EList<ClaimText> claim;

  /**
   *
   *
   * @generated
   */
  protected ClaimBodyImpl()
  {
    super();
  }

  /**
   *
   *
   * @generated
   */
  @Override
  protected EClass eStaticClass()
  {
    return ResolutePackage.Literals.CLAIM_BODY;
  }

  /**
   *
   *
   * @generated
   */
  public EList<ClaimText> getClaim()
  {
    if (claim == null)
    {
      claim = new EObjectContainmentEList<ClaimText>(ClaimText.class, this, ResolutePackage.CLAIM_BODY__CLAIM);
    }
    return claim;
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
  {
    switch (featureID)
    {
      case ResolutePackage.CLAIM_BODY__CLAIM:
        return ((InternalEList<?>)getClaim()).basicRemove(otherEnd, msgs);
    }
    return super.eInverseRemove(otherEnd, featureID, msgs);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public Object eGet(int featureID, boolean resolve, boolean coreType)
  {
    switch (featureID)
    {
      case ResolutePackage.CLAIM_BODY__CLAIM:
        return getClaim();
    }
    return super.eGet(featureID, resolve, coreType);
  }

  /**
   *
   *
   * @generated
   */
  @SuppressWarnings("unchecked")
  @Override
  public void eSet(int featureID, Object newValue)
  {
    switch (featureID)
    {
      case ResolutePackage.CLAIM_BODY__CLAIM:
        getClaim().clear();
        getClaim().addAll((Collection<? extends ClaimText>)newValue);
        return;
    }
    super.eSet(featureID, newValue);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public void eUnset(int featureID)
  {
    switch (featureID)
    {
      case ResolutePackage.CLAIM_BODY__CLAIM:
        getClaim().clear();
        return;
    }
    super.eUnset(featureID);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public boolean eIsSet(int featureID)
  {
    switch (featureID)
    {
      case ResolutePackage.CLAIM_BODY__CLAIM:
        return claim != null && !claim.isEmpty();
    }
    return super.eIsSet(featureID);
  }

} //ClaimBodyImpl


text:
require_relative 'spec_helper'

describe file('/usr/bin/chromedriver') do
  it { should be_file }
  it { should be_mode 755 }
  it { should be_owned_by 'root' }
  it { should be_grouped_into 'root' }
end


text:
'use strict';

// JavaScript issues: There appears to be no efficient and easy way in
// JavaScript to search the contents of a string starting at an arbitrary
// offset, as you can with Lua's `string.match`.  We can set the
// `regexp.lastIndex` before calling `.exec()`, which will skip an initial
// portion of the string but search the entire remainder of the string --
// `^` cannot be used to anchor at `lastIndex`; `^` matches only at the
// beginning of the *string*.  Using substr() + exec() would provide
// something close to the desired functionality but perhaps in a very
// inefficient way.  `string.charCodeAt()` could be efficient, but quite
// tedious.  Perhaps this could be made reasonably easy with the aid of a
// parser generator library.
//
// The approach used here is to call `regexp.exec()` after setting
// `regexp.lastIndex` to match tokens.  This starts as a given point in a
// the string and matches in a non-anchored manner, which is fine for
// identifying tokens. We then extract the matched substring and use
// *anchored* regexps to distinguish keywords (e.g. "end") from other
// identifiers (e.g. "bend") and other types.  Any characters skipped over
// by the non-anchored match are condsidered `text`.

var Class = require ('class.js');

var Highlight = Class.subclass();

// `nodeCtor(type, text)` is a function that constructs a value given the
// matched text and the type that has been assigned to it:
//
//    'keyword'    language keywords
//    'comment'    single- or multi-line comments
//    'number'     numeric constant
//    'string'     string literal
//    'text'       other text (none of the above)
//
Highlight.initialize = function (nodeCtor) {
    this.nodeCtor = nodeCtor;
};

// Reset parsing state, so highlighter can be reused for another file.
//
Highlight.reset = function () {
    this.modeEnd = null;
};

// Parse line into syntax elements. Each element is passed to its associated
// callback. The return value is an array of all callback results.
//
Highlight.doLine = function (line) {
    var m;
    var o = [];
    var text = "";
    var nodeCtor = this.nodeCtor;

    function emit(type, str) {
        o.push(nodeCtor(type, str));
    }

    function flushText() {
        if (text !== '') {
            emit('text', text);
            text = '';
        }
    }

    // This expression should match all of the next token, and maybe some
    // non-tokens.  The matched substring will be later tested with
    // testers/matchers.
    var tokenRE = /0[xX][0-9A-Fa-f]+|(\d+\.?|\.\d)\d*([Ee][-+]?\d+)?|[\w_]+|--.*|['"].*|\[=*\[.*/g;

    // tester should quickly fail for tokens that do not match
    var testers = {
        keyword: /^[a-zA-Z_]/,
        string: /^['"]|^\[=*\[/,
        number: /^\.?\d/,
        comment: /^--/
    };

    var matchers = {
        keyword: /^(and|break|do|else(if)?|end|false|function|goto|i[fn]|local|nil|not|or|repeat|return|then|true|until|while)$/,
        number: /^0[xX][0-9A-Fa-f]+|(\d+\.?|\.\d)\d*([eE][-+]?\d+)?(?![\.\w])/,
        string: /^\[(=*)\[.*?\]\1\]|^'([^'\\]|\\.)*'|^"([^"\\]|\\.)*"/,
        comment: /^--\[(=*)\[.*?\]\1\]|^--(?!\[=*\[).*/
    };

    var pos = 0;

    if (this.modeEnd) {
        // in a multi-line mode... look for end
        m = this.modeEnd.exec(line);
        if (!m) {
            pos = line.length;
        } else {
            pos = m.index + m[0].length;
            this.reset();
        }
        emit(this.modeType, line.substr(0, pos));
    }

    for ( ; pos < line.length; ) {
        // "resume" at pos"
        tokenRE.lastIndex = pos;
        var tokenMatch = tokenRE.exec(line);
        if (!tokenMatch) {
            text += line.substr(pos);
            break;
        }

        text += line.substr(pos, tokenMatch.index-pos);
        pos = tokenMatch.index;
        var token = tokenMatch[0];
        var type = null;

        m = null;
        for (var k in testers) {
            if (testers[k].test(token)) {
                m = matchers[k].exec(token);
                type = k;
                break;
            }
        }

        if (!m && (type == "string" || type == "comment")) {
            // start of multi-line long string

            m = /^-?-?\[(=*)\[.*/.exec(token);
            if (m) {
               this.modeEnd = new RegExp('\]' + m[1] + '\]');
               this.modeType = type;
            }
        }

        if (m) {
            flushText();
            emit(type, m[0]);
            pos += m[0].length;
        } else {
            text += token;
            pos += token.length;
        }
    }
    flushText();

    return o;
};

module.exports = Highlight;


text:
require 'fileutils'
require 'merb/orms/data_mapper/connection'

namespace :db do

  task :merb_start do
    Merb.start_environment :adapter => 'runner',
    :environment => ENV['MERB_ENV'] || 'development'
  end

  desc "Create a sample database.yml file"
  task :database_yaml => :merb_env do
    sample_location = File.join(File.dirname(__FILE__), "..", "merb", "orms", "data_mapper", "database.yml.sample")
    target_location = Merb.dir_for(:config)
    FileUtils.cp sample_location, target_location
  end
  desc "Perform automigration"
  task :automigrate => :merb_env do
    ::DataMapper.auto_migrate!
  end
  desc "Perform non destructive automigration"
  task :autoupgrade => :merb_env do
    ::DataMapper.auto_upgrade!
  end

  namespace :migrate do
    task :load => :merb_env do
      require 'dm-migrations/migration_runner'
      FileList["schema/migrations/*.rb"].each do |migration|
        load migration
      end
    end

    desc "Migrate up using migrations"
    task :up, :version, :needs => :load do |t, args|
      version = args[:version] || ENV['VERSION']
      migrate_up!(version)
    end
    desc "Migrate down using migrations"
    task :down, :version, :needs => :load do |t, args|
      version = args[:version] || ENV['VERSION']
      migrate_down!(version)
    end
  end

  desc "Migrate the database to the latest version"
  task :migrate => 'db:migrate:up'

  desc "Create the database"
  task :create do
    config = Merb::Orms::DataMapper.config
    puts "Creating database '#{config[:database]}'"
    case config[:adapter]
    when 'postgres'
      `createdb -U #{config[:username]} #{config[:database]}`
    when 'mysql'
      `mysqladmin -u #{config[:username]} #{config[:password] ? "-p'#{config[:password]}'" : ''} create #{config[:database]}`
    when 'sqlite3'
      Rake::Task['rake:db:automigrate'].invoke
    else
      raise "Adapter #{config[:adapter]} not supported for creating databases yet."
    end
  end

  desc "Drop the database (postgres only)"
  task :drop do
    config = Merb::Orms::DataMapper.config
    puts "Dropping database '#{config[:database]}'"
    case config[:adapter]
    when 'postgres'
      `dropdb -U #{config[:username]} #{config[:database]}`
    else
      raise "Adapter #{config[:adapter]} not supported for dropping databases yet.\ntry db:automigrate"
    end
  end

  desc "Drop the database, and migrate from scratch"
  task :reset => [:drop, :create, :migrate]
end

namespace :sessions do
  desc "Perform automigration for sessions"
  task :create => :merb_env do
    Merb::DataMapperSessionStore.auto_migrate!
  end

  desc "Clears sessions"
  task :clear => :merb_env do
    Merb::DataMapperSessionStore.all.destroy!
  end
end


text:
var __ = require('platformSupport');
var myAnimation = require('animation');
var fontIconLoader = require("icomoonlib");
var loader = require("loader");
var loadingWindow = require('loadingWindow');
var dialogBox = require("psdialog");

var profileIcon = fontIconLoader.getIcon("panacea","profile",35,{color:Alloy.CFG.Colors.SideMenuIconColor});
var homeIcon = fontIconLoader.getIcon("panacea","home",35,{color:Alloy.CFG.Colors.SideMenuIconColor});
var sideMenuIcon = fontIconLoader.getIcon("panacea","navicon",35,{color:Alloy.CFG.Colors.IconWhite});
var favouriteIcon = fontIconLoader.getIcon("panacea","star",35,{color:Alloy.CFG.Colors.SideMenuIconColor});
var feedIcon = fontIconLoader.getIcon("panacea","rss",35,{color:Alloy.CFG.Colors.SideMenuIconColor});
var signOutIcon = fontIconLoader.getIcon("panacea","sign-out",35,{color:Alloy.CFG.Colors.SideMenuIconColor});
var popularIcon = fontIconLoader.getIcon("panacea","tag",35,{color:Alloy.CFG.Colors.SideMenuIconColor});

var appWrapper = null;
var isSliderOpen = false;
var homeData = null;
var newsData;
var popData;
var users = Alloy.Collections.users;

$.imgSideMenu.image = sideMenuIcon;

if(Alloy.isTablet) {
	$.imgSideMenu.width = 25;
	$.imgSideMenu.height = 25;
}

if (__.isiOS7Plus()) {
	$.AppWrapper.top = 20;
}

var beforeNodes = [
	{
		menuHeader : Alloy.CFG.Languages.appName,
		id : 0,
		title : Alloy.CFG.Languages.lblHome,
		image : homeIcon
	},
	{
		id : 1,
		title : Alloy.CFG.Languages.lblNewsFeed,
		image : feedIcon
	},
	{
		id : 2,
		title : Alloy.CFG.Languages.lblPopular,
		image : popularIcon
	},
	{
		id : 3,
		title : Alloy.CFG.Languages.lblFavourite,
		image : favouriteIcon
	},
	{
		id : 4,
		title : Alloy.CFG.Languages.lblProfile,
		image : profileIcon
	}
];

var afterNodes = [
	{
		menuHeader : Alloy.CFG.Languages.appName,
		id : 0,
		title : Alloy.CFG.Languages.lblHome,
		image : homeIcon
	},
	{
		id : 1,
		title : Alloy.CFG.Languages.lblNewsFeed,
		image : feedIcon
	},
	{
		id : 2,
		title : Alloy.CFG.Languages.lblPopular,
		image : popularIcon
	},
	{
		id : 3,
		title : Alloy.CFG.Languages.lblFavourite,
		image : favouriteIcon
	},
	{
		id : 4,
		title : Alloy.CFG.Languages.lblProfile,
		image : profileIcon
	},
	{
		id : 5,
		title : Alloy.CFG.Languages.lbllogout,
		image : signOutIcon
	}
];

function handleMenuClick(_event)
{
	if ( typeof _event.row.id !== "undefined") {
		openScreen(_event.row.id);
	}
}

function openScreen(rowID)
{
	if (rowID == 0) {
		if(homeData != "null"){
			loadContentView("home", homeData);
		}else{
			loadContentView("home", "My Account");
		}
	} else if (rowID == 1) {
		loadAllFeeds();
	} else if (rowID == 2) {
		var params = {
			name : Alloy.CFG.Languages.lblPopular
		};
		loadContentView("popularList", params);
	} else if (rowID == 3) {
		if(Ti.App.Properties.getString("userId") != null) {
			var params = {
				name : Alloy.CFG.Languages.lblFavourite
			};
			loadContentView("favouriteList", params);
		} else {
			var params = {
				name : Alloy.CFG.Languages.lblProfile
			};
			loadContentView("userProfile", params);
			$.SlideMenu.setIndex(4);
			dialogBox.loadCustomDialog("My Favourite", Alloy.CFG.Languages.needForFavouriteListMesssage);
		}
	} else if (rowID == 4) {
		var params = {
			name : Alloy.CFG.Languages.lblProfile
		};
		loadContentView("userProfile", params);
	}  else if (rowID == 5) {
		var user = users.get(Ti.App.Properties.getString("userId"));
		if (user != null) {
			user.destroy();
		}
		users.fetch();
		Ti.App.Properties.setString('userId', null);

		if(homeData != "null"){
			loadContentView("home", homeData);
		}else{
			loadContentView("home", "My Account");
		}

		$.SlideMenu.clear();
		$.SlideMenu.Nodes.removeEventListener("click", handleMenuClick);
		initSlideMenu(beforeNodes);
	}

	closeMenu();
}

var loadContentView = function(viewName, args)
{
	var contentView = Alloy.createController(viewName, args).getView();
	$.midContainer.removeAllChildren();
	$.midContainer.add(contentView);
	if(null != args) {
		$.mainTitle.text = args.name;
	} else {
		$.mainTitle.text = Alloy.CFG.Languages.appName;
	}
};

function initProcess()
{
	appWrapper = $.AppWrapper;

	if(OS_IOS) {
		$.AppWrapper.addEventListener("swipe", function(_event) {
			if (_event.direction == "right") {
				openMenu();

			} else if (_event.direction == "left") {
				closeMenu();
			}
		});
	}

}

function openMenu()
{
	appWrapper.animate({
		left : "200dp",
		right : "-200dp",
		duration : 250,
		curve : Ti.UI.ANIMATION_CURVE_EASE_IN_OUT
	});

	$.SlideMenu.Wrapper.animate({
		left : "0dp",
		right : "0dp",
		duration : 250,
		curve : Ti.UI.ANIMATION_CURVE_EASE_IN_OUT
	});

	isSliderOpen = true;
}

function closeMenu()
{
	appWrapper.animate({
		left : "0dp",
		right : "0dp",
		duration : 250,
		curve : Ti.UI.ANIMATION_CURVE_EASE_IN_OUT
	});

	$.SlideMenu.Wrapper.animate({
		left : "-200dp",
		duration : 250,
		curve : Ti.UI.ANIMATION_CURVE_EASE_IN_OUT
	});

	isSliderOpen = false;
}

function openLeftMenu()
{
	if (isSliderOpen) {
		closeMenu();
	} else {
		openMenu();
	}
}

function initSlideMenu(nodes)
{

	$.SlideMenu.init({
		nodes : nodes,
		color : {
			headingBackground : "#000",
			headingText : "#FFF"
		}
	});

	$.SlideMenu.setIndex(0);
	$.SlideMenu.Nodes.addEventListener("click", handleMenuClick);

}

var callBackLoadAllCategories = function(args)
{
	if(args.length != 0) {
		homeData = args;
		args.name = Alloy.CFG.Languages.appName;
		loadContentView('home', args);
	} else {
		dialogBox.loadCustomDialog("CityTour", Alloy.CFG.Languages.dataNotFound);
		loadingWindow.endLoading();
	}
};

var loadAllCategories = function()
{
	var loaderArgs = {
		callbackFunction : callBackLoadAllCategories,
		url : Alloy.CFG.Urls.baseURL + Alloy.CFG.Urls.getCategoriesWithThreeItems
	};
	loader.get(loaderArgs);
};

var updateFromVal = function()
{
	var limit = Alloy.CFG.LimitOfPosts;
	var from = Ti.App.Properties.getInt("From");
	Ti.App.Properties.setInt("From", (limit+from));
};

var loadAllFeeds = function()
{

	var limit = Alloy.CFG.LimitOfPosts;
	Ti.App.Properties.setInt("From", 0);

	var loaderArgs = {
		callbackFunction : callBackLoadAllFeeds,
		url : Alloy.CFG.Urls.baseURL + Alloy.CFG.Urls.getFeeds + limit + '/from/0'
	};
	loader.get(loaderArgs);
};

var callBackLoadAllFeeds = function(argsFeeds)
{
	if(argsFeeds != null) {
		if(argsFeeds.length > 0) {
			newsData = argsFeeds;
			updateFromVal();

			newsData.name = Alloy.CFG.Languages.lblNewsFeed;
			loadContentView("newsList", newsData);
		}
	}
};

$.index.addEventListener('open', function()
{
	loadingWindow.startLoading();
	loadAllCategories();

	initProcess();

	if(Ti.App.Properties.getString("userId") != null) {
		initSlideMenu(afterNodes);
	} else {
		initSlideMenu(beforeNodes);
	}

});

Ti.App.addEventListener('refreshMenu',function(e)
{
	$.SlideMenu.clear();
	$.SlideMenu.Nodes.removeEventListener("click", handleMenuClick);
	initSlideMenu(afterNodes);
});

$.index.open();


text:
<?php
if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');

/**
 * Provide application specific logic to the session object.
 * @api
 */
class SugarSession{
	private static $_instance;
	public static $sessionId;

	/**
	 * When constructing the session object, be sure to check if the session_id() already exists as is the case of session.auto_start = 1
	 *
	 */
	public function __construct(){

	}

	public function setSessionId($sessionId){
		self::$sessionId = session_id($sessionId);
	}

	public function start(){
		$session_id = session_id();
		if(empty($session_id)){
			session_start();
			self::$sessionId = session_id();
		}else{
			self::$sessionId = $session_id;
		}
	}

	public static function getInstance(){
		if(!isset(self::$_instance)){
			$className = __CLASS__;
			self::$_instance = new $className();
		}

		return self::$_instance;
	}

	public function destroy(){
		foreach ($_SESSION as $var => $val) {
        	$_SESSION[$var] = null;
        }
		session_destroy();
	}

	public function __clone(){

	}

	public function __get($var){
		return (!empty($_SESSION[$var]) ? $_SESSION[$var] : '');
	}

	public function __set($var, $val){
		return ($_SESSION[$var] = $val);
	}

	public function __destruct(){
		session_write_close();
	}
}
?>


text:
/**
 *
 */
package com.manning.sdmia.directory.modular.dao.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

import com.manning.sdmia.directory.dao.ContactDao;
import com.manning.sdmia.directory.domain.Contact;

/**
 * @author acogoluegnes
 *
 */
public class ContactDaoJdbc extends SimpleJdbcDaoSupport implements ContactDao {

	private static final String SQL_SELECT_CONTACTS = "select idcontact,firstname,lastname from directory_contact";

	private UserRowMapper userRowMapper = new UserRowMapper();

	/*
	 * (non-Javadoc)
	 * @see com.manning.sdmia.directory.dao.ContactDao#getContacts()
	 */
	@Override
	public List<Contact> getContacts() {
		List<Contact> contacts = getSimpleJdbcTemplate().query(SQL_SELECT_CONTACTS, userRowMapper);
		return contacts;
	}

	private class UserRowMapper implements ParameterizedRowMapper<Contact> {

		@Override
		public Contact mapRow(ResultSet rs, int row) throws SQLException {
			Contact user = new Contact();
			user.setId(rs.getLong("idcontact"));
			user.setFirstname(rs.getString("firstname"));
			user.setLastname(rs.getString("lastname"));
			return user;
		}

	}

}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    android:baselineAligned="false"
    android:divider="?android:attr/dividerHorizontal"
    android:orientation="horizontal"
    android:showDividers="middle"
    tools:context=".LogRecordListActivity" >

    <!--
    This layout is a two-pane layout for the Log Records
    master/detail flow. See res/values-large/refs.xml and
    res/values-sw600dp/refs.xml for an example of layout aliases
    that replace the single-pane version of the layout with
    this two-pane version.

    For more on layout aliases, see:
    http://developer.android.com/training/multiscreen/screensizes.html#TaskUseAliasFilters
    -->

    <fragment
        android:id="@+id/logrecord_list"
        android:name="org.programus.android.clipblacklist.LogRecordListFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        tools:layout="@android:layout/list_content" />

    <FrameLayout
        android:id="@+id/logrecord_detail_container"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3" />

</LinearLayout>


text:
* Builder.ToQueryString - Turn flat object into a query string
* Builder.ToQueryString - Turn object with array into a query string
* Builder.ToQueryString - Turn object into query string with custom field converter
* Builder.ToQueryString - Turn object into query string with camel case fields
* Builder.ToQueryString - Turn object value into dictionary
* Builder.ToQueryString - Turn object with deep graph into deep nested key
* Builder.ToQueryString - Objects with properties that are null are returned with no value


text:
class AddPrecisionToIccaSiteCoordinates < ActiveRecord::Migration[5.2]
  def up
    change_column :icca_sites, :lat, :decimal, precision: 9, scale: 7
    change_column :icca_sites, :lon, :decimal, precision: 10, scale: 7
  end

  def down
    change_column :icca_sites, :lat, :float
    change_column :icca_sites, :lon, :float
  end
end


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Lightbox Example</title>
  <link rel="stylesheet" href="./style.css">

Lightbox Example

    <select id="service"></select>


text:
(function($, window) {
    tinymce.init({
  selector: 'textarea',
  height: 500,
  menubar: false,
  plugins: [
    'advlist autolink lists link image charmap print preview anchor',
    'searchreplace visualblocks code fullscreen',
    'insertdatetime table contextmenu paste code'
  ],
  toolbar: 'undo redo | insert | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
  content_css: '//www.tinymce.com/css/codepen.min.css'
});
}).call(this, jQuery, window);


text:
/*
Problem 24. Order words

Write a program that reads a list of words, separated by spaces and prints the list in an alphabetical order.
*/

using System;
class SortWords
{
    static void Main()
    {
        string text = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout The point of using Lorem Ipsum is that it has a more or less normal distribution of letters as opposed to using Content here content here making it look like readable English Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text and a search for lorem ipsum will uncover many web sites still in their infancy Various versions have evolved over the years sometimes by accident sometimes on purpose";
        string[] words = text.ToLower().Split(' ');
        Array.Sort(words);
        foreach (string word in words) Console.WriteLine(word);
    }
}


text:
namespace Baseclass.Contrib.Mef.Catalogs.Criteria
{
    using System.Collections.Generic;
    using System.Reflection;

    /// <summary>
    ///   Defines the contract for the criteria responsible to filter assemblies for the discovery in <see cref="AssemblyFilteredDirectoryCatalog"/>.
    /// </summary>
    public interface IAssemblyNameCriteria
    {
        #region Public Methods and Operators

        /// <summary>
        /// Filters an enumerable of <see cref="IEnumerable{AssemblyName}"/>s.
        /// </summary>
        /// <param name="assemblyNames">
        /// The enumerable of <see cref="AssemblyName"/> which should be filtered.
        /// </param>
        /// <returns>
        /// The enumerable of <see cref="AssemblyName"/> which meets this criteria.
        /// </returns>
        IEnumerable<AssemblyName> MeetCriteria(IEnumerable<AssemblyName> assemblyNames);

        #endregion
    }
}


text:
<?php

namespace common\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;

/**
 * This is the model class for table "{{%product_image}}".
 *
 * @property integer $id
 * @property integer $product_id
 * @property integer $type
 * @property string $url
 * @property string $created_at
 * @property string $updated_at
 *
 * @property Product $product
 */
class ProductImage extends Entity
{
    const TYPE_ACCESSORIESIMAGE = 1;
    const TYPE_ALTERNATEVIEWSIMAGE = 2;
    const TYPE_ANGLEIMAGE = 3;
    const TYPE_BACKVIEWIMAGE = 4;
    const TYPE_ENERGYGUIDEIMAGE = 5;
    const TYPE_IMAGE = 6;
    const TYPE_LARGEFRONTIMAGE = 7;
    const TYPE_LARGEIMAGE = 8;
    const TYPE_LEFTVIEWIMAGE = 9;
    const TYPE_MEDIUMIMAGE = 10;
    const TYPE_REMOTECONTROLIMAGE = 11;
    const TYPE_RIGHTVIEWIMAGE = 12;
    const TYPE_SPIN360URL = 13;
    const TYPE_THUMBNAILIMAGE = 14;
    const TYPE_TOPVIEWIMAGE = 15;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%product_image}}';
    }

    /**
     *
     * {@inheritDoc}
     * @see \yii\base\Component::behaviors()
     */
    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'value' => new Expression('NOW()'),
            ]
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['product_id', 'type', 'url'], 'required'],
            [['product_id', 'type'], 'integer'],
            [['created_at', 'updated_at'], 'safe'],
            [['product_id'], 'exist', 'skipOnError' => true, 'targetClass' => Product::className(), 'targetAttribute' => ['product_id' => 'id']],
        ];
    }

    /**
     *
     * {@inheritDoc}
     * @see \yii\elasticsearch\ActiveRecord::attributes()
     */
    public function attributes()
    {
        return [
            'id',
            'product_id',
            'type',
            'url',
            'created_at',
            'updated_at',
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'product_id' => Yii::t('app', 'Product ID'),
            'type' => Yii::t('app', 'Type'),
            'url' => Yii::t('app', 'Url'),
            'created_at' => Yii::t('app', 'Created At'),
            'updated_at' => Yii::t('app', 'Updated At'),
        ];
    }

    /**
     * @return string[]
     */
    public static function imageLabels()
    {
        return [
            self::TYPE_ACCESSORIESIMAGE => Yii::t('app', 'Accessories'),
            self::TYPE_ALTERNATEVIEWSIMAGE => Yii::t('app', 'Alternate View'),
            self::TYPE_ANGLEIMAGE => Yii::t('app', 'Angle View'),
            self::TYPE_BACKVIEWIMAGE => Yii::t('app', 'Back View'),
            self::TYPE_ENERGYGUIDEIMAGE => Yii::t('app', 'Energy Guide'),
            self::TYPE_IMAGE => Yii::t('app', 'Image'),
            self::TYPE_LARGEFRONTIMAGE => Yii::t('app', 'Large Front'),
            self::TYPE_LARGEIMAGE => Yii::t('app', 'Large Image'),
            self::TYPE_LEFTVIEWIMAGE => Yii::t('app', 'Left View'),
            self::TYPE_MEDIUMIMAGE => Yii::t('app', 'Medium Image'),
            self::TYPE_REMOTECONTROLIMAGE => Yii::t('app', 'Remote Controller'),
            self::TYPE_RIGHTVIEWIMAGE => Yii::t('app', 'Right View'),
            self::TYPE_SPIN360URL => Yii::t('app', 'Spin 360'),
            self::TYPE_THUMBNAILIMAGE => Yii::t('app', 'Thumbnail'),
            self::TYPE_TOPVIEWIMAGE => Yii::t('app', 'Top View'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProduct()
    {
        return $this->hasOne(Product::className(), ['id' => 'product_id']);
    }

    /**
     * @return string
     */
    public function getLabel()
    {
        return self::imageLabels()[$this->type];
    }

    /**
     *
     * @param integer $product_id
     * @param array $images
     */
    public static function upsertAllByProductId($product_id, array $images)
    {
        $Images = self::find()->where(['product_id' => $product_id])->indexBy('type')->all();
        $imagesToInsert = [];
        $imagesToDelete = [];
        $imagesToUpdate = [];

        foreach ($images as $type => $url)
        {
            if (!empty($url))
            {
                if (!isset($Images[$type]))
                {
                    $imagesToInsert[] = [$product_id, $type, $url, new Expression('NOW()'), new Expression('NOW()')];
                }
                elseif ($Images[$type]->url != $url)
                {
                    $Images[$type]->url = $url;
                    $Images[$type]->save();
                }
            }
            else
            {
                $imagesToDelete[] = $type;
            }
        }

        if (!empty($imagesToInsert))
        {
            self::getDb()->createCommand()->batchInsert(self::tableName(),
                ['product_id', 'type', 'url', 'created_at', 'updated_at'], $imagesToInsert)->execute();
        }

        if (!empty($imagesToDelete))
        {
            self::deleteAll(['product_id' => $product_id, 'type' => $imagesToDelete]);
        }
    }
}


text:
<?php

/*
 * This file is part of the GeckoPackages.
 *
 * (c) GeckoPackages https://github.com/GeckoPackages
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace GeckoPackages\Silex\Services\Config\Loader;

use Symfony\Component\Filesystem\Exception\FileNotFoundException;
use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Parser;

/**
 * @internal
 *
 * @author SpacePossum
 */
final class YamlLoader implements LoaderInterface
{
    /**
     * @var Parser
     */
    private $parser;

    public function __construct()
    {
        $this->parser = new Parser();
    }

    /**
     * {@inheritdoc}
     */
    public function getConfig($file)
    {
        if (false === is_file($file)) {
            throw new FileNotFoundException(sprintf('Config file not found "%s".', $file));
        }

        if (false === $config = @file_get_contents($file)) {
            throw new IOException(sprintf('Failed to load config file "%s".', $file));
        }

        try {
            $config = $this->parser->parse($config);
        } catch (ParseException $e) {
            throw new IOException(sprintf('Failed to parse config file "%s". %s', $file, $e->getMessage()), $e->getCode(), $e);
        }

        return $config;
    }
}


text:
/* @flow */
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { actions as gameActions } from '../../redux/modules/games';
import TicTacToeBoard from 'components/TicTacToeBoard';
import MoveList from 'components/MoveList';
import GameDetailHeader from 'components/GameDetailHeader';
import styles from './GameDetailView.scss';
// import GameList from 'components/GameList';

// We can use Flow (http://flowtype.org/) to type our component's props
// and state. For convenience we've included both regular propTypes and
// Flow types, but if you want to try just using Flow you'll want to
// disable the eslint rule `react/prop-types`.
// NOTE: You can run `npm run flow:check` to check for any errors in your
// code, or `npm i -g flow-bin` to have access to the binary globally.
// Sorry Windows users :(.
// type Props = {};

// We avoid using the `@connect` decorator on the class definition so
// that we can export the undecorated component for testing.
// See: http://rackt.github.io/redux/docs/recipes/WritingTests.html
export class GameDetailView extends React.Component {
  constructor () {
    super();
    this.state = {
      currentlyDisplayedMove: 0,
    };
  }
  // props: Props;
  static propTypes = {
    gameActions: PropTypes.object.isRequired,
    currentGame: PropTypes.object.isRequired,
    params: PropTypes.object.isRequired,
  };

  componentDidMount = () => {
    this.props.gameActions.getGameDetail(this.props.params.id);
  }

  componentWillUnmount = () => {
    this.props.gameActions.clearGameDetail();
  }

  componentWillReceiveProps = (nextProps) => {
    this.setState({
      ...this.state,
      currentlyDisplayedMove: nextProps.currentGame.moves.length - 1,
    });
  }

  handleSliderOnChange = (e) => {
    this.setState({
      ...this.state,
      currentlyDisplayedMove: e.target.value,
    });
  }

  handleMoveOnClick = (moveIdx) => {
    this.setState({
      ...this.state,
      currentlyDisplayedMove: moveIdx,
    });
  }

  render () {
    if (!this.props.currentGame) {
      return (Loading...);
    }

    const lastMove = this.props.currentGame.moves[this.props.currentGame.moves.length - 1];

    const currentGameState = this.props.currentGame.moves[this.state.currentlyDisplayedMove].gameState;
    const previousMove = this.props.currentGame.moves[this.state.currentlyDisplayedMove - 1];
    let previousGameState;
    if (previousMove === undefined) {
      previousGameState = undefined;
    } else {
      previousGameState = previousMove.gameState;
    }

    return (

        <GameDetailHeader
          game={this.props.currentGame}
          lastMove={lastMove}
          />

          <TicTacToeBoard
            currentGameState={currentGameState}
            previousGameState={previousGameState}
            />

Moves

            Adjust the slider or click on a move to view that move on the board.

          <input
            type='range'
            className={styles.movesSlider}
            min='0'
            max={this.props.currentGame.moves.length - 1}
            step='1'
            onChange={this.handleSliderOnChange}
            value={this.state.currentlyDisplayedMove}
            />
          <MoveList
            moves={this.props.currentGame.moves}
            moveOnClick={this.handleMoveOnClick}
            highlightMoveIndex={this.state.currentlyDisplayedMove}
            />

    );
  }
}

const mapStateToProps = (state) => ({
  currentGame: state.games.currentGame,
});

const mapDisptachToProps = (dispatch) => {
  return {
    gameActions: bindActionCreators(gameActions, dispatch),
  };
};

export default connect(mapStateToProps, mapDisptachToProps)(GameDetailView);


text:
<?php

App::uses('AclNode', 'Model');

/**
 * AclAco Model
 *
 * @category Model
 * @package  Croogo.Acl.Model
 * @version  1.0
 * @author   Fahad Ibnay Heylaal <contact@fahad19.com>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://www.croogo.org
 */
class AclAco extends AclNode {

/**
 * name
 *
 * @var string
 */
	public $name = 'AclAco';

/**
 * useTable
 *
 * @var string
 */
	public $useTable = 'acos';

/**
 * actsAs
 *
 * @var array
 */
	public $actsAs = array('Tree');

/**
 * alias
 *
 */
	public $alias = 'Aco';

/**
 * hasAndBelongsToMany
 */
	public $hasAndBelongsToMany = array(
		'Aro' => array(
			'with' => 'Acl.AclPermission',
		),
	);

/**
 * getChildren
 *
 * @param integer aco id
 */
	public function getChildren($acoId, $fields = array()) {
		$fields = Hash::merge(array('id', 'parent_id', 'alias'), $fields);
		$acos = $this->children($acoId, true, $fields);
		foreach ($acos as &$aco) {
			$aco[$this->alias]['children'] = $this->childCount($aco[$this->alias]['id'], true);
		}
		return $acos;
	}

/**
 * Create ACO tree
 */
	public function createFromPath($path) {
		$pathE = explode('/', $path);
		$parent = $current = null;
		foreach ($pathE as $alias) {
			$current[] = $alias;
			$node = $this->node(join('/', $current));
			if ($node) {
				$parent = $node[0];
			} else {
				$aco = $this->create(array(
					'parent_id' => $parent['Aco']['id'],
					'alias' => $alias,
				));
				$parent = $this->save($aco);
			}
		}
		return $parent;
	}

/**
 * ACL: add ACO
 *
 * Creates ACOs with permissions for roles.
 *
 * @param string $action possible values: Controller, Controller/action,
 *                                        Plugin/Controller/action
 * @param array $allowRoles Role aliases
 * @return void
 */
	public function addAco($action, $allowRoles = array()) {
		// AROs
		$roles = array();
		if (count($allowRoles) > 0) {
			$roles = ClassRegistry::init('Users.Role')->find('list', array(
				'conditions' => array(
					'Role.alias' => $allowRoles,
				),
				'fields' => array(
					'Role.id',
					'Role.alias',
				),
			));
		}

		$this->createFromPath($action);
		$Permission = ClassRegistry::init('Acl.AclPermission');
		foreach ($roles as $roleId => $roleAlias) {
			$Permission->allow(array('model' => 'Role', 'foreign_key' => $roleId), $action);
		}
	}

/**
 * ACL: remove ACO
 *
 * Removes ACOs and their Permissions
 *
 * @param string $action possible values: ControllerName, ControllerName/method_name
 * @return void
 */
	public function removeAco($action) {
		$acoNode = $this->node($action);
		if (isset($acoNode['0']['Aco']['id'])) {
			$this->delete($acoNode['0']['Aco']['id']);
		}
	}

/**
 * Get valid permission roots
 *
 * @return array Array of valid permission roots
 */
	public function getPermissionRoots() {
		$roots = $this->find('all', array(
			'recursive' => -1,
			'fields' => array('id', 'alias'),
			'conditions' => array(
				'parent_id' => null,
				'alias' => array('controllers', 'api'),
			),
		));

		$apiRoot = -1;
		foreach ($roots as $i => &$root) {
			if ($root['Aco']['alias'] === 'api') {
				$apiRoot = $root['Aco']['id'];
				$apiIndex = $i;
			}
			$root['Aco']['title'] = ucfirst($root['Aco']['alias']);
		}
		if (isset($apiIndex)) {
			unset($roots[$apiIndex]);
		}

		$versionRoots = $this->find('all', array(
			'recursive' => -1,
			'fields' => array('id', 'alias'),
			'conditions' => array(
				'parent_id' => $apiRoot,
			),
		));

		$apiCount = count($versionRoots);

		$api = __d('croogo', 'API');
		foreach ($versionRoots as &$versionRoot) {
			$alias = strtolower(str_replace('_', '.', $versionRoot['Aco']['alias']));
			$versionRoot['Aco']['alias'] = $alias;
			$versionRoot['Aco']['title'] = $apiCount == 1 ? $api : $api . ' ' . $alias;
		}

		return array_merge($roots, $versionRoots);
	}

}


text:
OSName=$(uname -s)
case $OSName in
    Darwin)
        OS=OSX
        ;;

    Linux)
        OS=Linux
        ;;

    *)
        echo "Unsupported OS '$OSName' detected. Cannot continue with build, the scripts must be updated to support this OS."
        exit 1
        ;;
esac

# On Linux (or at least, Ubuntu), when building with Mono, need to install the mono-devel package first.
if [ $OS = 'Linux' ]; then
    sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
    echo "deb http://download.mono-project.com/repo/debian wheezy main" | sudo tee /etc/apt/sources.list.d/mono-xamarin.list
    sudo apt-get update
    sudo apt-get -y install mono-devel
fi

# Check if SSL certificates have been imported into Mono's certificate store.
# If certs haven't been installed, some/all of the Nuget packages will fail to restore.
#if [ $('certmgr -list -c Trust | grep -c -F "X.509"') -le 1 ]; then
#  echo "No SSL certificates installed so unable to restore NuGet packages." >&2;
#  echo "Run 'mozroots --sync --import' to install certificates to Mono's certificate store." >&2;
#  exit 1
#fi

# Restore NuGet packages (needed for compiler bootstrap and tests).
mono .nuget/NuGet.exe restore packages.config -PackagesDirectory packages -ConfigFile .nuget/NuGet.Config

(if test x-$BUILD_CORECLR = x-1; then \
  sudo sh -c 'echo "deb [arch=amd64] https://apt-mo.trafficmanager.net/repos/dotnet-release/ trusty main" > /etc/apt/sources.list.d/dotnetdev.list'; \
  sudo apt-key adv --keyserver apt-mo.trafficmanager.net --recv-keys 417A0893; \
  sudo apt-get update; \
  sudo apt-get -y install dotnet-dev-1.0.0-preview2-003131; \
  (cd tests/fsharp; mono ../../.nuget/NuGet.exe restore  project.json -PackagesDirectory ../../packages -ConfigFile ../../.nuget/NuGet.Config); \
  ./init-tools.sh;   \
  echo "------ start log";  \
  cat ./init-tools.log; echo "------ end log"; \
fi)

(if test x-$BUILD_PROTO_WITH_CORECLR_LKG = x-1; then \
  (cd lkg/fsc &&  dotnet restore --packages ../packages && dotnet publish project.json -o ../Tools/lkg -r ubuntu.14.04-x64); \
  (cd lkg/fsi &&  dotnet restore --packages ../packages && dotnet publish project.json -o ../Tools/lkg -r ubuntu.14.04-x64); \
fi)

#TODO: work out how to avoid the need for this
echo "chmod u+x packages/FSharp.Compiler.Tools.4.0.1.21/tools/fsi.exe"
echo "chmod u+x packages/FsLexYacc.7.0.4/build/fslex.exe"
echo "chmod u+x packages/FsLexYacc.7.0.4/build/fsyacc.exe"
chmod u+x packages/FSharp.Compiler.Tools.4.0.1.21/tools/fsi.exe
chmod u+x packages/FsLexYacc.7.0.4/build/fslex.exe
chmod u+x packages/FsLexYacc.7.0.4/build/fsyacc.exe

# The FSharp.Compiler.Tools package doesn't work correctly unless a proper install of F# has been done on the machine.
# OSX can skip this because the OSX Mono installer includes F#.
if [ $OS != 'OSX' ]; then
    sudo apt-get -y install fsharp
fi

# "access to the path /etc/mono/registry/last-time is denied"
# On non-OSX systems, may need to create Mono's registry folder to avoid exceptions during builds.
# This doesn't seem to be necessary on OSX, as the folder is created by the installer.
if [ $OS != 'OSX' ]; then
    # This registry folder path is correct for Linux;
    # on OSX the folder is /Library/Frameworks/Mono.framework/Versions/Current/etc/mono/registry
    # and may be different for *BSD systems.
    __MonoRegistryDir="/etc/mono/registry"
    if [ ! -d "$__MonoRegistryDir" ]; then
      echo "Mono registry directory does not exist (it may not have been created yet)."
      echo "The directory needs to be created now; superuser permissions are required for this."
      { sudo -- sh -c "mkdir -p $__MonoRegistryDir && chmod uog+rw $__MonoRegistryDir"; } || { echo "Unable to create/chmod Mono registry directory '$__MonoRegistryDir'." >&2; }
    fi
fi


text:
from __future__ import absolute_import, division, print_function

import gzip
from functools import partial
from unittest import TestCase
from datashape import var, dshape

from blaze.data import *
from blaze.utils import filetexts
import json

import json

data = {'a.json': {u'name': u'Alice', u'amount': 100},
        'b.json': {u'name': u'Bob', u'amount': 200},
        'c.json': {u'name': u'Charlie', u'amount': 50}}

tuples = (('Alice', 100),
          ('Bob', 200),
          ('Charlie', 50))

texts = dict((fn, json.dumps(val)) for fn, val in data.items())

schema = '{name: string, amount: int}'

class Test_Integrative(TestCase):
    def test_gzip_json_files(self):
        with filetexts(texts, open=gzip.open) as filenames:
            descriptors = [JSON(fn, dshape=schema, open=gzip.open)
                            for fn in sorted(filenames)]
            dd = Stack(descriptors)

            self.assertEqual(sorted(dd), sorted(tuples))

            self.assertEqual(dd.schema, dshape(schema))


text:
import { runInOp } from "../display/operations"
import { addToScrollPos } from "../display/scrolling"
import { regLineChange } from "../display/view_tracking"
import { heightAtLine, lineIsHidden } from "../line/spans"
import { lineNo, updateLineHeight } from "../line/utils_line"
import { widgetHeight } from "../measurement/widgets"
import { changeLine } from "./changes"
import { eventMixin } from "../util/event"

// Line widgets are block elements displayed above or below a line.

export function LineWidget(doc, node, options) {
  if (options) for (let opt in options) if (options.hasOwnProperty(opt))
    this[opt] = options[opt]
  this.doc = doc
  this.node = node
}
eventMixin(LineWidget)

function adjustScrollWhenAboveVisible(cm, line, diff) {
  if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
    addToScrollPos(cm, null, diff)
}

LineWidget.prototype.clear = function() {
  let cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line)
  if (no == null || !ws) return
  for (let i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1)
  if (!ws.length) line.widgets = null
  let height = widgetHeight(this)
  updateLineHeight(line, Math.max(0, line.height - height))
  if (cm) runInOp(cm, () => {
    adjustScrollWhenAboveVisible(cm, line, -height)
    regLineChange(cm, no, "widget")
  })
}
LineWidget.prototype.changed = function() {
  let oldH = this.height, cm = this.doc.cm, line = this.line
  this.height = null
  let diff = widgetHeight(this) - oldH
  if (!diff) return
  updateLineHeight(line, line.height + diff)
  if (cm) runInOp(cm, () => {
    cm.curOp.forceUpdate = true
    adjustScrollWhenAboveVisible(cm, line, diff)
  })
}

export function addLineWidget(doc, handle, node, options) {
  let widget = new LineWidget(doc, node, options)
  let cm = doc.cm
  if (cm && widget.noHScroll) cm.display.alignWidgets = true
  changeLine(doc, handle, "widget", line => {
    let widgets = line.widgets || (line.widgets = [])
    if (widget.insertAt == null) widgets.push(widget)
    else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget)
    widget.line = line
    if (cm && !lineIsHidden(doc, line)) {
      let aboveVisible = heightAtLine(line) < doc.scrollTop
      updateLineHeight(line, line.height + widgetHeight(widget))
      if (aboveVisible) addToScrollPos(cm, null, widget.height)
      cm.curOp.forceUpdate = true
    }
    return true
  })
  return widget
}


text:
module SyoboiCalendar
  module Responses
    class ListChannelsResponse < BaseResponse
      private

      # @note Override
      def resource_class
        ::SyoboiCalendar::Resources::ChannelResource
      end

      # @note Override
      def response_key
        "ChLookupResponse"
      end

      # @note Override
      def source_or_sources
        body[response_key]["ChItems"]["ChItem"]
      end
    end
  end
end


text:
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.components.subresource_filter;

import android.content.Context;
import android.content.res.Resources;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ClickableSpan;

import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;

import org.chromium.base.ThreadUtils;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.ui.base.WindowAndroid;
import org.chromium.ui.modaldialog.DialogDismissalCause;
import org.chromium.ui.modaldialog.ModalDialogManager;
import org.chromium.ui.modaldialog.ModalDialogManager.ModalDialogType;
import org.chromium.ui.modaldialog.ModalDialogProperties;
import org.chromium.ui.modaldialog.ModalDialogProperties.ButtonType;
import org.chromium.ui.modelutil.PropertyModel;
import org.chromium.ui.text.NoUnderlineClickableSpan;

/**
 * Java part of AdsBlockedDialog pair providing communication between native ads blocked
 * delegate code and Java ads blocked dialog UI components.
 */
public class AdsBlockedDialog implements ModalDialogProperties.Controller {
    private long mNativeDialog;
    private final Context mContext;
    private final ModalDialogManager mModalDialogManager;
    private PropertyModel mDialogModel;
    private ClickableSpan mClickableSpan;
    private Handler mDialogHandler;

    @CalledByNative
    static AdsBlockedDialog create(long nativeDialog, @NonNull WindowAndroid windowAndroid) {
        return new AdsBlockedDialog(nativeDialog, windowAndroid);
    }

    AdsBlockedDialog(long nativeDialog, @NonNull WindowAndroid windowAndroid) {
        mNativeDialog = nativeDialog;
        mContext = windowAndroid.getContext().get();
        mModalDialogManager = windowAndroid.getModalDialogManager();
        mDialogHandler = new Handler(ThreadUtils.getUiThreadLooper());
    }

    /**
     * Internal constructor for {@link AdsBlockedDialog}. Used by tests to inject
     * parameters. External code should use AdsBlockedDialog#create.
     *
     * @param nativeDialog The pointer to the dialog instance created by native code.
     * @param context The context for accessing resources.
     * @param modalDialogManager The ModalDialogManager to display the dialog.
     * @param dialogHandler The {@link Handler} used to post the call to show the dialog.
     */
    @VisibleForTesting
    AdsBlockedDialog(long nativeDialog, @NonNull Context context,
            @NonNull ModalDialogManager modalDialogManager, Handler dialogHandler) {
        mNativeDialog = nativeDialog;
        mContext = context;
        mModalDialogManager = modalDialogManager;
        mDialogHandler = dialogHandler;
    }

    @VisibleForTesting
    PropertyModel getDialogModelForTesting() {
        return mDialogModel;
    }

    @VisibleForTesting
    ClickableSpan getMessageClickableSpanForTesting() {
        return mClickableSpan;
    }

    @CalledByNative
    void show(boolean shouldPostDialog) {
        Resources resources = mContext.getResources();
        mClickableSpan = new NoUnderlineClickableSpan(
                mContext, (view) -> AdsBlockedDialogJni.get().onLearnMoreClicked(mNativeDialog));
        mDialogModel =
                new PropertyModel.Builder(ModalDialogProperties.ALL_KEYS)
                        .with(ModalDialogProperties.CONTROLLER, this)
                        .with(ModalDialogProperties.TITLE, resources,
                                R.string.blocked_ads_dialog_title)
                        .with(ModalDialogProperties.MESSAGE_PARAGRAPH_1, getFormattedMessageText())
                        .with(ModalDialogProperties.POSITIVE_BUTTON_TEXT, resources,
                                R.string.blocked_ads_dialog_always_allow)
                        .with(ModalDialogProperties.NEGATIVE_BUTTON_TEXT, resources,
                                R.string.cancel)
                        .with(ModalDialogProperties.CANCEL_ON_TOUCH_OUTSIDE, true)
                        .with(ModalDialogProperties.FOCUS_DIALOG, true)
                        .build();

        // shouldPostDialog determines if ModalDialogManager#showDialog should be invoked directly
        // or using Handler#post.
        // The dialog should be re-shown on the original tab on navigation back from the redirected
        // support link tab. This redirection is observed by
        // WebContentsObserver#OnWebContentsFocused and
        // TabModelSelectorTabModelObserver#didSelectTab. The sequence of invocation of these
        // methods is not consistent on phones and tablets. Using #post will delay the
        // #showDialog request reliably to after both tab events are handled on the UI thread,
        // guaranteeing that the dialog will be re-shown as expected. See crbug.com/1261967 for
        // details.
        // TODO (crbug.com/1272049): Investigate tab event observer ordering and tab modal
        // suspension logic as a follow up.
        if (shouldPostDialog) {
            mDialogHandler.post(
                    () -> mModalDialogManager.showDialog(mDialogModel, ModalDialogType.TAB));
        } else {
            mModalDialogManager.showDialog(mDialogModel, ModalDialogType.TAB);
        }
    }

    @CalledByNative
    void dismiss() {
        mModalDialogManager.dismissDialog(mDialogModel, DialogDismissalCause.DISMISSED_BY_NATIVE);
    }

    // Returns link-formatted message text for the ads blocked dialog.
    @VisibleForTesting
    CharSequence getFormattedMessageText() {
        Resources resources = mContext.getResources();
        String messageText = resources.getString(R.string.blocked_ads_dialog_message);
        String learnMoreLinkText = resources.getString(R.string.blocked_ads_dialog_learn_more);
        final SpannableString formattedLinkText = new SpannableString(learnMoreLinkText);
        formattedLinkText.setSpan(
                mClickableSpan, 0, learnMoreLinkText.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        return TextUtils.expandTemplate(messageText, formattedLinkText);
    }

    // ModalDialogProperties.Controller implementation.
    @Override
    public void onClick(PropertyModel model, @ButtonType int buttonType) {
        assert mNativeDialog != 0;
        if (buttonType == ButtonType.POSITIVE) {
            AdsBlockedDialogJni.get().onAllowAdsClicked(mNativeDialog);
        }
        mModalDialogManager.dismissDialog(model,
                buttonType == ButtonType.POSITIVE ? DialogDismissalCause.POSITIVE_BUTTON_CLICKED
                                                  : DialogDismissalCause.NEGATIVE_BUTTON_CLICKED);
    }

    @Override
    public void onDismiss(PropertyModel model, @DialogDismissalCause int dismissalCause) {
        mDialogHandler.removeCallbacksAndMessages(null);
        AdsBlockedDialogJni.get().onDismissed(mNativeDialog);
        mNativeDialog = 0;
    }

    @NativeMethods
    interface Natives {
        void onAllowAdsClicked(long nativeAdsBlockedDialog);
        void onLearnMoreClicked(long nativeAdsBlockedDialog);
        void onDismissed(long nativeAdsBlockedDialog);
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
<title>ColumnPrefixFilter xref</title>
<link type="text/css" rel="stylesheet" href="../../../../../stylesheet.css" />

View Javadoc

1
20
21  package org.apache.hadoop.hbase.filter;
22
23  import org.apache.hadoop.hbase.KeyValue;
24  import org.apache.hadoop.hbase.util.Bytes;
25
26  import java.io.DataOutput;
27  import java.io.IOException;
28  import java.io.DataInput;
29  import java.util.ArrayList;
30
31  import com.google.common.base.Preconditions;
32
33  /**
34   * This filter is used for selecting only those keys with columns that matches
35   * a particular prefix. For example, if prefix is 'an', it will pass keys with
36   * columns like 'and', 'anti' but not keys with columns like 'ball', 'act'.
37   */
38  public class ColumnPrefixFilter extends FilterBase {
39    protected byte [] prefix = null;
40
41    public ColumnPrefixFilter() {
42      super();
43    }
44
45    public ColumnPrefixFilter(final byte [] prefix) {
46      this.prefix = prefix;
47    }
48
49    public byte[] getPrefix() {
50      return prefix;
51    }
52
53    @Override
54    public ReturnCode filterKeyValue(KeyValue kv) {
55      if (this.prefix == null || kv.getBuffer() == null) {
56        return ReturnCode.INCLUDE;
57      } else {
58        return filterColumn(kv.getBuffer(), kv.getQualifierOffset(), kv.getQualifierLength());
59      }
60    }
61
62    public ReturnCode filterColumn(byte[] buffer, int qualifierOffset, int qualifierLength) {
63      if (qualifierLength < prefix.length) {
64        int cmp = Bytes.compareTo(buffer, qualifierOffset, qualifierLength, this.prefix, 0,
65            qualifierLength);
66        if (cmp <= 0) {
67          return ReturnCode.SEEK_NEXT_USING_HINT;
68        } else {
69          return ReturnCode.NEXT_ROW;
70        }
71      } else {
72        int cmp = Bytes.compareTo(buffer, qualifierOffset, this.prefix.length, this.prefix, 0,
73            this.prefix.length);
74        if (cmp < 0) {
75          return ReturnCode.SEEK_NEXT_USING_HINT;
76        } else if (cmp > 0) {
77          return ReturnCode.NEXT_ROW;
78        } else {
79          return ReturnCode.INCLUDE;
80        }
81      }
82    }
83
84    public static Filter createFilterFromArguments(ArrayList<byte []> filterArguments) {
85      Preconditions.checkArgument(filterArguments.size() == 1,
86                                  "Expected 1 but got: %s", filterArguments.size());
87      byte [] columnPrefix = ParseFilter.removeQuotesFromByteArray(filterArguments.get(0));
88      return new ColumnPrefixFilter(columnPrefix);
89    }
90
91    public void write(DataOutput out) throws IOException {
92      Bytes.writeByteArray(out, this.prefix);
93    }
94
95    public void readFields(DataInput in) throws IOException {
96      this.prefix = Bytes.readByteArray(in);
97    }
98
99    public KeyValue getNextKeyHint(KeyValue kv) {
100     return KeyValue.createFirstOnRow(
101         kv.getBuffer(), kv.getRowOffset(), kv.getRowLength(), kv.getBuffer(),
102         kv.getFamilyOffset(), kv.getFamilyLength(), prefix, 0, prefix.length);
103   }
104
105   @Override
106   public String toString() {
107     return this.getClass().getSimpleName() + " " + Bytes.toStringBinary(this.prefix);
108   }
109 }

This page was automatically generated by Maven


text:
package conrad.weiser.robinhood.api.endpoint.account.data;

import java.net.URL;

import conrad.weiser.robinhood.api.endpoint.account.data.enums.InvestmentExperience;
import conrad.weiser.robinhood.api.endpoint.account.data.enums.InvestmentObjective;
import conrad.weiser.robinhood.api.endpoint.account.data.enums.LiquidityNeeds;
import conrad.weiser.robinhood.api.endpoint.account.data.enums.RiskTolerance;
import conrad.weiser.robinhood.api.endpoint.account.data.enums.SourceOfFunds;
import conrad.weiser.robinhood.api.endpoint.account.data.enums.TimeHorizon;

public class AccountHolderInvestmentElement {

	private String annual_income;
	private String investment_experience;
	private String investment_objective;
	private String liquid_net_worth;
	private String liquidity_needs;
	private String risk_tolerance;
	private String source_of_funds;
	private boolean suitability_verified;
	private String tax_bracket;
	private String time_horizon;
	private String total_net_worth;

	//TODO: Updated_at
	private URL user;

	/**
	 * @return the annual_income
	 */
	public String getAnnualIncome() {
		return annual_income;
	}

	/**
	 * @return the investment_experience as an enum value.
	 */
	public InvestmentExperience getInvestmentExperience() {

		switch(this.investment_experience) {

		case "extensive_investment_exp": return InvestmentExperience.EXTENSIVE_INVESTMENT_EXPERIENCE;
		case "good_investment_exp": return InvestmentExperience.GOOD_INVESTMENT_EXPERIENCE;
		case "limited_investment_exp": return InvestmentExperience.LIMITED_INVESTMENT_EXPERIENCE;
		case "no_investment_exp": return InvestmentExperience.LIMITED_INVESTMENT_EXPERIENCE;
		default: return InvestmentExperience.ERROR;

		}

	}

	/**
	 * @return the investment_objective as an enum value
	 */
	public InvestmentObjective getInvestmentObjective() {

		switch(this.investment_objective) {

		case "cap_preserve_invest_obj": return InvestmentObjective.CAPITAL_PRESERVE_INVESTMENT_OBJECTIVE;
		case "income_invest_obj": return InvestmentObjective.INCOME_INVESTMENT_OBJECTIVE;
		case "growth_invest_obj": return InvestmentObjective.GROWTH_INVESTMENT_OBJECTIVE;
		case "speculation_invest_obj": return InvestmentObjective.SPECULATION_INVESTMENT_OBJECTIVE;
		case "other_invest_obj": return InvestmentObjective.OTHER_INVESTMENT_OBJECTIVE;
		default: return InvestmentObjective.ERROR;

		}
	}

	/**
	 * @return the liquid_net_worth
	 */
	public String getLiquidNetWorth() {
		return liquid_net_worth;
	}

	/**
	 * @return the liquidity_needs as an enum value
	 */
	public LiquidityNeeds getLiquidityNeeds() {

		switch(this.liquidity_needs) {

		case "not_important_liq_need": return LiquidityNeeds.NOT_IMPORTANT_LIQUIDITY_NEED;
		case "somewhat_important_liq_need": return LiquidityNeeds.SOMEWHAT_IMPORTANT_LIQUIDITY_NEED;
		case "very_important_liq_need": return LiquidityNeeds.VERY_IMPORTANT_LIQUIDITY_NEED;
		default: return LiquidityNeeds.ERROR;

		}

	}

	/**
	 * @return the risk_tolerance
	 */
	public RiskTolerance getRiskTolerance() {

		switch(this.risk_tolerance) {

		case "low_risk_tolerance": return RiskTolerance.LOW_RISK_TOLERANCE;
		case "med_risk_tolerance": return RiskTolerance.MED_RISK_TOLERANCE;
		case "high_risk_tolerance": return RiskTolerance.HIGH_RISK_TOLERANCE;
		default: return RiskTolerance.ERROR;

		}
	}

	/**
	 * @return the source_of_funds
	 */
	public SourceOfFunds getSourceOfFunds() {

		switch(this.source_of_funds) {

		case "savings_personal_income": return SourceOfFunds.SAVINGS_PERSONAL_INCOME;
		case "pension_retirement": return SourceOfFunds.PENSION_RETIREMENT;
		case "insurance_payout": return SourceOfFunds.INSURANCE_PAYOUT;
		case "inheritance": return SourceOfFunds.INHERITANCE;
		case "gift": return SourceOfFunds.GIFT;
		case "sale_business_or_property": return SourceOfFunds.SALE_BUSINESS_OR_PROPERTY;
		case "other": return SourceOfFunds.OTHER;
		default: return SourceOfFunds.ERROR;

		}
	}

	/**
	 * @return the suitability_verified
	 */
	public boolean isSuitabilityVerified() {
		return suitability_verified;
	}

	/**
	 * @return the tax_bracket
	 */
	public String getTaxBracket() {
		return tax_bracket;
	}

	/**
	 * @return the time_horizon
	 */
	public TimeHorizon getTimeHorizon() {

		switch(this.time_horizon) {

		case "short_time_horizon": return TimeHorizon.SHORT_TIME_HORIZON;
		case "med_time_horizon": return TimeHorizon.MEDIUM_TIME_HORIZON;
		case "long_time_horizon": return TimeHorizon.LONG_TIME_HORIZON;
		default: return TimeHorizon.ERROR;

		}
	}

	/**
	 * @return the total_net_worth
	 */
	public String getTotalNetWorth() {
		return total_net_worth;
	}

	/**
	 * @return the user
	 */
	public URL getUser() {
		return user;
	}

}


text:
var rsa = require('../');
var fs = require('fs');
var pubkey = fs.readFileSync(process.argv[2], 'utf8');

var enc = rsa.encrypt(pubkey, { encoding: 'base64' });
process.stdin.pipe(enc).pipe(process.stdout);


text:
package com.blog.library;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
/*
 * This class is for providing base web driver instance
 */
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

public class BaseWebDriver {
	private static WebDriver driver = null;
	private static final String drivers_path="src/main/resources/Drivers/";

	/*
	 * This method returns driver object
	 */
	public static WebDriver getDriver(){
		String os=System.getProperty("os.name");
		if(os.startsWith("Mac"))
			System.setProperty("webdriver.chrome.driver", drivers_path+"chromedriver");
		if(os.startsWith("Windows"))
			System.setProperty("webdriver.chrome.driver", drivers_path+"chromedriver.exe");
		ChromeOptions options = new ChromeOptions();
		options.addArguments("--disable-notifications");
		driver= new ChromeDriver(options);
	driver.manage().window().maximize();
	Utils.driver=driver;
	Utils.js=(JavascriptExecutor) driver;
	//driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	return driver;
	}

}


text:
layout: post
title: "A Cookiecutter template for Flask-based Web Applications"
published: true
---

Recently, I started a github project
[ryanolson/cookiecutter-webapp](https://github.com/ryanolson/cookiecutter-webapp)
as a means to jumpstart the process of starting a new web application.  While there
remains a lot todo (and to document), it seems like a good time to open it up and
hopefully get some useful feedback.

## Features

The following is a list of core technologies used:

- [Vagrant](http://vagrantup.com) to bring up a local development server
- [Ansible](http://ansible.com) for provisioning
- [Flask](https://github.com/mitsuhiko/flask) WSGI application
- [Nginx](http://nginx.com) configured reverse-proxy with [h5bp/server-configs-nginx](https://github.com/h5bp/server-configs-nginx) best practices
- [PostgreSQL](http://www.postgresql.org) running on the provisioned VM
- [Grunt](http://gruntjs.com) and [Bower](http://bower.io) to manage web assets
- [Pragmatic Stateless RESTful API](http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api)
  using a combination of [Flask-Classy](https://github.com/apiguy/flask-classy) and
  [Flask-RESTful](https://github.com/twilio/flask-restful).
- Dynamic user interface based on [React](http://facebook.github.io/react/) and
  [Backbone.JS](http://backbonejs.org)
- [Flask-SQLAlchemy](https://github.com/mitsuhiko/flask-sqlalchemy) with basic User model
- Secure logins via [Flask-Security](https://github.com/mattupstate/flask-security),
  [Flask-WTForms](https://github.com/lepture/flask-wtf)
- Revocable JSON Web Tokens (JWT) for API authentication via [Flask-JWT](https://github.com/mattupstate/flask-jwt)
- Easy database migrations with [Flask-Migrate](https://github.com/miguelgrinberg/Flask-Migrate)
- [Twitter's Bootstrap 3](http://getbootstrap.com) and
  [Font Awesome 4](http://fortawesome.github.io/Font-Awesome/)
- [pytest](http://pytest.org/latest/),
  [WebTest](http://webtest.readthedocs.org/en/latest/), and
  [Factory-Boy](http://factoryboy.readthedocs.org/en/latest/) for testing
- A simple [Flask-Script](https://github.com/smurfix/flask-script) `manage.py` script.
- Useful [debug toolbar](https://github.com/mgood/flask-debugtoolbar)

## Getting Started

### Step 1: Customize Your Project

The [base project](https://github.com/ryanolson/cookiecutter-webapp) is a
[cookiecutter](https://github.com/audreyr/cookiecutter) template.  Therefore,
Step 1 is to create your customized project from the template using cookiecutter.

{% gist 7eb35dd67646dfe40afc install-cookiecutter.py %}

You will be asked some basic info about the project you wish to create:

- `app_name`: snake case name of the application
- `AppName`: CamelCase name of the application
- `project_name`: name of your applications, human form
- `license`
    * `MIT`
    * `GPLv3`
    * `GPLv2`
    * `Apache`
    * `ISC`
    * `Mozilla`
    * any other license - you will have to add the text to the LICENSE file
- `author`
- `email`
- `company`
- `copyright`: usually takes the form of "Year, Company/Author" (@ will be prepended)
- `app_repo`: git repository for storing your code
- `app_url`: the url for the hosted project
- `vagrant_ipv4`: the host-only IP address for the vagrant-managed virtual
   machine that will be created and provisioned.

That's it!  Cookiecutter will have generated your customized webapp project folder.

### Step 2: Fire it up

In this step, you will be creating and provisioning a virtual machine to
run your web app. You will need [Vagrant](http://vagrantup.com),
[Ansible](http://ansible.com), and
[VirtualBox](https://www.virtualbox.org/wiki/Downloads) installed on your machine.

To launch your VM, simply type `vagrant up` from the top-level directory of your
created project.

After Vagrant and Ansible do their work, direct your browser to
<https://192.168.100.10> or whatever IP address you specifed for `vagrant_ipv4`.

### Step 3: Develop your web app

Read the README.md file created in your project directory for more details on development, testing and deployment.

## More Info

Over the next few weeks, I'll add articles discussing:

- Vagrant / Ansible provisioning
- A Pragmatic RESTful API using Flask-Classy, Flask-RESTful and Flask-Restless
- Backbone.js + Conditional API - handling 304s
- Backbone.js + JWT - handling expired tokens and reissuing requests
- Flask-JWT + Revokeable tokens


text:
![](art/open_camera_result.jpg)

## Custom Camera Processing

![](art/custom_camera_processing_result.jpg)


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('plugins', '0005_auto_20160712_1438'),
    ]

    operations = [
        migrations.AlterField(
            model_name='boolparameter',
            name='plugin_param',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='bool_inst', to='plugins.PluginParameter'),
        ),
        migrations.AlterField(
            model_name='floatparameter',
            name='plugin_param',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='float_inst', to='plugins.PluginParameter'),
        ),
        migrations.AlterField(
            model_name='intparameter',
            name='plugin_param',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='int_inst', to='plugins.PluginParameter'),
        ),
        migrations.AlterField(
            model_name='stringparameter',
            name='plugin_param',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='string_inst', to='plugins.PluginParameter'),
        ),
    ]


text:
#ifndef __c2_Quadrotor_h__
#define __c2_Quadrotor_h__

/* Include files */
#include "sfc_sf.h"
#include "sfc_mex.h"
#include "rtwtypes.h"

/* Type Definitions */
typedef struct {
  const char * context;
  const char * name;
  const char * dominantType;
  const char * resolved;
  uint32_T fileTimeLo;
  uint32_T fileTimeHi;
  uint32_T mFileTimeLo;
  uint32_T mFileTimeHi;
} c2_ResolvedFunctionInfo;

typedef struct {
  int32_T c2_sfEvent;
  boolean_T c2_isStable;
  boolean_T c2_doneDoubleBufferReInit;
  uint8_T c2_is_active_c2_Quadrotor;
  SimStruct *S;
  ChartInfoStruct chartInfo;
  uint32_T chartNumber;
  uint32_T instanceNumber;
  real_T c2_Pp;
  boolean_T c2_Pp_not_empty;
  real_T c2_Q;
  boolean_T c2_Q_not_empty;
  real_T c2_R;
  boolean_T c2_R_not_empty;
  real_T c2_xp;
  boolean_T c2_xp_not_empty;
  real_T c2_A1;
  boolean_T c2_A1_not_empty;
  real_T c2_H;
  boolean_T c2_H_not_empty;
  real_T c2_I;
  boolean_T c2_I_not_empty;
  real_T c2_xp_dot;
  boolean_T c2_xp_dot_not_empty;
} SFc2_QuadrotorInstanceStruct;

/* Named Constants */

/* Variable Declarations */

/* Variable Definitions */

/* Function Declarations */
extern const mxArray *sf_c2_Quadrotor_get_eml_resolved_functions_info(void);

/* Function Definitions */
extern void sf_c2_Quadrotor_get_check_sum(mxArray *plhs[]);
extern void c2_Quadrotor_method_dispatcher(SimStruct *S, int_T method, void
  *data);

#endif


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

namespace LD37.GameObjects
{
    abstract class ChampionBehavior : Behavior
    {
        public Champion Champion => GameObject as Champion;
    }
}