text:
# coding: utf-8

####################################################
# Script that either:
# a) generate a metadata.csv based on config file and input gps infoframefiles, or
# b) update a set of images based on the input metadata (.csv) file, using exiftool
#
# Last modified: 07.10.2016
# Author: M.Pittore, M. Haas
# Contact: pittore@gfz-potsdam.de
#
####################################################

import argparse
import os
import sys
import csv
from geographiclib.geodesic import Geodesic
from scipy.interpolate import UnivariateSpline
import glob
import pandas as pd
import re
import datetime

def parse_args(argv):
    try:
        #command line functionality
        parser = argparse.ArgumentParser()
        parser.add_argument('-m','--mode',type=str,help="""
        operating mode:
        'gen-meta' only generates the metadata files;
        'update-meta' accepts a metadata file and updates images´ metadata;""",required=True)
        parser.add_argument('-d','--deltafile',type=str,help="""
        Optional camera delta file usually created by camDelta.py in directory
        containing the original pgr files, if not provided no deviation between
        camera-car-heading is assumed""",required=False)
        parser.add_argument('-f','--metafile',type=str,help="""
        metadata file to be processed to update images´ metadata.
        (required if mode='update-meta')""",required=False)
        parser.add_argument('-c','--configfile',type=str,help="""
        Name of the config file containing information about the survey,
        see config.ini.
        (required if mode='gen-meta')""",required=False)
        parser.add_argument('-i','--dir_gps',type=str,help="""
        directory where the gps_infoframe files are stored.
        (required if mode='gen-meta')""",required=False)
        parser.add_argument('-o','--out_dir',type=str,help="""
        directory where the metadata will be written to.
        (required if mode='gen-meta')""",required=False)
        parser.add_argument('-g','--dir_img',type=str,help="""
        directory where the extracted frames are stored (.jpg).
        (required if mode='update-meta')""",required=False)
        args = parser.parse_args(argv)
        return args
    except:
        print 'could not parse arguments.'
        return

def get_config(in_config):
    #gather config content
    #todo: sub in_config with args.config
    try:
        config={}
        with open(in_config,'rb') as f:
            reader = csv.reader(f,delimiter=';',skipinitialspace=True)
            for row in reader:
                config[row[1]]=[row[2]]
    except:
        print 'Could not read config: {}'.format(in_config)
    return config

def get_gpsinfoframefiles(in_dir):
    #get all frame info files in the specified folder
    try:
        gpsfiles = [f for f in glob.glob(in_dir+'/*.csv')]
        gpsfiles.sort()
        nr_gpsfiles = len(gpsfiles)
        1/(nr_gpsfiles > 0)
    except:
        print 'Could not find any gps (.csv) files in: {}'.format(in_dir)
        raise Exception
    return gpsfiles

def get_imgfiles(in_dir):
    #get all extracted image files in the specified folder
    try:
        imgfiles = [f for f in glob.glob(in_dir_img+'/*.jpg')]
        imgfiles.sort()
        nr_imgfiles = len(imgfiles)
        1/(nr_imgfiles > 0)
    except:
        print 'Could not find any jpg files in: {}'.format(in_dir_img)
        raise Exception
    return imgfiles

def get_deltainfo(in_delta,unique_streams=[]):
    #Gather delta.csv content
    delta = {}
    if unique_streams:
        for key in unique_streams:
            delta[key] = 0.
    try:
        with open(in_delta,'rb') as f:
            reader = csv.reader(f,delimiter=',')
            next(reader,None)
            for row in reader:
                delta[row[0]] = float(row[1])
        print 'Using {} as camera-car heading delta...'.format(in_delta)
    except:
        print 'Warning: Provided no delta.csv file, as can be created by createCamDelta.py.\nAssuming no deviation between car and camera heading.'

    #if unique streams have been provided, check consistency
    if unique_streams:
        if len(delta.keys())!=len(unique_streams):
            print 'Found a delta.csv file in {}. But its length does not correspond to the number of streams found in the directory.'.format(in_delta)
            raise Exception

    return delta

def get_seqname(filename):
    m = re.search('_[0-9]+_[0-9]+.csv$',filename)
    seq_name = filename[:-len(m.group())].split(os.sep)[-1]
    return seq_name

def unique_streams_fromimages(imgfiles):
    #determine unique streams from the set of image files
    #the filenames always terminate with a 6 digit number _******.jpg
    try:
        unique_streams = [s[:-11].split(os.sep)[-1] for s in imgfiles]
        unique_streams = set(unique_streams)
    except:
        print 'Could not determine unique streams'
        raise Exception
    return unique_streams

def unique_streams_fromgpsfiles(gpsfiles):
    #determine unique streams from the set of image files
    #the filenames always terminate with a 6 digit number _******.jpg
    try:
        streams=[get_seqname(s) for s in gpsfiles]
        unique_streams = set(streams)
    except:
        print 'Could not determine unique streams'
        raise Exception
    return unique_streams

#############################
# interpolate lat lon, altitude and time using the defined GPS epoch
# using a degree 3 spline
#############################

def interpolate_coords(df):
    #get approximate time using first gps time available and from there on camera clock
    #camera first cycle sec
    cam_t0 = float(df['TSCycleSeconds'][0])
    #indices of all non zero gps times
    idx_non_zero_gps = [i for i,t in enumerate(df['bValidGPS']) if t]
    cycle_sec=[int(cs) for cs in df['TSCycleSeconds']]
    #since these are cycles with 128 seconds convert to monoton sequence
    cam_sec = []
    init=0
    for cs in cycle_sec:
        if init==0:
            init = 1
            old = cs
            cam_sec.append(0)
        dt = cs-old
        if dt < 0:
            dt = dt+128
        old = cs
        cam_sec.append(cam_sec[-1]+dt)
    #remove first element added for calculation
    cam_sec=cam_sec[1:]

    #determine fractions of a second (later converted to microseconds) via cycle count of camera (8000 Hz)
    cam_cycles = [float(c)/8000.0 for c in df['TSCycleCount']]
    cam_time = [sum(x) for x in zip(cam_sec, cam_cycles)]
    delta_t = [t1-t2 for t1,t2 in zip(cam_time[1:],cam_time[:-1])]
    #interpolate gps using cam_time
    #get first index of image sequences with same gps time
    #in order to avoid multiple datapoints with same info
    idx_interp = []
    gps_time = []
    for i,t in enumerate(df['TSSeconds']):
        if t not in gps_time and df['bValidGPS'][i]:
            gps_time.append(t)
            idx_interp.append(i)
    #time used for polynomial fit
    itime = [t for i,t in enumerate(cam_time) if i in idx_interp]
    #gps data used for polynomial fit
    gps_lat = [float(s) for i,s in enumerate(df['GGALatitude']) if i in idx_interp]
    gps_lon = [float(s) for i,s in enumerate(df['GGALongitude']) if i in idx_interp]
    gps_alt = [float(s) for i,s in enumerate(df['GGAAltitude']) if i in idx_interp]
    gps_time2= [float(s) for i,s in enumerate(gps_time)]

    #polynomyial
    s_lat = UnivariateSpline(x=itime, y=gps_lat,s=0,k=3)
    s_lon = UnivariateSpline(x=itime, y=gps_lon,s=0,k=3)
    s_alt = UnivariateSpline(x=itime, y=gps_alt,s=0,k=3)
    s_time = UnivariateSpline(x=itime, y=gps_time2,s=0,k=3)

    #get interpolated values
    lat = [float(s_lat(t)) for t in cam_time]
    lon = [float(s_lon(t)) for t in cam_time]
    altitude = [float(s_alt(t)) for t in cam_time]
    intime = [float(s_time(t)) for t in cam_time]

    #calculate gps speed for coordinate point pairs
    pairs = list(zip(lat,lon))
    geo = [Geodesic.WGS84.Inverse(p1[0],p1[1],p2[0],p2[1]) for p1,p2 in zip(pairs[:-1],pairs[1:])]
    vel = [g['s12']/float(dt)*3.6 for g,dt in zip(geo,delta_t)]

    #storing velocities assuming first image was taken at same speed as second
    abspeed = [vel[0]] + vel
    #azimuth for coordinate point pairs
    azi = [g['azi1'] for g in geo]
    #storing azimuth assuming last image has same azimuth as second last
    azimuth = azi + [azi[-1]]
    #create utc time line starting with first gps time (unfortunately no delay info available, and only 1Hz)
    #first non zero gps time
    #timeformat = '%Y-%m-%d %H:%M:%S'
    #gps_t = df['TSSeconds'][idx_non_zero_gps]
    #utctimestamp = [datetime.datetime.utcfromtimestamp(t).strftime(timeformat) for t in gps_t]

    return lat, lon, altitude, abspeed, azimuth, intime

#############################
#attach metadata to jpg files according to metadata
#############################

def update_metadata(metadata,in_dir_img):
    fieldnames = list(metadata.keys())
    fieldnames.sort()
    #append the exiftool location (i.e. current folder) to the os.path
    os.environ['PATH'] += os.pathsep + os.getcwd()

    #iterate over images in the metadata dictionary
    for i in range(len(metadata['FileName'])):
        image_filename=metadata['FileName'][i]
        imgpath = os.path.join(in_dir_img,image_filename)
        if not os.path.isfile(imgpath):
            print 'file {} not found.',format(imgpath)
        else:
            #init command
            #exiftool base command (check OS version: exiftool.exe is for Windows OS)
            cmd = 'exiftool.exe -config gfz.ns -overwrite_original'
            for key in fieldnames:
                cmd = cmd + ' -{}="{}"'.format(key,metadata[key][i])
            cmd = cmd + ' {}'.format(imgpath)
            os.system(cmd)

#############################
# generate asingle csv containing metadata + filename
############################ #

def generate_metadata(df,config,in_dir_img):
    #create a dictionary that keeps all metadata for the sequence
    meta = {}
    #initialize all keys defined in config
    for key in config.keys():
        meta[key]=[]
    #initialize additional keys
    meta['FileName']=[]
    meta['Repository']=[]
    meta['FrameId']=[]
    meta['PoseHeadingDegrees']=[]
    meta['FirstPhotoDate']=[]
    meta['GPSAltitude']=[]
    meta['GPSAzimuth']=[]
    meta['GPSSpeed']=[]
    meta['GPSSpeedRef']=[]
    meta['GPSLatitude']=[]
    meta['GPSLongitude']=[]

    #iterate over images in the frame-info file
    for i, image in df.iterrows():
        #check that the image exists (has been extracted)
        image_filename = image['seqName']+'_{:06d}.jpg'.format(image['frameID'])
        imgpath = os.path.join(in_dir_img,image_filename)
        if not os.path.isfile(imgpath):
            print 'file {} not found.',format(imgpath)
        else:
            #append base meta provided by config file
            for key in config.keys():
                meta[key].append(config[key][0])
            #append other values
            meta['FileName'].append(image_filename)
            meta['Repository'].append(in_dir_img)
            meta['FrameId'].append(image['frameID'])
            real_azimuth = image['iAzimuth']#+delta[stream_id]
            meta['PoseHeadingDegrees'].append(real_azimuth)
            meta['FirstPhotoDate'].append(image['UTCTimeStamp'])
            meta['GPSAltitude'].append(image['iAlt'])
            meta['GPSAzimuth'].append(image['iAzimuth'])
            meta['GPSSpeed'].append(image['iAbsVel'])
            meta['GPSSpeedRef'].append('km/h')
            meta['GPSLatitude'].append(image['iLat'])
            meta['GPSLongitude'].append(image['iLon'])

    return meta

#append meta2 keys to meta1
def append_metadata(meta1,meta2):
    meta1keys = meta1.keys()
    meta2keys = meta2.keys()
    #if empty init meta1
    if not meta1keys:
        for k in meta2keys:
            meta1[k] = []
    for k in meta2keys:
        for i,val in enumerate(meta2[k]):
            meta1[k].append(val)
    return meta1

def save_metadata(metadata,out_dir,filename='metadata.csv'):
    with open(os.path.join(out_dir,filename),'wb') as f:
        fieldnames = list(metadata.keys())
        fieldnames.sort()
        writer = csv.DictWriter(f,fieldnames=fieldnames)
        writer.writeheader()
        for i in range(len(metadata[fieldnames[0]])):
            row={}
            for key in fieldnames:
                row[key] = metadata[key][i]
            writer.writerow(row)

def load_metadata(in_meta):
    meta = {}
    with open(in_meta,'r') as f:
        metareader = csv.DictReader(f)
        fieldnames = metareader.fieldnames
        #init keys
        for key in fieldnames:
            meta[key] = []
            #populate keys
        try:
            for row in metareader:
                for key in fieldnames:
                    meta[key].append(row[key])
        except csv.Error as e:
            sys.exit('file {}, line {}: {}'.format(in_meta, metareader.line_num, e))
    return meta

def main(argv):

    # init folders - DEBUG ONLY - under LINUX
    in_dir_gps = '/home/max/Desktop/Documents/GFZ_sync/ACTIVITIES/RRVS/new_version/gps_tmp'
    in_dir_img = '/home/max/Desktop/Documents/GFZ_sync/ACTIVITIES/RRVS/new_version/test_images'
    out_dir = '/home/max/Desktop/Documents/GFZ_sync/ACTIVITIES/RRVS/new_version'
    in_config = '/home/max/Desktop/Documents/GFZ_sync/ACTIVITIES/RRVS/new_version/permanent-dev/config-rieti.ini'
    in_delta = ''

    opMode = 'update-meta'

    args = parse_args(argv)

    if args:
        opMode = args.mode
        in_dir_gps = args.dir_gps
        in_delta = args.deltafile
        in_config = args.configfile
        in_dir_img = args.dir_img
        out_dir = args.out_dir
        in_meta = args.metafile
    else:
        print 'use default parameters'

    if opMode=='gen-meta':

        print """generating metadata.
        Delta file:{}
        Config file: {}
        Input gps folder: {}
        Images folder: {}
        Output folder: {} """.format(in_delta,in_config,in_dir_gps,in_dir_img,out_dir)

        config = get_config(in_config)
        gpsfiles = get_gpsinfoframefiles(in_dir_gps)
        unique_streams = unique_streams_fromgpsfiles(gpsfiles)
        delta = get_deltainfo(in_delta,unique_streams)
        #read all gps info frames (in csv format) and generate a single csv file
        df_all = pd.DataFrame()
        meta_all = {}
        for s in gpsfiles:
            #extract sequence name from gpsframe-info files
            seq_name = get_seqname(s)
            print 'processing {} ...'.format(seq_name)
            #load sequence data
            df = pd.read_csv(s)
            #interpolate coordinates
            lat, lon, altitude, abspeed, azimuth, itime = interpolate_coords(df)
            #populate dataframe with interpolated data
            df['iLat'] = lat
            df['iLon'] = lon
            df['iAlt'] = altitude
            df['iAbsVel'] = abspeed
            df['iAzimuth'] = azimuth
            #add sequence name
            df['seqName'] = seq_name
            #add utc timestamp from internal clock (ieee1394)
            timeformat = '%Y-%m-%d %H:%M:%S'
            intime = [int(t) for t in itime]
            #gps_t = [t for i,t in df['TSSeconds'] where df['bValidGPS'][i]]
            utctimestamp = [datetime.datetime.utcfromtimestamp(t).strftime(timeformat) for t in intime]
            df['UTCTimeStamp'] = utctimestamp

            #generate metadata for the extracted images.
            seq_meta = generate_metadata(df,config,in_dir_img)
            save_metadata(seq_meta,out_dir,seq_name+'_metadata.csv')

            #append metadata to global one ?
            append_metadata(meta_all,seq_meta)

            #append dataframe to the global one
            if (not df_all.empty):
                df_all = df_all.append(df)
            else:
                df_all = df

        #save the global dataframe and global metadata as a csv files
        print 'saving global datasets and metadata...'
        df_all = df_all.set_index(['frameID'])
        df_all.to_csv(os.path.join(out_dir,'test_all.csv'))
        save_metadata(meta_all,out_dir,'meta_all.csv')

    elif opMode=='update-meta':

        print """updating images metadata.
        Input metadata: {}
        Images folder: {}""".format(in_meta,in_dir_img)

        seq_meta = load_metadata(in_meta)
        update_metadata(seq_meta,in_dir_img)

    else:
        print 'operation mode {} unknown.'.format(opMode)

    print 'processing completed. exit.'

if __name__ == "__main__":
    main(sys.argv[1:])


text:
.TransactionItem {
  clear: both;
  display: inline-block;
  width: 100%;
  padding-bottom: var(--spacing);
}

.TransactionItem .ProfilePhoto {
  float: left;
  width: 2.5rem;
  height: 2.5rem;
}
.TransactionItem-info {
  float: left;
  width: calc(100% - 86px - 1rem);
  padding-left: var(--spacing);
}

.TransactionItem-meta {
  font-weight: 14px;
}

.TransactionItem-created {
  clear: both;
  float: left;
  font-size: 0.9rem;
  width: 50%;
  color: gray;
}

.TransactionItem-status {
  float: right;
  font-size: 0.9rem;
  font-style: italic;
}

.TransactionItem-description {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  width: 80%;
  font-size: 1.25rem;
  float:left;
}

.TransactionItem-amount {
  font-size: 1.25rem;
  float: right;
  text-align: right;
  width: 15%;
}

redpajama_set_name: RedPajamaGithub


text:
package com.google.api.codegen.transformer.ruby;

import com.google.api.codegen.config.FieldConfig;
import com.google.api.codegen.transformer.ModelTypeNameConverter;
import com.google.api.codegen.util.NamePath;
import com.google.api.codegen.util.TypeName;
import com.google.api.codegen.util.TypeNameConverter;
import com.google.api.codegen.util.TypedValue;
import com.google.api.codegen.util.ruby.RubyTypeTable;
import com.google.api.tools.framework.model.EnumValue;
import com.google.api.tools.framework.model.ProtoElement;
import com.google.api.tools.framework.model.TypeRef;
import com.google.common.collect.ImmutableMap;
import com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Type;

public class RubyModelTypeNameConverter implements ModelTypeNameConverter {

  /** A map from primitive types to its default value. */
  private static final ImmutableMap<Type, String> PRIMITIVE_ZERO_VALUE =
      ImmutableMap.<Type, String>builder()
          .put(Type.TYPE_BOOL, "false")
          .put(Type.TYPE_DOUBLE, "0.0")
          .put(Type.TYPE_FLOAT, "0.0")
          .put(Type.TYPE_INT64, "0")
          .put(Type.TYPE_UINT64, "0")
          .put(Type.TYPE_SINT64, "0")
          .put(Type.TYPE_FIXED64, "0")
          .put(Type.TYPE_SFIXED64, "0")
          .put(Type.TYPE_INT32, "0")
          .put(Type.TYPE_UINT32, "0")
          .put(Type.TYPE_SINT32, "0")
          .put(Type.TYPE_FIXED32, "0")
          .put(Type.TYPE_SFIXED32, "0")
          .put(Type.TYPE_STRING, "\'\'")
          .put(Type.TYPE_BYTES, "\'\'")
          .build();

  /** A map from primitive type to its corresponding ruby types */
  private static final ImmutableMap<Type, String> PRIMITIVE_TYPE_MAP =
      ImmutableMap.<Type, String>builder()
          .put(Type.TYPE_BOOL, "true, false")
          .put(Type.TYPE_DOUBLE, "Float")
          .put(Type.TYPE_FLOAT, "Float")
          .put(Type.TYPE_INT64, "Integer")
          .put(Type.TYPE_UINT64, "Integer")
          .put(Type.TYPE_SINT64, "Integer")
          .put(Type.TYPE_FIXED64, "Integer")
          .put(Type.TYPE_SFIXED64, "Integer")
          .put(Type.TYPE_INT32, "Integer")
          .put(Type.TYPE_UINT32, "Integer")
          .put(Type.TYPE_SINT32, "Integer")
          .put(Type.TYPE_FIXED32, "Integer")
          .put(Type.TYPE_SFIXED32, "Integer")
          .put(Type.TYPE_STRING, "String")
          .put(Type.TYPE_BYTES, "String")
          .build();

  private TypeNameConverter typeNameConverter;

  public RubyModelTypeNameConverter(String implicitPackageName) {
    this.typeNameConverter = new RubyTypeTable(implicitPackageName);
  }

  @Override
  public TypeName getTypeNameInImplicitPackage(String shortName) {
    return typeNameConverter.getTypeNameInImplicitPackage(shortName);
  }

  @Override
  public TypeName getTypeName(TypeRef type) {
    if (type.isMap()) {
      return new TypeName("Hash");
    } else if (type.isRepeated()) {
      return new TypeName("Array");
    } else {
      return getTypeNameForElementType(type);
    }
  }

  /**
   * Returns the Ruby representation of a type. If the type is a primitive,
   * getTypeNameForElementType returns it in unboxed form.
   */
  @Override
  public TypeName getTypeNameForElementType(TypeRef type) {
    String primitiveTypeName = PRIMITIVE_TYPE_MAP.get(type.getKind());
    if (primitiveTypeName != null) {
      return new TypeName(primitiveTypeName);
    }
    switch (type.getKind()) {
      case TYPE_MESSAGE:
        return getTypeName(type.getMessageType());
      case TYPE_ENUM:
        return getTypeName(type.getEnumType());
      default:
        throw new IllegalArgumentException("unknown type kind: " + type.getKind());
    }
  }

  @Override
  public TypeName getTypeName(ProtoElement elem) {
    return typeNameConverter.getTypeName(
        NamePath.dotted(elem.getFullName()).withUpperPieces().toDoubleColoned());
  }

  /**
   * Returns the Ruby representation of a zero value for that type, to be used in code sample doc.
   */
  @Override
  public TypedValue getZeroValue(TypeRef type) {
    // Don't call getTypeName; we don't need to import these.
    if (type.isMap()) {
      return TypedValue.create(new TypeName("Hash"), "{}");
    }
    if (type.isRepeated()) {
      return TypedValue.create(new TypeName("Array"), "[]");
    }
    if (PRIMITIVE_ZERO_VALUE.containsKey(type.getKind())) {
      return TypedValue.create(getTypeName(type), PRIMITIVE_ZERO_VALUE.get(type.getKind()));
    }
    if (type.isMessage()) {
      return TypedValue.create(getTypeName(type), "%s.new");
    }
    if (type.isEnum()) {
      EnumValue enumValue = type.getEnumType().getValues().get(0);
      return TypedValue.create(getTypeName(type), "%s::" + enumValue.getSimpleName());
    }
    return TypedValue.create(new TypeName(""), "nil");
  }

  @Override
  public String renderPrimitiveValue(TypeRef type, String value) {
    Type primitiveType = type.getKind();
    if (!PRIMITIVE_TYPE_MAP.containsKey(primitiveType)) {
      throw new IllegalArgumentException(
          "Initial values are only supported for primitive types, got type "
              + type
              + ", with value "
              + value);
    }
    switch (primitiveType) {
      case TYPE_BOOL:
        return value.toLowerCase();
      case TYPE_STRING:
      case TYPE_BYTES:
        return "\"" + value + "\"";
      default:
        // Types that do not need to be modified (e.g. TYPE_INT32) are handled
        // here
        return value;
    }
  }

  @Override
  public TypeName getTypeNameForTypedResourceName(
      FieldConfig fieldConfig, String typedResourceShortName) {
    throw new UnsupportedOperationException(
        "getTypeNameForTypedResourceName not supported by Ruby");
  }

  @Override
  public TypeName getTypeNameForResourceNameElementType(
      FieldConfig fieldConfig, String typedResourceShortName) {
    throw new UnsupportedOperationException(
        "getTypeNameForResourceNameElementType not supported by Ruby");
  }

  @Override
  public TypedValue getEnumValue(TypeRef type, String value) {
    throw new UnsupportedOperationException("getEnumValue not supported by Ruby");
  }
}


text:
<?php

namespace MPK\App\Factory;

use MPK\App\Entity\Line;

/**
 * @author Łukasz Chruściel <lchrusciel@gmail.com>
 */
class LineFactory implements LineFactoryInterface
{

    public function createLineWithStops($argument1)
    {
        return $argument1;
    }

    /**
     * {@inheritdoc}
     */
    public function createLine(array $rawLine)
    {
        $line = new Line();

        $line->setId($rawLine['line_id']);
        $line->setLine($rawLine['line']);
        $line->setType($rawLine['type']);

        return $line;
    }
}


text:
package org.apache.flink.runtime.rest.messages;

import org.apache.flink.util.Preconditions;

import java.util.Collection;

/**
 * This class defines the path/query {@link MessageParameter}s that can be used for a request.
 */
public abstract class MessageParameters {

	/**
	 * Returns the collection of {@link MessagePathParameter} that the request supports. The collection should not be
	 * modifiable.
	 *
	 * @return collection of all supported message path parameters
	 */
	public abstract Collection<MessagePathParameter<?>> getPathParameters();

	/**
	 * Returns the collection of {@link MessageQueryParameter} that the request supports. The collection should not be
	 * modifiable.
	 *
	 * @return collection of all supported message query parameters
	 */
	public abstract Collection<MessageQueryParameter<?>> getQueryParameters();

	/**
	 * Returns whether all mandatory parameters have been resolved.
	 *
	 * @return true, if all mandatory parameters have been resolved, false otherwise
	 */
	public final boolean isResolved() {
		return getPathParameters().stream().filter(MessageParameter::isMandatory).allMatch(MessageParameter::isResolved)
			&& getQueryParameters().stream().filter(MessageParameter::isMandatory).allMatch(MessageParameter::isResolved);
	}

	/**
	 * Resolves the given URL (e.g "jobs/:jobid") using the given path/query parameters.
	 *
	 *
This method will fail with an {@link IllegalStateException} if any mandatory parameter was not resolved.
	 *
	 *
Unresolved optional parameters will be ignored.
	 *
	 * @param genericUrl URL to resolve
	 * @param parameters message parameters parameters
	 * @return resolved url, e.g "/jobs/1234?state=running"
	 * @throws IllegalStateException if any mandatory parameter was not resolved
	 */
	public static String resolveUrl(String genericUrl, MessageParameters parameters) {
		Preconditions.checkState(parameters.isResolved(), "Not all mandatory message parameters were resolved.");
		StringBuilder path = new StringBuilder(genericUrl);
		StringBuilder queryParameters = new StringBuilder();

		for (MessageParameter<?> pathParameter : parameters.getPathParameters()) {
			if (pathParameter.isResolved()) {
				int start = path.indexOf(':' + pathParameter.getKey());

				final String pathValue = Preconditions.checkNotNull(pathParameter.getValueAsString());

				// only replace path parameters if they are present
				if (start != -1) {
					path.replace(start, start + pathParameter.getKey().length() + 1, pathValue);
				}
			}
		}
		boolean isFirstQueryParameter = true;
		for (MessageQueryParameter<?> queryParameter : parameters.getQueryParameters()) {
			if (queryParameter.isResolved()) {
				if (isFirstQueryParameter) {
					queryParameters.append('?');
					isFirstQueryParameter = false;
				} else {
					queryParameters.append('&');
				}
				queryParameters.append(queryParameter.getKey());
				queryParameters.append('=');
				queryParameters.append(queryParameter.getValueAsString());
			}
		}
		path.append(queryParameters);

		return path.toString();
	}
}


text:
teenyjs.define( 'storyCardDispatcher', [ 'storyCardStore', 'googleAuthStore' ], function ( storyCardStore, googleAuthStore ) {

	return DeLorean.Flux.createDispatcher({

		signIn: function ( key ) {

			this.dispatch( 'signIn', key );

		},

		signOut: function () {

			this.dispatch( 'signOut' );

		},

		addCardToList: function ( card ) {

			this.dispatch( 'addCardToList', card );

		},

		cardSaved: function () {

			this.dispatch( 'cardSaved' );

		},

		getStores: function () {

		    return {

		      storyCardStore: storyCardStore,
		      googleAuthStore: googleAuthStore

		    }

		},

		moved: function () {

			this.dispatch( 'moved' );

		},

		removeCards: function () {

			this.dispatch( 'removeCards' );

		}

	});

});


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\SetForOrderModelCrud */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'id_order') ?>

    <?= $form->field($model, 'id_notebook') ?>

    <?= $form->field($model, 'amount') ?>

    <?= $form->field($model, 'cost') ?>

        <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
import { EventEmitter, forwardRef, QueryList, Input, Output, ContentChildren, HostBinding, AfterContentInit, OnDestroy, Optional, Inject, Component, ChangeDetectorRef, Directive, ChangeDetectionStrategy, ViewEncapsulation } from '@angular/core';
import { ControlValueAccessor, NgControl } from '@angular/forms';
import { Subject, Subscription } from 'rxjs';
import { DATA_LIST_TOKEN, DataList, DataListItem, DataListMode } from './types';
import { DataListItemDirective } from './data-list-item.directive';

@Directive({
  selector: 'vcl-data-list-header',
})
export class DataListHeaderDirective {
  @HostBinding('class.data-list-header')
  hostClasses = true;
}

@Directive({
  selector: 'vcl-data-list-footer',
})
export class DataListFooterDirective {
  @HostBinding('class.data-list-footer')
  hostClasses = true;
}

@Component({
  selector: 'vcl-data-list',
  templateUrl: './data-list.component.html',
  styleUrls: ['./data-list.component.scss'],
  encapsulation: ViewEncapsulation.None,
  exportAs: 'vclDataList',
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [
    {
      provide: DATA_LIST_TOKEN,
      useExisting: forwardRef(() => DataListComponent)
    }
  ]
})
export class DataListComponent implements DataList, AfterContentInit, OnDestroy, ControlValueAccessor {
  constructor(
    @Optional()
    public ngControl?: NgControl,
    ) {
    // Set valueAccessor instead of providing it to avoid circular dependency of NgControl
    if (this.ngControl) {
      this.ngControl.valueAccessor = this;
    }
  }

  stateChange = new Subject<void>();

  private _cvaDisabled = false;

  @HostBinding('class.data-list')
  _hostClasses = true;

  private _itemsChangeSub?: Subscription;
  private _itemsChangeEmitter: Subject<void> = new Subject();

  readonly itemsChange = this._itemsChangeEmitter.asObservable();

  @Input()
  selectionMode: DataListMode = 'single';

  @Input()
  value: any | any[];

  @Input()
  disabled = false;

  @Input()
  @HostBinding('class.divider')
  dividier = false;

  @Input()
  @HostBinding('class.no-border')
  noBorder = false;

  @Output()
  valueChange =  new EventEmitter<any | any[]>();

  @ContentChildren(DataListItemDirective)
  private _items?: QueryList<DataListItem>;

  get isDisabled() {
    return this._cvaDisabled || this.disabled;
  }

  isItemSelected(item: DataListItem): boolean {
    if (this.selectionMode === 'single') {
      return item.value === this.value;
    } else if (this.selectionMode === 'multiple') {
      return Array.isArray(this.value) && this.value.includes(item.value);
    } else {
      return false;
    }
  }

  selectItem(item: DataListItem): void {
    if (this.selectionMode === 'none') {
      return;
    } else if (this.selectionMode === 'single') {
      this.value = item.value;
    } else {
      const values = Array.isArray(this.value) ? this.value : [this.value];
      if (values.includes(item.value)) {
        this.value = values.filter(_value => _value !== item.value);
      } else {
        this.value = [...values, item.value];
      }
    }

    this.valueChange.emit(this.value);
    this.onTouched();
    this.onChange(this.value);
    this.stateChange.next();
  }

  onItemFocus(item: DataListItem) {

  }

  onItemBlur(item: DataListItem) {
    if (this._items.last === item) {
      this.onTouched();
    }
  }

  ngAfterContentInit() {
    this._itemsChangeSub = this._items.changes.subscribe(this._itemsChangeEmitter);
  }

  ngOnDestroy() {
    this._itemsChangeSub && this._itemsChangeSub.unsubscribe();
    this.stateChange.complete();
  }

  /**
   * things needed for ControlValueAccessor-Interface
   */
  onChange: (_: any) => void = () => {};
  onTouched: () => void = () => {};

  writeValue(value: any): void {
    this.value = value;
    this.valueChange.emit(value);
    this.stateChange.next();
  }
  registerOnChange(fn: any): void {
    this.onChange = fn;
  }
  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }
  setDisabledState?(isDisabled: boolean): void {
    this._cvaDisabled = isDisabled;
  }

}


text:
package com.amazonaws.services.elasticbeanstalk.model;

import com.amazonaws.AmazonServiceException;

/**
 * <p>
 * The caller does not have a subscription to Amazon S3.
 * </p>
 */
public class S3SubscriptionRequiredException extends AmazonServiceException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new S3SubscriptionRequiredException with the specified error
     * message.
     *
     * @param message Describes the error encountered.
     */
    public S3SubscriptionRequiredException(String message) {
        super(message);
    }

}


text:
var Vector2 = require('./Vector2');

/**
 * Takes the `x` and `y` coordinates and transforms them into the same space as
 * defined by the position, rotation and scale values.
 *
 * @function Phaser.Math.TransformXY
 * @since 3.0.0
 *
 * @param {number} x - The x coordinate to be transformed.
 * @param {number} y - The y coordinate to be transformed.
 * @param {number} positionX - Horizontal position of the transform point.
 * @param {number} positionY - Vertical position of the transform point.
 * @param {number} rotation - Rotation of the transform point, in radians.
 * @param {number} scaleX - Horizontal scale of the transform point.
 * @param {number} scaleY - Vertical scale of the transform point.
 * @param {(Phaser.Math.Vector2|Phaser.Geom.Point|object)} [output] - The output vector, point or object for the translated coordinates.
 *
 * @return {(Phaser.Math.Vector2|Phaser.Geom.Point|object)} The translated point.
 */
var TransformXY = function (x, y, positionX, positionY, rotation, scaleX, scaleY, output)
{
    if (output === undefined) { output = new Vector2(); }

    //  ITRS

    var sr = Math.sin(-rotation);
    var cr = Math.cos(-rotation);

    var a = cr * scaleX;
    var b = -sr * scaleX;
    var c = sr * scaleY;
    var d = cr * scaleY;

    //  Invert

    var n = a * d - b * c;

    var m0 = d / n;
    var m1 = -b / n;
    var m2 = -c / n;
    var m3 = a / n;
    var m4 = (c * positionY - d * positionX) / n;
    var m5 = -(a * positionY - b * positionX) / n;

    //  Transform

    output.x = x * m0 + y * m2 + m4;
    output.y = x * m1 + y * m3 + m5;

    return output;
};

module.exports = TransformXY;


text:
{-# LANGUAGE CPP #-}
module GHCJS.DOM.AudioNode (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
  module GHCJS.DOM.JSFFI.Generated.AudioNode
#else
#endif
  ) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.AudioNode
#else
#endif


text:
"""Abstract base classes for different types of simulators.

Simulator types include:

    SimulatesSamples: mimics the interface of quantum hardware.

    SimulatesAmplitudes: computes amplitudes of desired bitstrings in the
        final state of the simulation.

    SimulatesFinalState: allows access to the final state of the simulation.

    SimulatesIntermediateState: allows for access to the state of the simulation
        as the simulation iterates through the moments of a cirq.
"""

from typing import (
    Any,
    Dict,
    Iterator,
    List,
    Sequence,
    Tuple,
    Union,
    Optional,
    TYPE_CHECKING,
    Set,
    cast,
    Callable,
    TypeVar,
    Generic,
)

import abc
import collections

import numpy as np

from cirq import circuits, ops, protocols, study, value, work
from cirq._compat import deprecated

if TYPE_CHECKING:
    import cirq

TStepResult = TypeVar('TStepResult', bound='StepResult')
TSimulationTrialResult = TypeVar('TSimulationTrialResult', bound='SimulationTrialResult')
TSimulatorState = TypeVar('TSimulatorState')

class SimulatesSamples(work.Sampler, metaclass=abc.ABCMeta):
    """Simulator that mimics running on quantum hardware.

    Implementors of this interface should implement the _run method.
    """

    def run_sweep(
        self,
        program: 'cirq.Circuit',
        params: study.Sweepable,
        repetitions: int = 1,
    ) -> List[study.Result]:
        """Runs the supplied Circuit, mimicking quantum hardware.

        In contrast to run, this allows for sweeping over different parameter
        values.

        Args:
            program: The circuit to simulate.
            params: Parameters to run with the program.
            repetitions: The number of repetitions to simulate.

        Returns:
            Result list for this run; one for each possible parameter
            resolver.
        """
        if not program.has_measurements():
            raise ValueError("Circuit has no measurements to sample.")

        _verify_unique_measurement_keys(program)

        trial_results = []  # type: List[study.Result]
        for param_resolver in study.to_resolvers(params):
            measurements = {}
            if repetitions == 0:
                for _, op, _ in program.findall_operations_with_gate_type(ops.MeasurementGate):
                    measurements[protocols.measurement_key(op)] = np.empty([0, 1])
            else:
                measurements = self._run(
                    circuit=program, param_resolver=param_resolver, repetitions=repetitions
                )
            trial_results.append(
                study.Result.from_single_parameter_set(
                    params=param_resolver, measurements=measurements
                )
            )
        return trial_results

    @abc.abstractmethod
    def _run(
        self, circuit: circuits.Circuit, param_resolver: study.ParamResolver, repetitions: int
    ) -> Dict[str, np.ndarray]:
        """Run a simulation, mimicking quantum hardware.

        Args:
            circuit: The circuit to simulate.
            param_resolver: Parameters to run with the program.
            repetitions: Number of times to repeat the run. It is expected that
                this is validated greater than zero before calling this method.

        Returns:
            A dictionary from measurement gate key to measurement
            results. Measurement results are stored in a 2-dimensional
            numpy array, the first dimension corresponding to the repetition
            and the second to the actual boolean measurement results (ordered
            by the qubits being measured.)
        """
        raise NotImplementedError()

class SimulatesAmplitudes(metaclass=abc.ABCMeta):
    """Simulator that computes final amplitudes of given bitstrings.

    Given a circuit and a list of bitstrings, computes the amplitudes
    of the given bitstrings in the state obtained by applying the circuit
    to the all zeros state. Implementors of this interface should implement
    the compute_amplitudes_sweep method.
    """

    def compute_amplitudes(
        self,
        program: 'cirq.Circuit',
        bitstrings: Sequence[int],
        param_resolver: 'study.ParamResolverOrSimilarType' = None,
        qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
    ) -> Sequence[complex]:
        """Computes the desired amplitudes.

        The initial state is assumed to be the all zeros state.

        Args:
            program: The circuit to simulate.
            bitstrings: The bitstrings whose amplitudes are desired, input
                as an integer array where each integer is formed from measured
                qubit values according to `qubit_order` from most to least
                significant qubit, i.e. in big-endian ordering.
            param_resolver: Parameters to run with the program.
            qubit_order: Determines the canonical ordering of the qubits. This
                is often used in specifying the initial state, i.e. the
                ordering of the computational basis states.

        Returns:
            List of amplitudes.
        """
        return self.compute_amplitudes_sweep(
            program, bitstrings, study.ParamResolver(param_resolver), qubit_order
        )[0]

    @abc.abstractmethod
    def compute_amplitudes_sweep(
        self,
        program: 'cirq.Circuit',
        bitstrings: Sequence[int],
        params: study.Sweepable,
        qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
    ) -> Sequence[Sequence[complex]]:
        """Computes the desired amplitudes.

        The initial state is assumed to be the all zeros state.

        Args:
            program: The circuit to simulate.
            bitstrings: The bitstrings whose amplitudes are desired, input
                as an integer array where each integer is formed from measured
                qubit values according to `qubit_order` from most to least
                significant qubit, i.e. in big-endian ordering.
            params: Parameters to run with the program.
            qubit_order: Determines the canonical ordering of the qubits. This
                is often used in specifying the initial state, i.e. the
                ordering of the computational basis states.

        Returns:
            List of lists of amplitudes. The outer dimension indexes the
            circuit parameters and the inner dimension indexes the bitstrings.
        """
        raise NotImplementedError()

class SimulatesExpectationValues(metaclass=abc.ABCMeta):
    """Simulator that computes exact expectation values of observables.

    Given a circuit and an observable map, computes exact (to float precision)
    expectation values for each observable at the end of the circuit.

    Implementors of this interface should implement the
    simulate_expectation_values_sweep method.
    """

    def simulate_expectation_values(
        self,
        program: 'cirq.Circuit',
        observables: Union['cirq.PauliSumLike', List['cirq.PauliSumLike']],
        param_resolver: 'study.ParamResolverOrSimilarType' = None,
        qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
        initial_state: Any = None,
        permit_terminal_measurements: bool = False,
    ) -> List[float]:
        """Simulates the supplied circuit and calculates exact expectation
        values for the given observables on its final state.

        This method has no perfect analogy in hardware. Instead compare with
        Sampler.sample_expectation_values, which calculates estimated
        expectation values by sampling multiple times.

        Args:
            program: The circuit to simulate.
            observables: An observable or list of observables.
            param_resolver: Parameters to run with the program.
            qubit_order: Determines the canonical ordering of the qubits. This
                is often used in specifying the initial state, i.e. the
                ordering of the computational basis states.
            initial_state: The initial state for the simulation. The form of
                this state depends on the simulation implementation. See
                documentation of the implementing class for details.
            permit_terminal_measurements: If the provided circuit ends with
                measurement(s), this method will generate an error unless this
                is set to True. This is meant to prevent measurements from
                ruining expectation value calculations.

        Returns:
            A list of expectation values, with the value at index `n`
            corresponding to `observables[n]` from the input.

        Raises:
            ValueError if 'program' has terminal measurement(s) and
            'permit_terminal_measurements' is False.
        """
        return self.simulate_expectation_values_sweep(
            program,
            observables,
            study.ParamResolver(param_resolver),
            qubit_order,
            initial_state,
            permit_terminal_measurements,
        )[0]

    @abc.abstractmethod
    def simulate_expectation_values_sweep(
        self,
        program: 'cirq.Circuit',
        observables: Union['cirq.PauliSumLike', List['cirq.PauliSumLike']],
        params: 'study.Sweepable',
        qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
        initial_state: Any = None,
        permit_terminal_measurements: bool = False,
    ) -> List[List[float]]:
        """Simulates the supplied circuit and calculates exact expectation
        values for the given observables on its final state, sweeping over the
        given params.

        This method has no perfect analogy in hardware. Instead compare with
        Sampler.sample_expectation_values, which calculates estimated
        expectation values by sampling multiple times.

        Args:
            program: The circuit to simulate.
            observables: An observable or list of observables.
            params: Parameters to run with the program.
            qubit_order: Determines the canonical ordering of the qubits. This
                is often used in specifying the initial state, i.e. the
                ordering of the computational basis states.
            initial_state: The initial state for the simulation. The form of
                this state depends on the simulation implementation. See
                documentation of the implementing class for details.
            permit_terminal_measurements: If the provided circuit ends in a
                measurement, this method will generate an error unless this
                is set to True. This is meant to prevent measurements from
                ruining expectation value calculations.

        Returns:
            A list of expectation-value lists. The outer index determines the
            sweep, and the inner index determines the observable. For instance,
            results[1][3] would select the fourth observable measured in the
            second sweep.

        Raises:
            ValueError if 'program' has terminal measurement(s) and
            'permit_terminal_measurements' is False.
        """

class SimulatesFinalState(Generic[TSimulationTrialResult], metaclass=abc.ABCMeta):
    """Simulator that allows access to the simulator's final state.

    Implementors of this interface should implement the simulate_sweep
    method. This simulator only returns the state of the quantum system
    for the final step of a simulation. This simulator state may be a state
    vector, the density matrix, or another representation, depending on the
    implementation.  For simulators that also allow stepping through
    a circuit see `SimulatesIntermediateState`.
    """

    def simulate(
        self,
        program: 'cirq.Circuit',
        param_resolver: 'study.ParamResolverOrSimilarType' = None,
        qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
        initial_state: Any = None,
    ) -> TSimulationTrialResult:
        """Simulates the supplied Circuit.

        This method returns a result which allows access to the entire
        simulator's final state.

        Args:
            program: The circuit to simulate.
            param_resolver: Parameters to run with the program.
            qubit_order: Determines the canonical ordering of the qubits. This
                is often used in specifying the initial state, i.e. the
                ordering of the computational basis states.
            initial_state: The initial state for the simulation. The form of
                this state depends on the simulation implementation. See
                documentation of the implementing class for details.

        Returns:
            SimulationTrialResults for the simulation. Includes the final state.
        """
        return self.simulate_sweep(
            program, study.ParamResolver(param_resolver), qubit_order, initial_state
        )[0]

    @abc.abstractmethod
    def simulate_sweep(
        self,
        program: 'cirq.Circuit',
        params: study.Sweepable,
        qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
        initial_state: Any = None,
    ) -> List[TSimulationTrialResult]:
        """Simulates the supplied Circuit.

        This method returns a result which allows access to the entire final
        simulator state. In contrast to simulate, this allows for sweeping
        over different parameter values.

        Args:
            program: The circuit to simulate.
            params: Parameters to run with the program.
            qubit_order: Determines the canonical ordering of the qubits. This
                is often used in specifying the initial state, i.e. the
                ordering of the computational basis states.
            initial_state: The initial state for the simulation. The form of
                this state depends on the simulation implementation. See
                documentation of the implementing class for details.

        Returns:
            List of SimulationTrialResults for this run, one for each
            possible parameter resolver.
        """
        raise NotImplementedError()

class SimulatesIntermediateState(
    Generic[TStepResult, TSimulationTrialResult, TSimulatorState],
    SimulatesFinalState[TSimulationTrialResult],
    metaclass=abc.ABCMeta,
):
    """A SimulatesFinalState that simulates a circuit by moments.

    Whereas a general SimulatesFinalState may return the entire simulator
    state at the end of a circuit, a SimulatesIntermediateState can
    simulate stepping through the moments of a circuit.

    Implementors of this interface should implement the _base_iterator
    method.

    Note that state here refers to simulator state, which is not necessarily
    a state vector.
    """

    def simulate_sweep(
        self,
        program: 'cirq.Circuit',
        params: study.Sweepable,
        qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
        initial_state: Any = None,
    ) -> List[TSimulationTrialResult]:
        """Simulates the supplied Circuit.

        This method returns a result which allows access to the entire
        state vector. In contrast to simulate, this allows for sweeping
        over different parameter values.

        Args:
            program: The circuit to simulate.
            params: Parameters to run with the program.
            qubit_order: Determines the canonical ordering of the qubits. This
                is often used in specifying the initial state, i.e. the
                ordering of the computational basis states.
            initial_state: The initial state for the simulation. The form of
                this state depends on the simulation implementation. See
                documentation of the implementing class for details.

        Returns:
            List of SimulationTrialResults for this run, one for each
            possible parameter resolver.
        """
        trial_results = []
        qubit_order = ops.QubitOrder.as_qubit_order(qubit_order)
        for param_resolver in study.to_resolvers(params):
            all_step_results = self.simulate_moment_steps(
                program, param_resolver, qubit_order, initial_state
            )
            measurements = {}  # type: Dict[str, np.ndarray]
            for step_result in all_step_results:
                for k, v in step_result.measurements.items():
                    measurements[k] = np.array(v, dtype=np.uint8)
            trial_results.append(
                self._create_simulator_trial_result(
                    params=param_resolver,
                    measurements=measurements,
                    final_simulator_state=step_result._simulator_state(),
                )
            )
        return trial_results

    def simulate_moment_steps(
        self,
        circuit: circuits.Circuit,
        param_resolver: 'study.ParamResolverOrSimilarType' = None,
        qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
        initial_state: Any = None,
    ) -> Iterator[TStepResult]:
        """Returns an iterator of StepResults for each moment simulated.

        If the circuit being simulated is empty, a single step result should
        be returned with the state being set to the initial state.

        Args:
            circuit: The Circuit to simulate.
            param_resolver: A ParamResolver for determining values of Symbols.
            qubit_order: Determines the canonical ordering of the qubits. This
                is often used in specifying the initial state, i.e. the
                ordering of the computational basis states.
            initial_state: The initial state for the simulation. The form of
                this state depends on the simulation implementation. See
                documentation of the implementing class for details.

        Returns:
            Iterator that steps through the simulation, simulating each
            moment and returning a StepResult for each moment.
        """
        param_resolver = study.ParamResolver(param_resolver)
        resolved_circuit = protocols.resolve_parameters(circuit, param_resolver)
        check_all_resolved(resolved_circuit)
        actual_initial_state = 0 if initial_state is None else initial_state
        return self._base_iterator(resolved_circuit, qubit_order, actual_initial_state)

    @deprecated(deadline='v0.11', fix='Override _base_iterator instead')
    def _simulator_iterator(
        self,
        circuit: circuits.Circuit,
        param_resolver: study.ParamResolver,
        qubit_order: ops.QubitOrderOrList,
        initial_state: Any,
    ) -> Iterator[TStepResult]:
        """Iterator over StepResult from Moments of a Circuit.

        If the initial state is an int, the state is set to the computational
        basis state corresponding to this state. Otherwise if the initial
        state is a np.ndarray it is the full initial state, either a pure state
        or the full density matrix.  If it is the pure state it must be the
        correct size, be normalized (an L2 norm of 1), and be safely castable
        to an appropriate dtype for the simulator.  If it is a mixed state
        it must be correctly sized and positive semidefinite with trace one.

        Args:
            circuit: The circuit to simulate.
            param_resolver: A ParamResolver for determining values of
                Symbols.
            qubit_order: Determines the canonical ordering of the qubits. This
                is often used in specifying the initial state, i.e. the
                ordering of the computational basis states.
            initial_state: The initial state for the simulation. The form of
                this state depends on the simulation implementation. See
                documentation of the implementing class for details.

        Yields:
            StepResults from simulating a Moment of the Circuit.
        """
        return self.simulate_moment_steps(circuit, param_resolver, qubit_order, initial_state)

    @abc.abstractmethod
    def _base_iterator(
        self,
        circuit: circuits.Circuit,
        qubit_order: ops.QubitOrderOrList,
        initial_state: Any,
    ) -> Iterator[TStepResult]:
        """Iterator over StepResult from Moments of a Circuit.

        Args:
            circuit: The circuit to simulate.
            param_resolver: A ParamResolver for determining values of
                Symbols.
            qubit_order: Determines the canonical ordering of the qubits. This
                is often used in specifying the initial state, i.e. the
                ordering of the computational basis states.
            initial_state: The initial state for the simulation. The form of
                this state depends on the simulation implementation. See
                documentation of the implementing class for details.

        Yields:
            StepResults from simulating a Moment of the Circuit.
        """
        raise NotImplementedError()

    @abc.abstractmethod
    def _create_simulator_trial_result(
        self,
        params: study.ParamResolver,
        measurements: Dict[str, np.ndarray],
        final_simulator_state: TSimulatorState,
    ) -> TSimulationTrialResult:
        """This method can be implemented to create a trial result.

        Args:
            params: The ParamResolver for this trial.
            measurements: The measurement results for this trial.
            final_simulator_state: The final state of the simulator for the
                StepResult.

        Returns:
            The SimulationTrialResult.
        """
        raise NotImplementedError()

class StepResult(Generic[TSimulatorState], metaclass=abc.ABCMeta):
    """Results of a step of a SimulatesIntermediateState.

    Attributes:
        measurements: A dictionary from measurement gate key to measurement
            results, ordered by the qubits that the measurement operates on.
    """

    def __init__(self, measurements: Optional[Dict[str, List[int]]] = None) -> None:
        self.measurements = measurements or collections.defaultdict(list)

    @abc.abstractmethod
    def _simulator_state(self) -> TSimulatorState:
        """Returns the simulator state of the simulator after this step.

        This method starts with an underscore to indicate that it is private.
        To access public state, see public methods on StepResult.

        The form of the simulator_state depends on the implementation of the
        simulation,see documentation for the implementing class for the form of
        details.
        """

    @abc.abstractmethod
    def sample(
        self,
        qubits: List[ops.Qid],
        repetitions: int = 1,
        seed: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None,
    ) -> np.ndarray:
        """Samples from the system at this point in the computation.

        Note that this does not collapse the state vector.

        Args:
            qubits: The qubits to be sampled in an order that influence the
                returned measurement results.
            repetitions: The number of samples to take.
            seed: A seed for the pseudorandom number generator.

        Returns:
            Measurement results with True corresponding to the ``|1⟩`` state.
            The outer list is for repetitions, and the inner corresponds to
            measurements ordered by the supplied qubits. These lists
            are wrapped as a numpy ndarray.
        """
        raise NotImplementedError()

    def sample_measurement_ops(
        self,
        measurement_ops: List[ops.GateOperation],
        repetitions: int = 1,
        seed: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None,
    ) -> Dict[str, np.ndarray]:
        """Samples from the system at this point in the computation.

        Note that this does not collapse the state vector.

        In contrast to `sample` which samples qubits, this takes a list of
        `cirq.GateOperation` instances whose gates are `cirq.MeasurementGate`
        instances and then returns a mapping from the key in the measurement
        gate to the resulting bit strings. Different measurement operations must
        not act on the same qubits.

        Args:
            measurement_ops: `GateOperation` instances whose gates are
                `MeasurementGate` instances to be sampled form.
            repetitions: The number of samples to take.
            seed: A seed for the pseudorandom number generator.

        Returns: A dictionary from measurement gate key to measurement
            results. Measurement results are stored in a 2-dimensional
            numpy array, the first dimension corresponding to the repetition
            and the second to the actual boolean measurement results (ordered
            by the qubits being measured.)

        Raises:
            ValueError: If the operation's gates are not `MeasurementGate`
                instances or a qubit is acted upon multiple times by different
                operations from `measurement_ops`.
        """

        # Sanity checks.
        seen_measurement_keys: Set[str] = set()
        for op in measurement_ops:
            gate = op.gate
            if not isinstance(gate, ops.MeasurementGate):
                raise ValueError(f'{op.gate} was not a MeasurementGate')
            key = protocols.measurement_key(gate)
            if key in seen_measurement_keys:
                raise ValueError(f'Duplicate MeasurementGate with key {key}')
            seen_measurement_keys.add(key)

        # Find measured qubits, ensuring a consistent ordering.
        measured_qubits = []
        seen_qubits: Set[cirq.Qid] = set()
        for op in measurement_ops:
            for q in op.qubits:
                if q not in seen_qubits:
                    seen_qubits.add(q)
                    measured_qubits.append(q)

        # Perform whole-system sampling of the measured qubits.
        indexed_sample = self.sample(measured_qubits, repetitions, seed=seed)

        # Extract results for each measurement.
        results: Dict[str, np.ndarray] = {}
        qubits_to_index = {q: i for i, q in enumerate(measured_qubits)}
        for op in measurement_ops:
            gate = cast(ops.MeasurementGate, op.gate)
            out = np.zeros(shape=(repetitions, len(op.qubits)), dtype=np.int8)
            inv_mask = gate.full_invert_mask()
            for i, q in enumerate(op.qubits):
                out[:, i] = indexed_sample[:, qubits_to_index[q]]
                if inv_mask[i]:
                    out[:, i] ^= out[:, i] < 2
            results[gate.key] = out

        return results

@value.value_equality(unhashable=True)
class SimulationTrialResult:
    """Results of a simulation by a SimulatesFinalState.

    Unlike Result these results contain the final simulator_state of the
    system. This simulator_state is dependent on the simulation implementation
    and may be, for example, the state vector or the density matrix of the
    system.

    Attributes:
        params: A ParamResolver of settings used for this result.
        measurements: A dictionary from measurement gate key to measurement
            results. Measurement results are a numpy ndarray of actual boolean
            measurement results (ordered by the qubits acted on by the
            measurement gate.)
    """

    def __init__(
        self,
        params: study.ParamResolver,
        measurements: Dict[str, np.ndarray],
        final_simulator_state: Any,
    ) -> None:
        self.params = params
        self.measurements = measurements
        self._final_simulator_state = final_simulator_state

    def __repr__(self) -> str:
        return (
            f'cirq.SimulationTrialResult(params={self.params!r}, '
            f'measurements={self.measurements!r}, '
            f'final_simulator_state={self._final_simulator_state!r})'
        )

    def __str__(self) -> str:
        def bitstring(vals):
            separator = ' ' if np.max(vals) >= 10 else ''
            return separator.join(str(int(v)) for v in vals)

        results = sorted([(key, bitstring(val)) for key, val in self.measurements.items()])
        if not results:
            return '(no measurements)'
        return ' '.join([f'{key}={val}' for key, val in results])

    def _repr_pretty_(self, p: Any, cycle: bool) -> None:
        """Text output in Jupyter."""
        if cycle:
            # There should never be a cycle.  This is just in case.
            p.text('SimulationTrialResult(...)')
        else:
            p.text(str(self))

    def _value_equality_values_(self) -> Any:
        measurements = {k: v.tolist() for k, v in sorted(self.measurements.items())}
        return (self.params, measurements, self._final_simulator_state)

    @property
    def qubit_map(self) -> Dict[ops.Qid, int]:
        """A map from Qid to index used to define the ordering of the basis in
        the result.
        """
        return self._final_simulator_state.qubit_map

    def _qid_shape_(self) -> Tuple[int, ...]:
        return _qubit_map_to_shape(self.qubit_map)

def _qubit_map_to_shape(qubit_map: Dict[ops.Qid, int]) -> Tuple[int, ...]:
    qid_shape: List[int] = [-1] * len(qubit_map)
    try:
        for q, i in qubit_map.items():
            qid_shape[i] = q.dimension
    except IndexError:
        raise ValueError(f'Invalid qubit_map. Qubit index out of bounds. Map is <{qubit_map!r}>.')
    if -1 in qid_shape:
        raise ValueError(f'Invalid qubit_map. Duplicate qubit index. Map is <{qubit_map!r}>.')
    return tuple(qid_shape)

def _verify_unique_measurement_keys(circuit: circuits.Circuit):
    result = collections.Counter(
        key for op in ops.flatten_op_tree(iter(circuit)) for key in protocols.measurement_keys(op)
    )
    if result:
        duplicates = [k for k, v in result.most_common() if v > 1]
        if duplicates:
            raise ValueError(f"Measurement key {','.join(duplicates)} repeated")

def check_all_resolved(circuit):
    """Raises if the circuit contains unresolved symbols."""
    if protocols.is_parameterized(circuit):
        unresolved = [op for moment in circuit for op in moment if protocols.is_parameterized(op)]
        raise ValueError(
            'Circuit contains ops whose symbols were not specified in '
            'parameter sweep. Ops: {}'.format(unresolved)
        )

def split_into_matching_protocol_then_general(
    circuit: 'cirq.Circuit',
    predicate: Callable[['cirq.Operation'], bool],
) -> Tuple['cirq.Circuit', 'cirq.Circuit']:
    """Splits the circuit into a matching prefix and non-matching suffix.

    The splitting happens in a per-qubit fashion. A non-matching operation on
    qubit A will cause later operations on A to be part of the non-matching
    suffix, but later operations on other qubits will continue to be put into
    the matching part (as long as those qubits have had no non-matching operation
    up to that point).
    """
    blocked_qubits: Set[cirq.Qid] = set()
    matching_prefix = circuits.Circuit()
    general_suffix = circuits.Circuit()
    for moment in circuit:
        matching_part = []
        general_part = []
        for op in moment:
            qs = set(op.qubits)
            if not predicate(op) or not qs.isdisjoint(blocked_qubits):
                blocked_qubits |= qs

            if qs.isdisjoint(blocked_qubits):
                matching_part.append(op)
            else:
                general_part.append(op)
        if matching_part:
            matching_prefix.append(ops.Moment(matching_part))
        if general_part:
            general_suffix.append(ops.Moment(general_part))
    return matching_prefix, general_suffix


text:
import sys
import os
import shutil
import glob

# This is Debian control file in a skeleton reusable block
control_skeleton='''
Maintainer: Albert Casals <skarbat@gmail.com>
Section: others
Package: {pkg_name}
Version: {pkg_version}
Conflicts: libqt5all-dev (<= 5.7-1)
Architecture: armhf
Depends: debconf (>= 0.5.00), {pkg_depends}
Priority: optional
Description: {pkg_description}

'''

postinst_script='''
#!/bin/bash

case "$1" in
    configure)
       mkdir -p mkdir -p /opt/rpi-tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin/
       ln -sf /usr/bin/gcc      /opt/rpi-tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin/arm-linux-gnueabihf-gcc
       ln -sf /usr/bin/g++      /opt/rpi-tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin/arm-linux-gnueabihf-g++
       ln -sf /usr/bin/objcopy  /opt/rpi-tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin/arm-linux-gnueabihf-objcopy
       ln -sf /usr/bin/strip    /opt/rpi-tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin/arm-linux-gnueabihf-strip
       ;;
esac

#DEBHELPER#

exit 0
'''

postrm_script='''
#!/bin/bash

case "$1" in
    remove)
       rm -f /usr/bin/qmake
       rm -rf /opt/rpi-tools
       ;;
esac

#DEBHELPER#

exit 0
'''

# Allows forget about setting PATH on build environments
qmake_link ='''#!/bin/bash
PATH=$PATH:/usr/local/qt5/bin /usr/local/qt5/bin/qmake
'''

extra_deps = ''

# These are the packages we are building
# For the moment we are collecting everyting in one single Debian pkg
packages=[

    { 'fileset': '',
      'pkg_name': 'libqt5all-native-tools',
      'pkg_version': 0,
      'pkg_depends': 'libqt5all-dev (>= 5.9-0)',
      'pkg_description': 'QT5 Native compilation tools for the RaspberryPI' }
]

def pack_tools(root_directory, source_directory, qt5_version, tools_directory, dry_run=False):

    complete_source='{}/{}'.format(root_directory, source_directory)

    # Sanity check
    if not os.path.exists(complete_source):
        print 'error: path not found', complete_source
        sys.exit(1)

    for pkg in packages:

        pkg['pkg_version'] = qt5_version
        pkg['fileset'] = [ tools_directory ]

        # allocate a versioned directory name for the package
        versioned_pkg_name = 'pkgs/{}_{}'.format(pkg['pkg_name'], qt5_version)
        print 'Processing package {}...'.format(versioned_pkg_name)

        # extract the files from the root file system preparing them for packaging
        target_directory = '{}/{}'.format (versioned_pkg_name, source_directory)

        for files in pkg['fileset']:

            # Complete the pathname to the target directory
            last_path = os.path.dirname(files)
            target_files_path='{}/{}'.format(target_directory, last_path)

            print 'Extracting {} into {}...'.format(os.path.join(complete_source, files), target_files_path)
            if not os.path.exists(target_files_path) and not dry_run:
                os.makedirs(target_files_path)

            if not dry_run:
                os.system('cp -rvP {} {}'.format(os.path.join(complete_source, files), target_files_path))

        # create the Debian control file for "dpkg-deb" tool to know what to pack
        if not dry_run:
            debian_dir=os.path.join(versioned_pkg_name, 'DEBIAN')
            if not os.path.exists(debian_dir):
                os.makedirs(debian_dir)
            with open(os.path.join(debian_dir, 'control'), 'w') as control_file:
                control_file.writelines(control_skeleton.format(**pkg))

        # package postinst & postrm scripts - resolve qmake PATH on native builds
        if not dry_run:
            postinst_filename='{}/postinst'.format(debian_dir)
            postrm_filename='{}/postrm'.format(debian_dir)
            qmake_filename='{}/usr/bin/qmake'.format(os.path.join(versioned_pkg_name))
            with open(postinst_filename, 'w') as f:
                f.write(postinst_script)
                os.system('chmod ugo+rx {}'.format(postinst_filename))

            with open(postrm_filename, 'w') as f:
                f.write(postrm_script)
                os.system('chmod ugo+rx {}'.format(postrm_filename))

            os.makedirs(os.path.dirname(qmake_filename))
            with open(qmake_filename, 'w') as f:
                f.write(qmake_link)
                os.system('chmod ugo+rx {}'.format(qmake_filename))

        # finally call dpkg-deb and generate a debian package
        if not dry_run:
            rc=os.system('dpkg-deb --build {}'.format(versioned_pkg_name))
        else:
            rc=0

        if not rc:
            print 'Package {} created correctly'.format(versioned_pkg_name)
        else:
            print 'WARNING: Error creating package {}'.format(versioned_pkg_name)


text:
var insertionSort = require('./insertionSort');
var mergeSort = require('./mergeSort');

module.exports = {
    insertionSort: insertionSort,
    mergeSort: mergeSort
};


text:
using BellRichM.Attribute.CodeCoverage;
using Serilog.Core;

namespace BellRichM.Logging
{
    /// <summary>
    /// The logging level switches.
    /// </summary>
    [ExcludeFromCodeCoverage]
    public class LoggingLevelSwitches
    {
        /// <summary>
        /// Gets or sets <see cref="LoggingLevelSwitch"/>that dynamically controls the default logging level.
        /// </summary>
        /// <value>
        /// The logging level to filter on.
        /// </value>
        public LoggingLevelSwitch DefaultLoggingLevelSwitch { get; set; }

        /// <summary>
        /// Gets or sets <see cref="LoggingLevelSwitch"/>that dynamically controls the logging level of microsoft messages.
        /// </summary>
        /// <value>
        /// The logging level to filter on.
        /// </value>
        public LoggingLevelSwitch MicrosoftLoggingLevelSwitch { get; set; }

        /// <summary>
        /// Gets or sets <see cref="LoggingLevelSwitch"/>that dynamically controls the logging level of system messages.
        /// </summary>
        /// <value>
        /// The logging level to filter on.
        /// </value>
        public LoggingLevelSwitch SystemLoggingLevelSwitch { get; set; }

        /// <summary>
        /// Gets or sets <see cref="LoggingLevelSwitch"/>that dynamically controls the logging level of the console sink.
        /// </summary>
        /// <value>
        /// The logging level to filter on.
        /// </value>
        public LoggingLevelSwitch ConsoleSinkLevelSwitch { get; set; }
    }
}


text:
The public-REST based web application to serve the frontend of the RateMyNews service. This application has been
developed as coursework for the my NET302 coursework.
## Requirements
* Docker (1.8.0)

## Instructions
This application uses a docker container to deploy the Flask based application to the host machine and forwards the relevant ports.

1. Open your command line utility to the 'RateMyNewsUI' folder.
2. Enter the following command: `docker build -t ratemynewsui:latest .`
3. Enter the following command: `docker run -d --name rmnui -it -p 5000:5000 ratemynewsui`

## Available Routes
Title | Description | Route
--- | --- | ---
View News | Provides a news article and form to allow the user to react. | `/view-news`
React | Accepts a news article from the previously mentioned page and pushes the data to the Elasticsearch cluster. | `/submit-reaction`

## Contents
### Folder Layout
![Package Diagram](https://github.com/Sciprios/RateMyNewsUI/raw/master/docs/images/pckg.png "Package Diagram for RateMyNewsUI")
### Content Descriptions
#### RateMyNewsUI
Name | Type | Description
--- | --- | ---
.gitignore | File | A file containing references to files which should not be uploaded to Git.
Dockerfile | File | A file which details what should happen when this components docker container is built and ran.
LICENSE | File | A file containing details of the license this component is available under.
README | Markdown File | A file describing what should be shown on the GitHub home page for this repository. This contains instructions for running the service.
requirements | Text File | A list of requirements this component requires in order to run. These requirements are installed when the docker container is built.
#### rate_my_news_ui
Name | Type | Description
--- | --- | ---
__init__ | Python File | A file indicating this folder as a Python package, contains any package initialization code.
config | Python File | Adds any config variables to the Flask application.
default | Python File | Contains the code for each route to be served.
forms | Python File | Contains the classes for WTF-Forms used.
run | Python File | A script which begins the application and serves the routes.
#### templates
Name | Type | Description
--- | --- | ---
news | HTML File | Jinja2 template to produce a HTML page for the user containing a news story, form to react with and social media buttons.
no_news | HTML File | Jinja2 template to produce HTML page for the occurence there is no news.


text:
import { createStore, applyMiddleware } from 'redux'
import thunkMiddleware from 'redux-thunk'
import rootReducer from '../reducers'

export default function configureStore(initialState) {
    const store = createStore(
        rootReducer,
        initialState,
        applyMiddleware(
            thunkMiddleware, // 允许我们 dispatch() 函数
        ),
    )
    return store
}


text:
class AddReceiverEmailToMessage < ActiveRecord::Migration
  def up
    add_column :messages, :receiver_email, :string

    execute(<<-SQL)
      UPDATE messages SET receiver_email = users.email
      FROM users
      WHERE messages.receiver_id = users.id
    SQL

    change_column :messages, :receiver_email, :string, null: false
  end

  def down
    remove_column :messages, :receiver_email
  end
end


text:
This Bazel project provides examples on how to build Docker images using
[rules_docker](https://github.com/bazelbuild/rules_docker). This project is
structured such that every directory contains one separate example. For ease of
understanding, each example also comes with the equivalent Dockerfile. In
addition, all examples include tests that run against the image built from
a Dockerfile and against the image generated by rules_docker.

## Getting Started

Simply browse each directory and compare side by side the Dockerfile with the
BUILD file where the Bazel targets to build images are defined.

In order to run the tests to verify the images' equivalence, you can run all
the test targets (which also builds all the required images using rules_docker)
by running the following from the root of this project:
```
$ bazel test //...
```

## More Details

For further comparison details between Dockerfile and container_image from
rules_docker, please refer to the [Dockerfile reference](https://docs.docker.com/engine/reference/builder)
and [container_image reference](https://github.com/bazelbuild/rules_docker#container_image-1)


text:
#ifndef OF_GAMESTATES_GAME_AI_ASTAR_H
#define OF_GAMESTATES_GAME_AI_ASTAR_H

#include <ace/types.h>
#include "gamestates/game/ai/heap.h"
#include "gamestates/game/ai/ai.h"

#define ASTAR_STATE_OFF 0
#define ASTAR_STATE_LOOPING 1
#define ASTAR_STATE_DONE 2

#define ASTAR_ROUTE_NODE_MAX 20

/**
 * Pathfinding route struct.
 * TOOD implement as stack
 */
typedef struct _tRoute {
	UBYTE ubNodeCount; ///< Number of nodes in route.
	UBYTE ubCurrNode; ///< Currently processed route node idx.
	tAiNode *pNodes[ASTAR_ROUTE_NODE_MAX]; ///< First is dest
} tRoute;

typedef struct {
	UBYTE ubState; ///< See ASTAR_STATE_* defines
	tHeap *pFrontier;
	tAiNode *pCameFrom[AI_MAX_NODES];
	UWORD pCostSoFar[AI_MAX_NODES];
	tAiNode *pNodeDst;
	tAiNode *pNodeCurr;
	UWORD uwCurrNeighbourIdx;
	tRoute sRoute;
} tAstarData;

/**
 * Allocates data for A* algorithm.
 * @return Newly allocated A* data struct.
 */
tAstarData *astarCreate(void);

/**
 * Frees A* data structure.
 * @param pNav A* data structure to be freed.
 */
void astarDestroy(tAstarData *pNav);

/**
 * Prepares A* initial conditions.
 * @param pNav A* data struct to be used.
 * @param pNodeSrc Route's first node.
 * @param pNodeDst Route's destination node.
 */
void astarStart(tAstarData *pNav, tAiNode *pNodeSrc, tAiNode *pNodeDst);

/**
 *
 */
UBYTE astarProcess(tAstarData *pNav);

#endif // OF_GAMESTATES_GAME_AI_ASTAR_H


text:
[![Donate via PayPal][donate-image]][donate-link]
[![Discord][discord-image]][discord-link]
[![Build][github-ci-image]][github-ci-link]
[![Coverage Status][codecov-image]][codecov-link]
[![PyPI Version][pypi-image]][pypi-link]
[![PyPI - Python Version][python-image]][pypi-link]
![License][license-image-mit]
# Bracex

Bracex is a brace expanding library (à la Bash) for Python. Brace expanding is used to generate arbitrary strings.

```console
$ echo {{a,b},c}d
ad bd cd
```

Bracex adds this ability to Python:

```python
>>> bracex.expand(r'file-{{a,b},c}d.txt')
['file-ad.txt', 'file-bd.txt', 'file-cd.txt']
```

and as a command:

```console
$ python3 -m bracex -0 "base/{a,b}/{1..2}" | xargs -0 mkdir -p
$ tree base/
base/
├── a
│   ├── 1
│   └── 2
└── b
    ├── 1
    └── 2
```

- **Why Bracex over other solutions?**

    Bracex actually follows pretty closely to how Bash processes braces. It is not a 1:1 implementation of how Bash
    handles braces, but generally, it follows very closely. Almost all of the test cases are run through Bash first,
    then our implementation is compared against the results Bash gives. There are a few cases where we have purposely
    deviated. For instance, we are not handling Bash's command line inputs, so we are not giving special meaning to back
    ticks and quotes at this time.

    On the command line Bracex can handle more expansions than Bash itself.

## Install

```console
$ pip install bracex
```

## Documentation

Documentation is found here: https://facelessuser.github.io/bracex/.

## License

MIT License

[github-ci-image]: https://github.com/facelessuser/bracex/workflows/build/badge.svg?branch=master&event=push
[github-ci-link]: https://github.com/facelessuser/bracex/actions?query=workflow%3Abuild+branch%3Amaster
[discord-image]: https://img.shields.io/discord/678289859768745989?logo=discord&logoColor=aaaaaa&color=mediumpurple&labelColor=333333
[discord-link]:https://discord.gg/TWs8Tgr
[codecov-image]: https://img.shields.io/codecov/c/github/facelessuser/bracex/master.svg?logo=codecov&logoColor=aaaaaa&labelColor=333333
[codecov-link]: https://codecov.io/github/facelessuser/bracex
[pypi-image]: https://img.shields.io/pypi/v/bracex.svg?logo=pypi&logoColor=aaaaaa&labelColor=333333
[pypi-link]: https://pypi.python.org/pypi/bracex
[python-image]: https://img.shields.io/pypi/pyversions/bracex?logo=python&logoColor=aaaaaa&labelColor=333333
[license-image-mit]: https://img.shields.io/badge/license-MIT-blue.svg?labelColor=333333
[donate-image]: https://img.shields.io/badge/Donate-PayPal-3fabd1?logo=paypal
[donate-link]: https://www.paypal.me/facelessuser