text:
from cinder import db
from cinder import exception
from cinder.i18n import _
from cinder import objects
from cinder.objects import base
from cinder.objects import fields as c_fields
from oslo_versionedobjects import fields

@base.CinderObjectRegistry.register
class Group(base.CinderPersistentObject, base.CinderObject,
            base.CinderObjectDictCompat):
    # Version 1.0: Initial version
    # Version 1.1: Added group_snapshots, group_snapshot_id, and
    #              source_group_id
    VERSION = '1.1'

    OPTIONAL_FIELDS = ['volumes', 'volume_types', 'group_snapshots']

    fields = {
        'id': fields.UUIDField(),
        'user_id': fields.StringField(),
        'project_id': fields.StringField(),
        'cluster_name': fields.StringField(nullable=True),
        'host': fields.StringField(nullable=True),
        'availability_zone': fields.StringField(nullable=True),
        'name': fields.StringField(nullable=True),
        'description': fields.StringField(nullable=True),
        'group_type_id': fields.StringField(),
        'volume_type_ids': fields.ListOfStringsField(nullable=True),
        'status': c_fields.GroupStatusField(nullable=True),
        'group_snapshot_id': fields.UUIDField(nullable=True),
        'source_group_id': fields.UUIDField(nullable=True),
        'volumes': fields.ObjectField('VolumeList', nullable=True),
        'volume_types': fields.ObjectField('VolumeTypeList',
                                           nullable=True),
        'group_snapshots': fields.ObjectField('GroupSnapshotList',
                                              nullable=True),
    }

    @staticmethod
    def _from_db_object(context, group, db_group,
                        expected_attrs=None):
        if expected_attrs is None:
            expected_attrs = []
        for name, field in group.fields.items():
            if name in Group.OPTIONAL_FIELDS:
                continue
            value = db_group.get(name)
            setattr(group, name, value)

        if 'volumes' in expected_attrs:
            volumes = base.obj_make_list(
                context, objects.VolumeList(context),
                objects.Volume,
                db_group['volumes'])
            group.volumes = volumes

        if 'volume_types' in expected_attrs:
            volume_types = base.obj_make_list(
                context, objects.VolumeTypeList(context),
                objects.VolumeType,
                db_group['volume_types'])
            group.volume_types = volume_types

        if 'group_snapshots' in expected_attrs:
            group_snapshots = base.obj_make_list(
                context, objects.GroupSnapshotList(context),
                objects.GroupSnapshot,
                db_group['group_snapshots'])
            group.group_snapshots = group_snapshots

        group._context = context
        group.obj_reset_changes()
        return group

    def create(self, group_snapshot_id=None, source_group_id=None):
        if self.obj_attr_is_set('id'):
            raise exception.ObjectActionError(action='create',
                                              reason=_('already_created'))
        updates = self.cinder_obj_get_changes()

        if 'volume_types' in updates:
            raise exception.ObjectActionError(
                action='create',
                reason=_('volume_types assigned'))

        if 'volumes' in updates:
            raise exception.ObjectActionError(action='create',
                                              reason=_('volumes assigned'))

        if 'group_snapshots' in updates:
            raise exception.ObjectActionError(
                action='create',
                reason=_('group_snapshots assigned'))

        db_groups = db.group_create(self._context,
                                    updates,
                                    group_snapshot_id,
                                    source_group_id)
        self._from_db_object(self._context, self, db_groups)

    def obj_load_attr(self, attrname):
        if attrname not in Group.OPTIONAL_FIELDS:
            raise exception.ObjectActionError(
                action='obj_load_attr',
                reason=_('attribute %s not lazy-loadable') % attrname)
        if not self._context:
            raise exception.OrphanedObjectError(method='obj_load_attr',
                                                objtype=self.obj_name())

        if attrname == 'volume_types':
            self.volume_types = objects.VolumeTypeList.get_all_by_group(
                self._context, self.id)

        if attrname == 'volumes':
            self.volumes = objects.VolumeList.get_all_by_generic_group(
                self._context, self.id)

        if attrname == 'group_snapshots':
            self.group_snapshots = objects.GroupSnapshotList.get_all_by_group(
                self._context, self.id)

        self.obj_reset_changes(fields=[attrname])

    def save(self):
        updates = self.cinder_obj_get_changes()
        if updates:
            if 'volume_types' in updates:
                msg = _('Cannot save volume_types changes in group object '
                        'update.')
                raise exception.ObjectActionError(
                    action='save', reason=msg)
            if 'volumes' in updates:
                msg = _('Cannot save volumes changes in group object update.')
                raise exception.ObjectActionError(
                    action='save', reason=msg)
            if 'group_snapshots' in updates:
                msg = _('Cannot save group_snapshots changes in group object '
                        'update.')
                raise exception.ObjectActionError(
                    action='save', reason=msg)

            db.group_update(self._context, self.id, updates)
            self.obj_reset_changes()

    def destroy(self):
        with self.obj_as_admin():
            db.group_destroy(self._context, self.id)

@base.CinderObjectRegistry.register
class GroupList(base.ObjectListBase, base.CinderObject):
    # Version 1.0: Initial version
    VERSION = '1.0'

    fields = {
        'objects': fields.ListOfObjectsField('Group')
    }
    child_version = {
        '1.0': '1.0',
    }

    @classmethod
    def get_all(cls, context, filters=None, marker=None, limit=None,
                offset=None, sort_keys=None, sort_dirs=None):
        groups = db.group_get_all(
            context, filters=filters, marker=marker, limit=limit,
            offset=offset, sort_keys=sort_keys, sort_dirs=sort_dirs)
        return base.obj_make_list(context, cls(context),
                                  objects.Group,
                                  groups)

    @classmethod
    def get_all_by_project(cls, context, project_id, filters=None, marker=None,
                           limit=None, offset=None, sort_keys=None,
                           sort_dirs=None):
        groups = db.group_get_all_by_project(
            context, project_id, filters=filters, marker=marker, limit=limit,
            offset=offset, sort_keys=sort_keys, sort_dirs=sort_dirs)
        return base.obj_make_list(context, cls(context),
                                  objects.Group,
                                  groups)


text:
'use strict';
var Blueprint     = require('../../lib/models/blueprint');
var originTaskFor = Blueprint.prototype.taskFor;
var assert        = require('../helpers/assert');
var Promise       = require('../../lib/ext/promise');

module.exports = {
  disableNPM: function() {
    Blueprint.prototype.taskFor = function(taskName) {
      // we don't actually need to run the npm-install task, so lets mock it to
      // speedup tests that need it
      assert.equal(taskName, 'npm-install');

      return {
        run: function() {
          return Promise.resolve();
        }
      };
    };
  },

  restoreNPM: function() {
    Blueprint.prototype.taskFor = originTaskFor;
  }
};

redpajama_set_name: RedPajamaGithub


text:
package com.peterphi.std.guice.web.rest.jaxrs.exception;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;

/**
 * An exception that contains the exact Response that should be sent back to the client
 */
public class LiteralRestResponseException extends WebApplicationException
{
	public LiteralRestResponseException(Response response)
	{
		super(response);
	}

	public LiteralRestResponseException(Response response, Throwable cause)
	{
		super(cause, response);
	}
}


text:
#import <React/RCTResizeMode.h>

@implementation RCTConvert (RCTResizeMode)

RCT_ENUM_CONVERTER(
    RCTResizeMode,
    (@{
      @"cover" : @(RCTResizeModeCover),
      @"contain" : @(RCTResizeModeContain),
      @"stretch" : @(RCTResizeModeStretch),
      @"center" : @(RCTResizeModeCenter),
      @"repeat" : @(RCTResizeModeRepeat),
    }),
    RCTResizeModeStretch,
    integerValue)

@end


text:
package org.lumongo.server.search;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.DisjunctionMaxQuery;
import org.apache.lucene.search.MultiPhraseQuery;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.Query;
import org.lumongo.server.config.IndexConfig;

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

/**
 * Created by Matt Davis on 5/14/16.
 * @author mdavis
 * Copied mostly from org.apache.lucene.queryparser.classic.MultiFieldQueryParser
 */
public class LumongoMultiFieldQueryParser extends LumongoQueryParser {

	protected List<String> fields;
	protected Map<String, Float> boosts;
	private float dismaxTie = 0;
	private boolean dismax = false;

	public LumongoMultiFieldQueryParser(Analyzer analyzer, IndexConfig indexConfig) {
		super(analyzer, indexConfig);
	}

	public void enableDismax(float dismaxTie) {
		this.dismaxTie = dismaxTie;
		this.dismax = true;
	}

	public void disableDismax() {
		this.dismax = false;
	}

	public void setDefaultFields(Collection<String> fields) {
		setDefaultFields(fields, null);
	}

	public void setDefaultFields(Collection<String> fields, Map<String, Float> boosts) {
		this.field = null;
		this.fields = new ArrayList<>(fields);
		this.boosts = boosts;
	}

	@Override
	public void setDefaultField(String field) {
		super.setDefaultField(field);
		this.fields = null;
	}

	@Override
	protected Query getFieldQuery(String field, String queryText, int slop) throws ParseException {
		if (field == null) {
			List<Query> clauses = new ArrayList<>();
			for (String f : fields) {
				Query q = super.getFieldQuery(f, queryText, true);
				if (q != null) {
					//If the user passes a map of boosts
					if (boosts != null) {
						//Get the boost from the map and apply them
						Float boost = boosts.get(f);
						if (boost != null) {
							q = new BoostQuery(q, boost);
						}
					}
					q = applySlop(q, slop);
					clauses.add(q);
				}
			}
			if (clauses.size() == 0)  // happens for stopwords
				return null;
			return getMultiFieldQuery(clauses);
		}
		Query q = super.getFieldQuery(field, queryText, true);
		q = applySlop(q, slop);
		return q;
	}

	private Query applySlop(Query q, int slop) {
		if (q instanceof PhraseQuery) {
			PhraseQuery.Builder builder = new PhraseQuery.Builder();
			builder.setSlop(slop);
			PhraseQuery pq = (PhraseQuery) q;
			org.apache.lucene.index.Term[] terms = pq.getTerms();
			int[] positions = pq.getPositions();
			for (int i = 0; i < terms.length; ++i) {
				builder.add(terms[i], positions[i]);
			}
			q = builder.build();
		}
		else if (q instanceof MultiPhraseQuery) {
			MultiPhraseQuery mpq = (MultiPhraseQuery) q;

			if (slop != mpq.getSlop()) {
				q = new MultiPhraseQuery.Builder(mpq).setSlop(slop).build();
			}
		}
		return q;
	}

	@Override
	protected Query getFieldQuery(String field, String queryText, boolean quoted) throws ParseException {
		if (field == null) {
			List<Query> clauses = new ArrayList<>();
			Query[] fieldQueries = new Query[fields.size()];
			int maxTerms = 0;
			for (int i = 0; i < fields.size(); i++) {
				Query q = super.getFieldQuery(fields.get(i), queryText, quoted);
				if (q != null) {
					if (q instanceof BooleanQuery) {
						maxTerms = Math.max(maxTerms, ((BooleanQuery) q).clauses().size());
					}
					else {
						maxTerms = Math.max(1, maxTerms);
					}
					fieldQueries[i] = q;
				}
			}
			for (int termNum = 0; termNum < maxTerms; termNum++) {
				List<Query> termClauses = new ArrayList<>();
				for (int i = 0; i < fields.size(); i++) {
					if (fieldQueries[i] != null) {
						Query q = null;
						if (fieldQueries[i] instanceof BooleanQuery) {
							List<BooleanClause> nestedClauses = ((BooleanQuery) fieldQueries[i]).clauses();
							if (termNum < nestedClauses.size()) {
								q = nestedClauses.get(termNum).getQuery();
							}
						}
						else if (termNum == 0) { // e.g. TermQuery-s
							q = fieldQueries[i];
						}
						if (q != null) {
							if (boosts != null) {
								//Get the boost from the map and apply them
								Float boost = boosts.get(fields.get(i));
								if (boost != null) {
									q = new BoostQuery(q, boost);
								}
							}
							termClauses.add(q);
						}
					}
				}
				if (maxTerms > 1) {
					if (termClauses.size() > 0) {
						//mdavis - don't use super method because of min match
						BooleanQuery.Builder builder = new BooleanQuery.Builder();
						for (Query termClause : termClauses) {
							builder.add(termClause, BooleanClause.Occur.SHOULD);
						}
						clauses.add(builder.build());
					}
				}
				else {
					clauses.addAll(termClauses);
				}
			}
			if (clauses.size() == 0)  // happens for stopwords
				return null;
			return getMultiFieldQuery(clauses);
		}
		Query q = super.getFieldQuery(field, queryText, quoted);
		return q;
	}

	@Override
	protected Query getFuzzyQuery(String field, String termStr, float minSimilarity) throws ParseException {
		if (field == null) {
			List<Query> clauses = new ArrayList<>();
			for (String f : fields) {
				clauses.add(getFuzzyQuery(f, termStr, minSimilarity));
			}
			return getMultiFieldQuery(clauses);
		}
		return super.getFuzzyQuery(field, termStr, minSimilarity);
	}

	@Override
	protected Query getPrefixQuery(String field, String termStr) throws ParseException {
		if (field == null) {
			List<Query> clauses = new ArrayList<>();
			for (String f : fields) {
				clauses.add(getPrefixQuery(f, termStr));
			}
			return getMultiFieldQuery(clauses);
		}
		return super.getPrefixQuery(field, termStr);
	}

	@Override
	protected Query getWildcardQuery(String field, String termStr) throws ParseException {
		if (field == null) {
			List<Query> clauses = new ArrayList<>();
			for (String f : fields) {
				clauses.add(getWildcardQuery(f, termStr));
			}
			return getMultiFieldQuery(clauses);
		}
		return super.getWildcardQuery(field, termStr);
	}

	@Override
	protected Query getRangeQuery(String field, String part1, String part2, boolean startInclusive, boolean endInclusive) throws ParseException {
		if (field == null) {
			List<Query> clauses = new ArrayList<>();
			for (String f : fields) {
				clauses.add(getRangeQuery(f, part1, part2, startInclusive, endInclusive));
			}
			return getMultiFieldQuery(clauses);
		}
		return super.getRangeQuery(field, part1, part2, startInclusive, endInclusive);
	}

	@Override
	protected Query getRegexpQuery(String field, String termStr) throws ParseException {
		if (field == null) {
			List<Query> clauses = new ArrayList<>();
			for (String f : fields) {
				clauses.add(getRegexpQuery(f, termStr));
			}
			return getMultiFieldQuery(clauses);
		}
		return super.getRegexpQuery(field, termStr);
	}

	/** Creates a multifield query */
	// TODO: investigate more general approach by default, e.g. DisjunctionMaxQuery?
	protected Query getMultiFieldQuery(List<Query> queries) throws ParseException {
		if (queries.isEmpty()) {
			return null; // all clause words were filtered away by the analyzer.
		}

		if (dismax) {
			return new DisjunctionMaxQuery(queries, dismaxTie);
		}
		else {
			//mdavis - don't use super method because of min match
			BooleanQuery.Builder query = new BooleanQuery.Builder();
			for (Query sub : queries) {
				query.add(sub, BooleanClause.Occur.SHOULD);
			}

			return query.build();
		}
	}

}


text:
<?php

namespace IDCT\Codec;

use IDCT\ICodec;

class SerializeCodec implements ICodec
{
    /**
     * @inheritdoc
    */
    public function encode($object)
    {
        return serialize($object);
    }

    /**
     * @inheritdoc
    */
    public function decode($string)
    {
        return unserialize($string);
    }
}


text:
module.exports = function json_encode(json){
    return JSON.stringify(json);
}


text:
var assert = require('assert'),
	scraper = require('../index');

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

describe('stores', function(){

	describe('amazon', function(){
		this.slow(6500);

		it('has not changed markup', function(done){
			this.timeout(10000);

			scraper.init('http://www.amazon.com/gp/product/B00X4WHP5E/', function(data){

				if(Object.size(data) != 7) throw err;
				done();

			});

		});

	});

	describe('bestbuy', function(){
		this.slow(6500);

		it('has not changed markup', function(done){
			this.timeout(10000);

			scraper.init('http://www.bestbuy.com/site/apple-macbook-pro-15-4-display-intel-core-i7-16gb-memory-256gb-flash-storage-silver/8532502.p?id=1219343246944&skuId=8532502', function(data){

				if(Object.size(data) != 6) throw err;
				done();

			});

		});

	});

	describe('etsy', function(){
		this.slow(6500);

		it('has not changed markup', function(done){
			this.timeout(10000);

			scraper.init('https://www.etsy.com/listing/255992683/iskelter-case-built-for-iphone-66s-and', function(data){

				if(Object.size(data) != 6) throw err;
				done();

			});

		});

	});

	describe('target', function(){
		this.slow(6500);

		it('has not changed markup', function(done){
			this.timeout(10000);

			scraper.init('http://www.target.com/p/canon-eos-rebel-sl1-18mp-digital-slr-camera-with-18-55mm-lens/-/A-14537289?lnk=rec|pdp|top_rated|cath770X250', function(data){

				if(Object.size(data) != 5) throw err;
				done();

			});

		});

	});

	describe('walmart', function(){
		this.slow(6500);

		it('has not changed markup', function(done){
			this.timeout(10000);

			scraper.init('http://www.walmart.com/ip/40549455', function(data){

				if(Object.size(data) != 6) throw err;
				done();

			});

		});

	});

});


text:
using System;
using System.Data;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Globalization;

namespace Serenity.Data
{
    public sealed class Int64Field : GenericValueField<Int64>, IIdField
    {
        public Int64Field(ICollection<Field> collection, string name, LocalText caption = null, int size = 0, FieldFlags flags = FieldFlags.Default,
            Func<Row, Int64?> getValue = null, Action<Row, Int64?> setValue = null)
            : base(collection, FieldType.Int64, name, caption, size, flags, getValue, setValue)
        {
        }

        public static Int64Field Factory(ICollection<Field> collection, string name, LocalText caption, int size, FieldFlags flags,
            Func<Row, Int64?> getValue, Action<Row, Int64?> setValue)
        {
            return new Int64Field(collection, name, caption, size, flags, getValue, setValue);
        }

        public override void GetFromReader(IDataReader reader, int index, Row row)
        {
            if (reader == null)
                throw new ArgumentNullException("reader");

            if (reader.IsDBNull(index))
                _setValue(row, null);
            else
                _setValue(row, Convert.ToInt64(reader.GetValue(index), CultureInfo.InvariantCulture));

            if (row.tracking)
                row.FieldAssignedValue(this);
        }

        public override void ValueToJson(JsonWriter writer, Row row, JsonSerializer serializer)
        {
            var value = _getValue(row);
            if (value == null)
                writer.WriteNull();
            else
            {
                var intvalue = value.Value;
                if (intvalue > 9007199254740992 ||
                    intvalue < -9007199254740992)
                    writer.WriteValue(intvalue.ToString(CultureInfo.InvariantCulture));
                else
                    writer.WriteValue(intvalue);
            }
        }

        public override void ValueFromJson(JsonReader reader, Row row, JsonSerializer serializer)
        {
            if (reader == null)
                throw new ArgumentNullException("reader");

            switch (reader.TokenType)
            {
                case JsonToken.Null:
                case JsonToken.Undefined:
                    _setValue(row, null);
                    break;
                case JsonToken.Integer:
                case JsonToken.Float:
                case JsonToken.Boolean:
                    var v = Convert.ToInt64(reader.Value, CultureInfo.InvariantCulture);
                    if (EnumType == null)
                        _setValue(row, v);
                    else
                        _setValue(row, Int32Field.ConvertEnumFromInt(EnumType, v));
                    break;
                case JsonToken.String:
                    string s = ((string)reader.Value).TrimToNull();
                    if (s == null)
                        _setValue(row, null);
                    else if (EnumType == null)
                        _setValue(row, Convert.ToInt64(s, CultureInfo.InvariantCulture));
                    else
                        _setValue(row, Int32Field.ConvertEnumFromString(EnumType, s));
                    break;
                default:
                    throw JsonUnexpectedToken(reader);
            }

            if (row.tracking)
                row.FieldAssignedValue(this);
        }

        Int64? IIdField.this[Row row]
        {
            get
            {
                CheckUnassignedRead(row);
                return _getValue(row);
            }
            set
            {
                _setValue(row, value);
                if (row.tracking)
                    row.FieldAssignedValue(this);
            }
        }

        bool IIdField.IsIntegerType
        {
            get { return true; }
        }
    }
}


text:
const Chance = require("chance");

let cache = Object.create(null);

module.exports = {
  get(seed) {
    if (!cache[seed]) {
      cache[seed] = new Chance(seed);
    }
    return cache[seed];
  },
  clear() {
    cache = Object.create(null);
  }
};


text:
C    Copyright(C) 2009-2017 National Technology & Engineering Solutions
C    of Sandia, LLC (NTESS).  Under the terms of Contract DE-NA0003525 with
C    NTESS, the U.S. Government retains certain rights in this software.
C
C    Redistribution and use in source and binary forms, with or without
C    modification, are permitted provided that the following conditions are
C    met:
C
C        * Redistributions of source code must retain the above copyright
C          notice, this list of conditions and the following disclaimer.
C
C        * Redistributions in binary form must reproduce the above
C          copyright notice, this list of conditions and the following
C          disclaimer in the documentation and/or other materials provided
C          with the distribution.
C
C        * Neither the name of NTESS nor the names of its
C          contributors may be used to endorse or promote products derived
C          from this software without specific prior written permission.
C
C    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
C    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
C    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
C    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
C    OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
C    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
C    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
C    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
C    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
C    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
C    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
C=======================================================================
      SUBROUTINE NUMSTR (NNUM, NSIG, RNUM, RSTR, LSTR)
C=======================================================================

C   --*** NUMSTR *** (STRLIB) Convert real numbers to strings
C   --
C   --NUMSTR converts a set of real numbers into a consistent set of
C   --strings.  It will convert to engineering notation with all
C   --exponents the same, if possible.
C   --
C   --Parameters:
C   --   NNUM - IN - the number of real numbers in the set
C   --   NSIG - IN - the maximum number of significant digits, max of 8
C   --   RNUM - IN - the array of real numbers to be converted
C   --   RSTR - OUT - the set of real number strings
C   --   LSTR - OUT - the maximum length of the number strings

C   --Routines Called:
C   --   IENGRX - (included) Get engineering notation exponent

      INTEGER NNUM
      INTEGER NSIG
      REAL RNUM(*)
      CHARACTER*(*) RSTR(*)
      INTEGER LSTR

      CHARACTER*20 BLANKS
      CHARACTER*10 SCRFMT
      CHARACTER*20 SCRSTR
      CHARACTER*20 TMPSTR
      CHARACTER*15 FFMT

C   --Convert all to E notation and find the minimum and maximum exponent
C   --   MINE and MAXE are the minimum and maximum exponents
C   --   ISIGN is the number of digits for the sign
C   --      (0 if all positive, 1 if any number negative)

      BLANKS = ' '

      WRITE (SCRFMT, 10000, IOSTAT=IDUM) NSIG+7, NSIG
10000  FORMAT ('(0PE', I2.2, '.', I2.2, ')')

      ISIGN = 0
      MINE  = 9999
      MINE2 = 9999
      MAXE  = -9999
      MAXES = MAXE
      DO 100 I = 1, NNUM
         IF (RNUM(I) .NE. 0.0) THEN
            WRITE (SCRSTR(1:NSIG+7), SCRFMT, IOSTAT=IDUM) RNUM(I)
            READ (SCRSTR(NSIG+5:NSIG+7), '(I3)', IOSTAT=IDUM) IE
            IF (MINE .GT. IE) MINE2 = MINE
            MINE = MIN (MINE, IE)
            MAXE = MAX (MAXE, IE)
            IF (RNUM(I) .LT. 0.0) THEN
               ISIGN = 1
               MAXES = MAX (MAXES, IE)
            END IF
         END IF
  100 CONTINUE

C   --Correct for one very small number (should be zero)

      IF ((MINE2 .LT. 1000) .AND. ((MINE2 - MINE) .GE. 6)) MINE = MINE2

C   --Handle all zero case

      IF (MINE .GT. MAXE) THEN
         MINE = 0
         MAXE = 0
         MAXES = 0
      END IF

C   --Determine the new exponent NEWEXP (use engineering notation)

      NEWEXP = IENGRX (MAXE, MINE)
      IF (ISIGN .EQ. 1) THEN
         IF (MAX (1, MAXE - NEWEXP) .GT. MAX (1, MAXES - NEWEXP))
     &      ISIGN = 0
      END IF

C   --Check if the numbers can all be sensibly converted to a common exponent

      IF (((MAXE - NEWEXP) .LE. 4)
     &   .AND. ((NEWEXP - MINE) .LE. 2)
     &   .AND. (-MINE .LT. (NSIG - MAXE))) THEN

C      --Determine the new F format
C      --   EXPDIV is the number to divide by to get the number
C      --      without an exponent
C      --   NWHOLE is the number of digits before the decimal
C      --   NFRAC is the number of digits after the decimal
C      --   NTOTAL is the total number of digits
C      --The new exponent is tagged on the end of the F-format number

         EXPDIV = 10.0 ** NEWEXP

         NWHOLE = MAX (1, MAXE - NEWEXP)
         NFRAC = MAX (0, MIN (NEWEXP - MINE + NSIG,
     &      NSIG - (MAXE - NEWEXP)))
         NTOTAL = ISIGN + NWHOLE + 1 + NFRAC
         IF (EXPDIV .NE. 0.0) THEN
            WRITE (FFMT, 10010, IOSTAT=IDUM) NTOTAL, NFRAC
10010        FORMAT ('(F', I2.2, '.', I2.2, ')')
         ELSE
            WRITE (FFMT, 10020, IOSTAT=IDUM) NTOTAL
10020        FORMAT ('(A', I2.2, 3X, ')')
         END IF

         IF (NEWEXP .EQ. 0) THEN
            LSTR = NTOTAL
         ELSE IF ((NEWEXP .LE. -10) .OR. (NEWEXP .GE. 10)) THEN
            WRITE (FFMT(8:15), 10030, IOSTAT=IDUM) NEWEXP
10030        FORMAT (',''E', SP, I3.2, ''')')
            LSTR = NTOTAL + 4
         ELSE
            WRITE (FFMT(8:15), 10040, IOSTAT=IDUM) NEWEXP
10040        FORMAT (',''E', SP, I2.1, ''')')
            LSTR = NTOTAL + 3
         END IF

C      --Convert all numbers to the new exponent by using the F format

         IF (EXPDIV .NE. 0.0) THEN
            DO 110 I = 1, NNUM
               WRITE (RSTR(I), FFMT, IOSTAT=IDUM) RNUM(I)/EXPDIV
               if (rstr(i)(:1) .eq. '*') then
C ... Roundoff occurred. Adjust format and try again...
                  IF (EXPDIV .NE. 0.0) THEN
                     WRITE (FFMT(:7), 10010, IOSTAT=IDUM) NTOTAL,
     $                    NFRAC-1
                     WRITE (RSTR(I), FFMT, IOSTAT=IDUM) RNUM(I)/EXPDIV
                  end if
               end if
 110           CONTINUE
         ELSE
            DO 120 I = 1, NNUM
               WRITE (RSTR(I), FFMT, IOSTAT=IDUM) '********************'
  120       CONTINUE
         END IF

      ELSE

C      --Do not try to use a common exponent, but use engineering notation;
C      --Algorithm as above

         LSTR = 0
         MINEXP = IENGRX (MINE, MINE)
         MAXEXP = IENGRX (MAXE, MAXE)

         DO 130 I = 1, NNUM
            WRITE (SCRSTR(1:NSIG+7), SCRFMT, IOSTAT=IDUM) RNUM(I)
            READ (SCRSTR(NSIG+5:NSIG+7), '(I3)', IOSTAT=IDUM) IE
            ISIGN = 0
            IF (RNUM(I) .LT. 0.0) ISIGN = 1

            NEWEXP = IENGRX (IE, IE)

            EXPDIV = 10.0 ** NEWEXP

            NWHOLE = MAX (1, IE - NEWEXP)
            NFRAC = MAX (0, MIN (NEWEXP - IE + NSIG,
     &         NSIG - (IE - NEWEXP)))
            IF ((RNUM(I) .EQ. 0.0) .AND. (MINE .GE. 0))
     &         NFRAC = NFRAC - 1
            NTOTAL = ISIGN + NWHOLE + 1 + NFRAC
            IF (EXPDIV .NE. 0.0) THEN
               WRITE (FFMT, 10010, IOSTAT=IDUM) NTOTAL, NFRAC
            ELSE
               WRITE (FFMT, 10020, IOSTAT=IDUM) NTOTAL
            END IF

            IF ((MINEXP .LE. -10) .OR. (MAXEXP .GE. 10)) THEN
               WRITE (FFMT(8:15), 10030, IOSTAT=IDUM) NEWEXP
               LSTR = MAX (LSTR, NTOTAL + 4)
            ELSE
               WRITE (FFMT(8:15), 10040, IOSTAT=IDUM) NEWEXP
               LSTR = MAX (LSTR, NTOTAL + 3)
            END IF

            IF (EXPDIV .NE. 0.0) THEN
               WRITE (RSTR(I), FFMT, IOSTAT=IDUM) RNUM(I)/EXPDIV
               if (rstr(i)(:1) .eq. '*') then
C ... Roundoff occurred. Adjust format and try again...
                  IF (EXPDIV .NE. 0.0) THEN
                     WRITE (FFMT(:7), 10010, IOSTAT=IDUM) NTOTAL,
     $                    NFRAC-1
                     WRITE (RSTR(I), FFMT, IOSTAT=IDUM) RNUM(I)/EXPDIV
                  end if
               end if
            ELSE
               WRITE (RSTR(I), FFMT, IOSTAT=IDUM) '********************'
            END IF
  130    CONTINUE

C      --Adjust the strings so that they are right-justified at
C      --a common length

         DO 140 I = 1, NNUM
            IB = INDEX (RSTR(I)(:LSTR), ' ')
            IF (IB .GT. 0) THEN
               NB = LSTR - IB + 1
               TMPSTR = RSTR(I)(:IB-1)
               RSTR(I) = BLANKS(:NB) // TMPSTR
            END IF
  140    CONTINUE

      END IF

      RETURN
      END


text:
"""
Dropbox file system and targets based on the GFAL file interface.
"""

__all__ = ["DropboxFileSystem", "DropboxTarget", "DropboxFileTarget", "DropboxDirectoryTarget"]

import six

import law
from law.config import Config
from law.target.remote import (
    RemoteFileSystem, RemoteTarget, RemoteFileTarget, RemoteDirectoryTarget,
)
from law.logger import get_logger

logger = get_logger(__name__)

law.contrib.load("gfal")

class DropboxFileSystem(RemoteFileSystem):

    file_interface_cls = law.gfal.GFALFileInterface

    @classmethod
    def parse_config(cls, section, config=None, overwrite=False):
        config = super(DropboxFileSystem, cls).parse_config(section, config=config,
            overwrite=overwrite)

        cfg = Config.instance()

        # helper to add a config value if it exists, extracted with a config parser method
        def add(option, func, prefix="dropbox_"):
            if option not in config or overwrite:
                config[option] = func(section, prefix + option)

        # app key
        add("app_key", cfg.get_expanded)

        # app secret
        add("app_secret", cfg.get_expanded)

        # access token
        add("access_token", cfg.get_expanded)

        return config

    def __init__(self, section=None, app_key=None, app_secret=None, access_token=None, **kwargs):
        # read configs from section and combine them with kwargs to get the file system and
        # file interface configs
        section, fs_config, fi_config = self._init_configs(section, "default_dropbox_fs",
            "dropbox_fs", kwargs)

        # store the config section
        self.config_section = section

        # overwrite dropbox credentials with passed values
        if app_key:
            fs_config["app_key"] = app_key
        if app_secret:
            fs_config["app_secret"] = app_secret
        if access_token:
            fs_config["access_token"] = access_token

        # base path, app key, app secret and access token are mandatory
        msg = ("attribute '{{0}}' must not be empty, set it either directly in the {} constructor, "
            "or add the option '{{0}}' to your config section '{}'".format(
                self.__class__.__name__, self.config_section))
        if not fi_config.get("base"):
            raise Exception(msg.format("base"))
        for attr in ["app_key", "app_secret", "access_token"]:
            if not fs_config.get(attr):
                raise Exception(msg.format(attr))

        # enforce some configs
        fs_config["has_permissions"] = False

        # pass dropbox credentials via gfal options
        gfal_options = fi_config.setdefault("gfal_options", {})
        gfal_options.setdefault("integer", []).append(("DROPBOX", "OAUTH", 2))
        gfal_options.setdefault("string", []).extend([
            ("DROPBOX", "APP_KEY", str(fs_config.pop("app_key"))),
            ("DROPBOX", "APP_SECRET", str(fs_config.pop("app_secret"))),
            ("DROPBOX", "ACCESS_TOKEN", str(fs_config.pop("access_token"))),
        ])

        # create the file interface
        file_interface = self.file_interface_cls(**fi_config)

        # initialize the file system itself
        super(DropboxFileSystem, self).__init__(file_interface, **fs_config)

# try to set the default fs instance
try:
    DropboxFileSystem.default_instance = DropboxFileSystem()
    logger.debug("created default DropboxFileSystem instance '{}'".format(
        DropboxFileSystem.default_instance))
except Exception as e:
    logger.warning("could not create default DropboxFileSystem instance: {}".format(e))

class DropboxTarget(RemoteTarget):
    """ __init__(path, fs=DropboxFileSystem.default_instance, **kwargs)
    """

    def __init__(self, path, fs=DropboxFileSystem.default_instance, **kwargs):
        if fs is None:
            fs = DropboxFileSystem.default_instance
        elif isinstance(fs, six.string_types):
            fs = DropboxFileSystem(fs)
        RemoteTarget.__init__(self, path, fs, **kwargs)

class DropboxFileTarget(DropboxTarget, RemoteFileTarget):

    pass

class DropboxDirectoryTarget(DropboxTarget, RemoteDirectoryTarget):

    pass

DropboxTarget.file_class = DropboxFileTarget
DropboxTarget.directory_class = DropboxDirectoryTarget


text:
package com.tilioteo.common.event;

import com.vaadin.ui.Component;

import java.util.Date;

public abstract class TimekeepingComponentEvent extends Component.Event {
    private final long clientTimestamp;
    private final Date serverTimestamp = new Date();

    protected TimekeepingComponentEvent(long timestamp, Component source) {
        super(source);
        this.clientTimestamp = timestamp;
    }

    public long getTimestamp() {
        return this.clientTimestamp;
    }

    public Date getClientDatetime() {
        return new Date(this.clientTimestamp);
    }

    public long getServerTimestamp() {
        return this.serverTimestamp.getTime();
    }

    public Date getServerDatetime() {
        return this.serverTimestamp;
    }
}


text:
/**
 * Created by kaicui on 17/8/5.
 */

var _hasProp = Object.prototype.hasOwnProperty;
/**
 * 定义类
 * @param metaData:{constructor,prototype,super}
 * @param base
 * @private
 */
var F = function () {};//proxy object's constructor
function _defineClass(metaData){
    if(metaData === undefined) return undefined;
    if(_hasProp.call(metaData,"constructor")){
        var cons = metaData["constructor"],
            realCons=cons;
        //如果是继承,则添加中介对象
        if(_hasProp.call(metaData,"super")){
            var parentClass = metaData["super"];
            if(parentClass !== undefined){
                F.prototype = parentClass.prototype;
                realCons = function(){
                    parentClass.apply(this,[].slice.call(arguments));//call parent to initial instance properties
                    cons.apply(this,[].slice.call(arguments));//then call sub
                    return this;
                }

                realCons.prototype = new F();
                realCons.prototype.constructor = realCons;//设置constructor指向构造函数
                //add by kaicui 2015-02-10(保留基类的prototype,方便调用基类方法)
                realCons.__supperClassProto__ = parentClass.prototype;
            }
        }

        if(_hasProp.call(metaData,"prototype")){
            for(i in metaData["prototype"]){
                realCons.prototype[i] = metaData["prototype"][i]
            }
        }

        return realCons;
    }else{
        throw new Error("must have constructor!")
    }
}

module.exports= {
    defineClass:_defineClass,
    getSupper:function(classRef){

        if(typeof  classRef ==='function'){
            return classRef.__supperClassProto__ ;
        }
        if(typeof  classRef ==='object'){
            return classRef.constructor.__supperClassProto__ ;
        }
    }
}


text:
<!DOCTYPE HTML>

		<meta http-equiv="Content-Type" content="html/html; charset=utf-8" />
		<title>EXTMultiObject Class Reference</title>
		<meta id="xcode-display" name="xcode-display" content="render"/>
		<meta name="viewport" content="width=550" />
		<link rel="stylesheet" type="text/css" href="../css/styles.css" media="all" />
		<link rel="stylesheet" type="text/css" media="print" href="../css/stylesPrint.css" />
		<meta name="generator" content="appledoc 2.1 (build 840)" />

libextobjc 0.2.5

				Justin Spahr-Summers

EXTMultiObject Class Reference

					<button aria-label="Show Table of Contents" role="checkbox" class="open" id="table_of_contents">Table of Contents</button>

					<select id="jumpTo">
	<option value="top">Jump To…</option>

	<option value="overview">Overview</option>

	<option value="tasks">Tasks</option>

	<option value="class_methods">Class Methods</option>

	<option value="//api/name/multiObjectForObjects:">    + multiObjectForObjects:</option>

	<option value="//api/name/multiObjectForObjectsInArray:">    + multiObjectForObjectsInArray:</option>

</select>

Overview

Tasks

Class Methods

multiObjectForObjects:

multiObjectForObjectsInArray:

Index

Hierarchy

EXTMultiObject Class Reference

	Inherits from
	NSObject

	Declared in
	EXTMultiObject.h

Overview

Functions as a proxy for one or more other objects of any class and forwards
each message to the first proxied object that responds to it. This does not send
every message to each target, with some exceptions for reflection functionality
within the \c NSObject protocol. The result is dynamism very much like multiple
inheritance.

Note: To avoid warnings about static typing, refer to instances of this class as
\c id or using one of the classes being proxied.

Tasks

		+ multiObjectForObjects:

Returns an autoreleased object that will selectively dispatch messages to the provided
objects as they are received. The order of the objects in the argument list
determines the order in which method lookup and dispatch occurs.

		+ multiObjectForObjectsInArray:

Returns an autoreleased object that will selectively dispatch messages to the provided
objects as they are received. The order of the objects in the array determines
the order in which method lookup and dispatch occurs.

Class Methods

multiObjectForObjects:

Returns an autoreleased object that will selectively dispatch messages to the provided
objects as they are received. The order of the objects in the argument list
determines the order in which method lookup and dispatch occurs.

+ (id)multiObjectForObjects:(id)firstObj, ...

Discussion

Returns an autoreleased object that will selectively dispatch messages to the provided
objects as they are received. The order of the objects in the argument list
determines the order in which method lookup and dispatch occurs.

Note: All provided objects are retained until the returned object is deallocated.

Declared In

		EXTMultiObject.h

multiObjectForObjectsInArray:

Returns an autoreleased object that will selectively dispatch messages to the provided
objects as they are received. The order of the objects in the array determines
the order in which method lookup and dispatch occurs.

+ (id)multiObjectForObjectsInArray:(NSArray *)objects

Discussion

Returns an autoreleased object that will selectively dispatch messages to the provided
objects as they are received. The order of the objects in the array determines
the order in which method lookup and dispatch occurs.

Note: All provided objects are retained until the returned object is deallocated.

Declared In

		EXTMultiObject.h

Index

Hierarchy

© 2013 Justin Spahr-Summers. All rights reserved. (Last updated: 2013-02-10)

						Generated by appledoc 2.1 (build 840).


text:
#include BOSS_WEBRTC_U_modules__audio_coding__neteq__rtcp_h //original-code:"modules/audio_coding/neteq/rtcp.h"

#include <stdlib.h>
#include <string.h>

#include <algorithm>

namespace webrtc {

void Rtcp::Init(uint16_t start_sequence_number) {
  cycles_ = 0;
  max_seq_no_ = start_sequence_number;
  base_seq_no_ = start_sequence_number;
  received_packets_ = 0;
  received_packets_prior_ = 0;
  expected_prior_ = 0;
  jitter_ = 0;
  transit_ = 0;
}

void Rtcp::Update(const RTPHeader& rtp_header, uint32_t receive_timestamp) {
  // Update number of received packets, and largest packet number received.
  received_packets_++;
  int16_t sn_diff = rtp_header.sequenceNumber - max_seq_no_;
  if (sn_diff >= 0) {
    if (rtp_header.sequenceNumber < max_seq_no_) {
      // Wrap-around detected.
      cycles_++;
    }
    max_seq_no_ = rtp_header.sequenceNumber;
  }

  // Calculate jitter according to RFC 3550, and update previous timestamps.
  // Note that the value in |jitter_| is in Q4.
  if (received_packets_ > 1) {
    int32_t ts_diff = receive_timestamp - (rtp_header.timestamp - transit_);
    int64_t jitter_diff = (std::abs(int64_t{ts_diff}) << 4) - jitter_;
    // Calculate 15 * jitter_ / 16 + jitter_diff / 16 (with proper rounding).
    jitter_ = jitter_ + ((jitter_diff + 8) >> 4);
    RTC_DCHECK_GE(jitter_, 0);
  }
  transit_ = rtp_header.timestamp - receive_timestamp;
}

void Rtcp::GetStatistics(bool no_reset, RtcpStatistics* stats) {
  // Extended highest sequence number received.
  stats->extended_highest_sequence_number =
      (static_cast<int>(cycles_) << 16) + max_seq_no_;

  // Calculate expected number of packets and compare it with the number of
  // packets that were actually received. The cumulative number of lost packets
  // can be extracted.
  uint32_t expected_packets =
      stats->extended_highest_sequence_number - base_seq_no_ + 1;
  if (received_packets_ == 0) {
    // No packets received, assume none lost.
    stats->packets_lost = 0;
  } else if (expected_packets > received_packets_) {
    stats->packets_lost = expected_packets - received_packets_;
    if (stats->packets_lost > 0xFFFFFF) {
      stats->packets_lost = 0xFFFFFF;
    }
  } else {
    stats->packets_lost = 0;
  }

  // Fraction lost since last report.
  uint32_t expected_since_last = expected_packets - expected_prior_;
  uint32_t received_since_last = received_packets_ - received_packets_prior_;
  if (!no_reset) {
    expected_prior_ = expected_packets;
    received_packets_prior_ = received_packets_;
  }
  int32_t lost = expected_since_last - received_since_last;
  if (expected_since_last == 0 || lost <= 0 || received_packets_ == 0) {
    stats->fraction_lost = 0;
  } else {
    stats->fraction_lost = std::min(0xFFU, (lost << 8) / expected_since_last);
  }

  stats->jitter = jitter_ >> 4;  // Scaling from Q4.
}

}  // namespace webrtc


text:
package org.apache.ignite.tests.p2p;

import org.apache.ignite.*;
import org.apache.ignite.cluster.*;
import org.apache.ignite.compute.*;
import org.apache.ignite.internal.util.typedef.*;
import org.apache.ignite.resources.*;
import org.jetbrains.annotations.*;

import java.util.*;

/**
 * Test task for {@code GridCacheDeploymentSelfTest}.
 */
public class CacheDeploymentTestTask1 extends ComputeTaskAdapter<ClusterNode, Object> {
    /** Number of puts. */
    private static final int PUT_CNT = 100;

    /** {@inheritDoc} */
    @Override public Map<? extends ComputeJob, ClusterNode> map(List<ClusterNode> subgrid,
        @Nullable ClusterNode node) {
        return F.asMap(
            new ComputeJobAdapter() {
                @IgniteInstanceResource
                private Ignite ignite;

                @Override public Object execute() {
                    X.println("Executing CacheDeploymentTestTask1 job on node " +
                        ignite.cluster().localNode().id());

                    IgniteCache<String, CacheDeploymentTestValue> cache = ignite.jcache(null);

                    for (int i = 0; i < PUT_CNT; i++)
                        cache.put("1" + i, new CacheDeploymentTestValue());

                    return null;
                }
            },
            node
        );
    }

    /** {@inheritDoc} */
    @Nullable @Override public Object reduce(List<ComputeJobResult> results) {
        return null;
    }
}


text:
<?php
// show potential errors / feedback (from login object)
if (isset($login)) {
    if ($login->errors) {
        foreach ($login->errors as $error) {
            echo $error;
        }
    }
    if ($login->messages) {
        foreach ($login->messages as $message) {
            echo $message;
        }
    }
}
?>

<form method="post" action="index.php" name="loginform">

    Email :
    <input id="login_input_email" class="login_input" type="text" name="user_email" required />

    Password :
    <input id="login_input_password" class="login_input" type="password" name="user_password" autocomplete="off" required />

    <input type="submit"  name="login" value="Log in" />

</form>

Register new account


text:
from toontown.toonbase import TTLocalizer
from toontown.parties.DistributedPartyCatchActivity import DistributedPartyCatchActivity
from toontown.parties import PartyGlobals
from toontown.parties import WinterPartyCatchActivityToonSD

class DistributedPartyWinterCatchActivity(DistributedPartyCatchActivity):

    def __init__(self, cr):
        DistributedPartyCatchActivity.__init__(self, cr)

    def getInstructions(self):
        return TTLocalizer.WinterPartyCatchActivityInstructions % {'badThing': self.DropObjectPlurals['anvil']}

    def load(self):
        DistributedPartyCatchActivity.load(self, loadModels=0, arenaModel='tt_m_ara_pty_partyCatchTreeWinter')
        self.__loadDropModels()

    def __loadDropModels(self):
        for objType in PartyGlobals.DropObjectTypes:
            model = None
            if not objType == PartyGlobals.Name2DropObjectType['anvil']:
                model = loader.loadModel('phase_13/models/parties/tt_m_ara_pty_winterPresent')
                model.setScale(0.5)
            else:
                model = loader.loadModel(objType.modelPath)
            self.dropObjModels[objType.name] = model
            model.flattenStrong()

        return

    def handleToonJoined(self, toonId):
        if toonId not in self.toonSDs:
            toonSD = WinterPartyCatchActivityToonSD.WinterPartyCatchActivityToonSD(toonId, self)
            self.toonSDs[toonId] = toonSD
            toonSD.load()
        self.notify.debug('handleToonJoined : currentState = %s' % self.activityFSM.state)
        if self.activityFSM.state == 'Active':
            if toonId in self.toonSDs:
                self.toonSDs[toonId].enter()
            if base.localAvatar.doId == toonId:
                base.localAvatar.b_setParent(self._avatarNodePathParentToken)
                self.putLocalAvatarInActivity()
            if toonId in self.toonSDs:
                self.toonSDs[toonId].fsm.request('rules')


text:
package org.wso2.siddhi.core.stream.output.sink.distributed;

import org.wso2.siddhi.core.util.config.ConfigReader;
import org.wso2.siddhi.core.util.transport.DynamicOptions;
import org.wso2.siddhi.core.util.transport.OptionHolder;
import org.wso2.siddhi.query.api.definition.StreamDefinition;
import org.wso2.siddhi.query.api.exception.SiddhiAppValidationException;

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

/**
 * Parent class for the Distributed publishing strategy extensions. Note that destinationId of the each
 * destination is implied by the order which @destination annotations appear in @sink annotation. Therefore, when
 * implementing a strategy, if the implementation wants refer to a certain @destination the ID can be derived by
 * looking at the listing order of @destination
 */
public abstract class DistributionStrategy {

    static final List<Integer> EMPTY_RETURN_VALUE = new ArrayList<>();
    List<Integer> activeDestinationIds = new ArrayList<>();

    /**
     * Initialize the Distribution strategy with the information it will require to make decisions.
     *
     * @param streamDefinition         The stream attached to the sink this DistributionStrategy is used in
     * @param transportOptionHolder    Sink options of the sink which uses this DistributionStrategy
     * @param distributionOptionHolder The option under @destination of the relevant sink.
     * @param destinationOptionHolders The list of options under @destination of the relevant sink.
     * @param configReader             This hold the {@link DistributionStrategy} extensions configuration reader.
     */
    public abstract void init(StreamDefinition streamDefinition, OptionHolder transportOptionHolder, OptionHolder
            distributionOptionHolder, List<OptionHolder> destinationOptionHolders, ConfigReader configReader);

    /**
     * This method tells the ID(s) of the destination(s) to which a given messages should be sent. There can be cases
     * where a given message is only sent to a specific destination(e.g., partition based) and message is sent to
     * multiple endpoints(e.g., broadcast)
     *
     * @param payload          payload of the message
     * @param transportOptions Dynamic transport options of the sink
     * @return Set of IDs of the destination to which the event should be sent
     */
    public abstract List<Integer> getDestinationsToPublish(Object payload, DynamicOptions transportOptions);

    /**
     * Remove a given destination from available set of destination IDs. Once this method is called for a given
     * destination ID, that particular destination ID will not included in the return value of subsequent
     * getDestinationsToPublish() is calls
     *
     * @param destinationId the ID of the destination to be removed
     */
    public synchronized void destinationFailed(Integer destinationId) {
        ArrayList<Integer> newDestinationIds = new ArrayList<>(activeDestinationIds);
        newDestinationIds.remove(destinationId);
        activeDestinationIds = newDestinationIds;
    }

    /**
     * Remove a destination to available set of destination IDs. Once this method is called for a given
     * destination ID, that particular destination ID will be considered when getDestinationsToPublish() is called
     *
     * @param destinationId the ID of the destination to be check for availability.
     */
    public synchronized void destinationAvailable(Integer destinationId) {
        if (activeDestinationIds.contains(destinationId)) {
            throw new SiddhiAppValidationException("Destination ID " + destinationId + " already registered");
        }

        ArrayList<Integer> newDestinationIds = new ArrayList<>(activeDestinationIds);
        newDestinationIds.add(destinationId);
        //Destination IDs are implied by the order they appear in @sink annotation. i.e, the first @desination appear
        // is assigned ID 0 and the second is assigned 1 and so on. IDs are not changed once assigned. Therefore,
        // sorting the Ids once a new ID is added to keep the IDs in the same order as their respective @destination
        // annotations are listed
        Collections.sort(newDestinationIds);
        activeDestinationIds = newDestinationIds;
    }

    /**
     * Get the active number of destinations
     *
     * @return The active number of destinations
     */
    public synchronized int getActiveDestinationCount() {
        return activeDestinationIds.size();
    }

}


text:
<?php
/**
 * Created by PhpStorm.
 * User: gueno
 * Date: 06/12/2017
 * Time: 17:45
 */

namespace MI\BilletterieBundle\Entity;

class CommandeTest extends \PHPUnit_Framework_TestCase
{
    private $Commande;

    public function __construct()
    {
        parent::__construct();
        $this->Commande = new Commande();
    }

    public function testCommandeDate()
    {
       $this->Commande->setDateEntree(new \DateTime('06/12/2017'));
       $this->assertNotEquals(new \DateTime('08/12/2017'), $this->Commande->getDateEntree());
       $this->assertEquals(new \DateTime('06/12/2017'), $this->Commande->getDateEntree());
    }

    public function testCommandeType()
    {
        $this->Commande->setType('journée');
        $this->assertNotEquals('Demi-journée', $this->Commande->getType());
        $this->assertEquals('journée', $this->Commande->getType());
    }

    public function testCommandeNbBillet()
    {
        $this->Commande->setNbBillet('3');
        $this->assertNotEquals('5', $this->Commande->getNbBillet());
        $this->assertEquals('3', $this->Commande->getNbBillet());
    }
}


text:
require 'erb'
require 'yaml'

module TwitterCldr
  module Resources

    ReadmeAssertionFailure = Struct.new(:message, :line_number)

    class ReadmeRenderer
      attr_reader :text, :assertion_failures

      def initialize(text)
        @text = text
        @assertion_failures = []
      end

      def render
        ERB.new(text).result(binding)
      end

      def datetime
        @datetime ||= DateTime.new(2014, 2, 14, 12, 20, 5, 0)
      end

      def time
        @time ||= Time.gm(2014, 2, 14, 12, 20, 5, 0)
      end

      private

      def assert(got, expected)
        if got.is_a?(String) && expected.is_a?(String)
          got = got.localize.normalize(using: :NFKC).to_s
          expected = expected.localize.normalize(using: :NFKC).to_s
        end

        unless objs_equal?(got, expected)
          line_num = line_num_from_stack_trace(Kernel.caller)
          assertion_failures << ReadmeAssertionFailure.new(
            "Expected `#{got.inspect}` to be `#{expected.inspect}` in README on line #{line_num}",
            line_num
          )
        end

        got
      end

      def objs_equal?(obj1, obj2)
        case obj1
          when Array
            obj1 - obj2 == []
          else
            obj1 == obj2
        end
      end

      def assert_true(got)
        assert(got, true)
      end

      def assert_false(got)
        assert(got, false)
      end

      def assert_no_error(proc)
        error = nil
        begin
          proc.call
        rescue => e
          line_num = line_num_from_stack_trace(Kernel.caller)
          assertion_failures << ReadmeAssertionFailure.new(
            "Expected README line #{line_num} not to raise an exception, but it did:\n#{e.message}\n#{e.backtrace.join("\n")}",
            line_num
          )
        end
      end

      def line_num_from_stack_trace(trace)
        trace[0].split(":")[1].to_i  # kind of a hack...
      end

      def ellipsize(obj)
        case obj
          when Array
            "[#{obj.map(&:inspect).join(", ")}, ... ]"
          when Hash
            hash_text = obj.map { |key, val| "#{key.inspect} => #{val.inspect}" }.join(", ")
            "{ ... #{hash_text} ... }"
        end
      end

      def slice_hash(hash, keys)
        hash.inject({}) do |ret, (key, val)|
          ret[key] = val if keys.include?(key)
          ret
        end
      end

      def tested_ruby_versions
        workflow = YAML.load_file(File.join(*%w(.github workflows unit_tests.yml)))
        workflow["jobs"]["build"]["strategy"]["matrix"]["ruby-version"].join(", ")
      end
    end

  end
end


text:
from tabulate import tabulate

from meta_graph_stat import MetaGraphStat

def summary(events, tablefmt, summary_kws):
    date_format = '%Y-%m-%d'

    table = []
    for i, e in enumerate(events):
        d = MetaGraphStat(e, summary_kws).summary_dict()
        row = ["**#{},**".format(i+1),
               d['basic_structure_stats']['#nodes'],
               "{} {}".format(
                   d['time_span']['start_time'].strftime(date_format),
                   d['time_span']['end_time'].strftime(date_format)
               ),
               # next(s for s in  d['email_content']['subjects(top5)'] if s),  # get first non-empty
               '\n'.join(d['email_content']['subjects(top5)']),
               ' '.join(d['topics']['topic_terms'])
           ]
        table.append(row)
    return tabulate(table, headers=["", "#nodes", "time",
                                    "subject(root)", "terms"],
                    tablefmt=tablefmt)


text:
layout: post
authors: [meren]
title: "Frontiers in Microbiology Special Topic"
excerpt: "A special topic for oligotyping"
modified: 2013-12-12
tags: [frontiers, pubs]
categories: [oligotyping]
comments: true
---

I am very pleased to announce that Frontiers in Microbiology is now hosting a research topic on oligotyping, which is open for submissions! Please visit the research topic page, "[New insights into microbial ecology through subtle nucleotide variation](http://www.frontiersin.org/systems_microbiology/researchtopics/new_insights_into_microbial_ec/2427)", for more information.

I will be editing this research topic with [Loïs Maignien](http://www.mendeley.com/profiles/lois-maignien/) (University of Western Brittany), and [Mitchell L. Sogin](http://www.mbl.edu/jbpc/faculty/mitchell-sogin/) (Marine Biological Laboratory).

Scope is very flexible. We will consider any submission that uses oligotyping: it could be a study that shows its advantages or caveats over canonical approaches, highlights novel findings through the use of oligotyping, or it could be a perspective that discusses why it may be important or misleading to rely on subtle nucleotide variations to make sense of microbial community data.

If you have a high-throughput sequencing dataset that you would like to revisit with oligotyping, or if you have an idea about the application of oligotyping to amplicon data, or if you have a novel idea no one seems to have thought about yet, you are most welcome to submit an abstract. Please do not hesitate to get in touch with me (via meren at mbl.edu) if you have any questions or comments.

---

[Frontiers](http://frontiersin.org/) is a very progressive publisher with many original ideas to empower researchers and improve the communication of science. I think the interest of Nature Publishing Group in Frontiers partially confirms that. You can read their broad perspective from their [intro page](http://www.frontiersin.org/about), but I especially am very excited about their "research topics". This is what Frontiers says about it:

>Research Topics aim at creating an online dialogue on a focused research area, with manuscripts encompassing recent advancements from various groups, the latest methods, opinions, and more. It is an opportunity for you to highlight your research focus, intensify collaborations and drive the next research in your field.

In a nut shell, research topics allow researchers to be guest editors of a Frontiers journal to put together a collection of peer-reviewed articles that are coherently reflect a grand idea. This could be an emerging method or technology, or a controversial topic of interest. The importance of this missing aspect in today's science publishing is rather obvious, and I am thankful for Frontiers to take a stab at it.

---

The deadline for abstract submission is 15 Mar 2014. I hope this research topic is going to be a gratifying example of how efficient these collections can be.


text:
package teams

import "golang.org/x/net/context"

type ctxKeyType string

const ctxKeySuppressLogging = ctxKeyType("sl")

func ShouldSuppressLogging(ctx context.Context) bool {
	v, _ := ctx.Value(ctxKeySuppressLogging).(bool)
	return v
}

func WithSuppressLogging(ctx context.Context, suppress bool) context.Context {
	return context.WithValue(ctx, ctxKeySuppressLogging, suppress)
}


text:
title: First post to her
layout: post
category: his
---

It has been five days since I came to Germany, it is not first time living abroad neither the first time having a long distance relationship. However, it is still hard not to miss her, it doesn't mean that I don't want to, but it just hurts and I know that it's okay but still.
I love her, I am 100% commitment to this relationship, I do really have faith in us. We are not anymore the stupid kids we were... we are still doing stupid things but we are more mature.

It is cold here, and I feel lonely sometimes... I am still wearing the scarf she gave me, it feels as she were here hugging and protecting me. Suddenly, the weather doesn't feel that cold and I don't feel alone anymore .

I love her, I really do. We have been together for a short time, but the quality of the time we spent together was high. I feel really connected to her, we are similar in several aspects and we share ideas that I think are  important for a long term relationship. She knows what I am talking about. However, I can say that the most important thing for me is that she is open minded, physically strong, independent and very intelligent, I believe that she is way smarter than me... and that's okay. And of course, she is the most sexiest woman I have ever met (I may jizz in my pants).

These last five days we have been talking a lot, online and offline, she also wrote me everyday. Somehow, it feels really good when I read her messages and letters, maybe it is because I feel as she were here with me talking to me.

Everything is gonna be alright!


text:
package api

import (
	"encoding/json"
	"fmt"
	"net"
	"net/http"
	"strconv"
	"strings"
	"testing"

	"net/url"

	"sort"

	"github.com/gorilla/mux"
	"github.com/tsuru/config"
	"github.com/tsuru/tsuru/db"
	"github.com/tsuru/tsuru/db/dbtest"
	tsuruNet "github.com/tsuru/tsuru/net"
	"github.com/tsuru/tsuru/router"
	"github.com/tsuru/tsuru/router/routertest"
	check "gopkg.in/check.v1"
)

func Test(t *testing.T) {
	check.TestingT(t)
}

type S struct {
	apiRouter  *fakeRouterAPI
	testRouter *apiRouter
}

var _ = check.Suite(&S{})

func init() {
	suite := &routertest.RouterSuite{}
	var r *fakeRouterAPI
	suite.SetUpTestFunc = func(c *check.C) {
		r = newFakeRouter(c)
		r.router.HandleFunc("/support/{feature}", func(http.ResponseWriter, *http.Request) {
		})
		config.Set("routers:apirouter:api-url", r.endpoint)
		config.Set("database:name", "router_api_tests")
		r.backends = make(map[string]*backend)
		apiRouter, err := createRouter("api", "routers:apirouter")
		c.Assert(err, check.IsNil)
		suite.Router = apiRouter
	}
	suite.TearDownTestFunc = func(c *check.C) {
		r.stop()
		config.Unset("routers:apirouter")
		conn, err := db.Conn()
		c.Assert(err, check.IsNil)
		defer conn.Close()
		dbtest.ClearAllCollections(conn.Collection("router_api_tests").Database)
	}
	check.Suite(suite)
}

func (s *S) SetUpTest(c *check.C) {
	s.apiRouter = newFakeRouter(c)
	s.apiRouter.certificates = make(map[string]certData)
	s.testRouter = &apiRouter{
		endpoint:   s.apiRouter.endpoint,
		client:     tsuruNet.Dial5Full60ClientNoKeepAlive,
		routerName: "apirouter",
	}
	config.Set("routers:apirouter:api-url", s.apiRouter.endpoint)
	config.Set("database:name", "router_api_tests")
	s.apiRouter.backends = make(map[string]*backend)
	s.testRouter.AddBackend("mybackend")
	s.apiRouter.backends = map[string]*backend{
		"mybackend": {addr: "mybackend.cloud.com", addresses: []string{"http://127.0.0.1:32876", "http://127.0.0.1:32678"}},
	}
}

func (s *S) TearDownTest(c *check.C) {
	config.Unset("routers:apirouter")
	conn, err := db.Conn()
	c.Assert(err, check.IsNil)
	defer conn.Close()
	dbtest.ClearAllCollections(conn.Collection("router_api_tests").Database)
	s.apiRouter.stop()
}

func (s *S) TestAddr(c *check.C) {
	addr, err := s.testRouter.Addr("mybackend")
	c.Assert(err, check.IsNil)
	c.Assert(addr, check.DeepEquals, "mybackend.cloud.com")
}

func (s *S) TestAddrNotFound(c *check.C) {
	addr, err := s.testRouter.Addr("invalid")
	c.Assert(err, check.DeepEquals, router.ErrBackendNotFound)
	c.Assert(addr, check.DeepEquals, "")
}

func (s *S) TestAddBackend(c *check.C) {
	err := s.testRouter.AddBackend("new-backend")
	c.Assert(err, check.IsNil)
	c.Assert(s.apiRouter.backends["new-backend"], check.NotNil)
}

func (s *S) TestAddBackendOpts(c *check.C) {
	err := s.testRouter.AddBackendOpts("new-backend", map[string]string{"opt1": "val1"})
	c.Assert(err, check.IsNil)
	c.Assert(s.apiRouter.backends["new-backend"].opts, check.DeepEquals, map[string]string{"opt1": "val1"})
}

func (s *S) TestUpdateBackendOpts(c *check.C) {
	err := s.testRouter.AddBackendOpts("new-backend", map[string]string{"opt1": "val1"})
	c.Assert(err, check.IsNil)
	err = s.testRouter.UpdateBackendOpts("new-backend", map[string]string{"opt1": "val2"})
	c.Assert(err, check.IsNil)
	c.Assert(s.apiRouter.backends["new-backend"].opts, check.DeepEquals, map[string]string{"opt1": "val2"})
}

func (s *S) TestAddBackendExists(c *check.C) {
	err := s.testRouter.AddBackend("mybackend")
	c.Assert(err, check.DeepEquals, router.ErrBackendExists)
}

func (s *S) TestRemoveBackend(c *check.C) {
	err := s.testRouter.RemoveBackend("mybackend")
	c.Assert(err, check.IsNil)
	c.Assert(s.apiRouter.backends["mybackend"], check.IsNil)
}

func (s *S) TestRemoveBackendNotFound(c *check.C) {
	err := s.testRouter.RemoveBackend("invalid")
	c.Assert(err, check.DeepEquals, router.ErrBackendNotFound)
}

func (s *S) TestRemoveBackendSwapped(c *check.C) {
	err := s.testRouter.AddBackend("backend2")
	c.Assert(err, check.IsNil)
	err = s.testRouter.Swap("mybackend", "backend2", false)
	c.Assert(err, check.IsNil)
	err = s.testRouter.RemoveBackend("mybackend")
	c.Assert(err, check.DeepEquals, router.ErrBackendSwapped)
}

func (s *S) TestAddRoutes(c *check.C) {
	addr, err := url.Parse("http://127.0.0.1:1234")
	c.Assert(err, check.IsNil)
	err = s.testRouter.AddRoutes("mybackend", []*url.URL{addr})
	c.Assert(err, check.IsNil)
	sort.Strings(s.apiRouter.backends["mybackend"].addresses)
	c.Assert(s.apiRouter.backends["mybackend"].addresses, check.DeepEquals,
		[]string{"http://127.0.0.1:1234", "http://127.0.0.1:32678", "http://127.0.0.1:32876"})
}

func (s *S) TestAddRoutesBackendNotFound(c *check.C) {
	addr, err := url.Parse("http://127.0.0.1:1234")
	c.Assert(err, check.IsNil)
	err = s.testRouter.AddRoutes("invalid", []*url.URL{addr})
	c.Assert(err, check.DeepEquals, router.ErrBackendNotFound)
}

func (s *S) TestRemoveRoute(c *check.C) {
	addr, err := url.Parse("http://127.0.0.1:32678")
	c.Assert(err, check.IsNil)
	err = s.testRouter.RemoveRoutes("mybackend", []*url.URL{addr})
	c.Assert(err, check.IsNil)
	c.Assert(s.apiRouter.backends["mybackend"].addresses, check.DeepEquals,
		[]string{"http://127.0.0.1:32876"})
}

func (s *S) TestRemoveRoutes(c *check.C) {
	addr, err := url.Parse("http://127.0.0.1:32678")
	c.Assert(err, check.IsNil)
	addr2, err := url.Parse("http://127.0.0.1:32876")
	c.Assert(err, check.IsNil)
	err = s.testRouter.RemoveRoutes("mybackend", []*url.URL{addr, addr2})
	c.Assert(err, check.IsNil)
	c.Assert(s.apiRouter.backends["mybackend"].addresses, check.DeepEquals, []string(nil))
}

func (s *S) TestRemoveRoutesBackendNotFound(c *check.C) {
	addr, err := url.Parse("http://127.0.0.1:1234")
	c.Assert(err, check.IsNil)
	err = s.testRouter.RemoveRoutes("invalid", []*url.URL{addr})
	c.Assert(err, check.DeepEquals, router.ErrBackendNotFound)
}

func (s *S) TestGetRoutes(c *check.C) {
	addr, err := url.Parse("http://127.0.0.1:32876")
	c.Assert(err, check.IsNil)
	addr2, err := url.Parse("http://127.0.0.1:32678")
	c.Assert(err, check.IsNil)
	addrs, err := s.testRouter.Routes("mybackend")
	c.Assert(err, check.IsNil)
	c.Assert(addrs, check.DeepEquals, []*url.URL{addr, addr2})
}

func (s *S) TestGetRoutesBackendNotFound(c *check.C) {
	addrs, err := s.testRouter.Routes("invalid")
	c.Assert(err, check.DeepEquals, router.ErrBackendNotFound)
	c.Assert(len(addrs), check.Equals, 0)
}

func (s *S) TestSwap(c *check.C) {
	err := s.testRouter.AddBackend("backend2")
	c.Assert(err, check.IsNil)
	err = s.testRouter.Swap("mybackend", "backend2", true)
	c.Assert(err, check.IsNil)
	c.Assert(s.apiRouter.backends["mybackend"].cnameOnly, check.Equals, true)
	c.Assert(s.apiRouter.backends["mybackend"].swapWith, check.Equals, "backend2")
	err = s.testRouter.Swap("mybackend", "backend2", true)
	c.Assert(err, check.IsNil)
	c.Assert(s.apiRouter.backends["mybackend"].swapWith, check.Equals, "")
}

func (s *S) TestSwapNotFound(c *check.C) {
	err := s.testRouter.Swap("invalid", "backend2", false)
	c.Assert(err, check.DeepEquals, router.ErrBackendNotFound)
}

func (s *S) TestSetCName(c *check.C) {
	cnameRouter := &apiRouterWithCnameSupport{s.testRouter}
	err := cnameRouter.SetCName("cname.com", "mybackend")
	c.Assert(err, check.IsNil)
}

func (s *S) TestSetCNameBackendNotFound(c *check.C) {
	cnameRouter := &apiRouterWithCnameSupport{s.testRouter}
	err := cnameRouter.SetCName("cname.com", "invalid")
	c.Assert(err, check.DeepEquals, router.ErrBackendNotFound)
}

func (s *S) TestSetCNameCNameAlreadyExists(c *check.C) {
	s.apiRouter.backends["mybackend"].cnames = []string{"cname.com"}
	cnameRouter := &apiRouterWithCnameSupport{s.testRouter}
	err := cnameRouter.SetCName("cname.com", "mybackend")
	c.Assert(err, check.DeepEquals, router.ErrCNameExists)
}

func (s *S) TestUnsetCName(c *check.C) {
	s.apiRouter.backends["mybackend"].cnames = []string{"cname.com"}
	cnameRouter := &apiRouterWithCnameSupport{s.testRouter}
	err := cnameRouter.UnsetCName("cname.com", "mybackend")
	c.Assert(err, check.IsNil)
}

func (s *S) TestUnsetCNameBackendNotFound(c *check.C) {
	cnameRouter := &apiRouterWithCnameSupport{s.testRouter}
	err := cnameRouter.UnsetCName("cname.com", "invalid")
	c.Assert(err, check.DeepEquals, router.ErrBackendNotFound)
}

func (s *S) TestUnsetCNameCNameNotFound(c *check.C) {
	cnameRouter := &apiRouterWithCnameSupport{s.testRouter}
	err := cnameRouter.UnsetCName("cname.com", "mybackend")
	c.Assert(err, check.DeepEquals, router.ErrCNameNotFound)
}

func (s *S) TestCNames(c *check.C) {
	s.apiRouter.backends["mybackend"].cnames = []string{"cname.com", "cname2.com"}
	cnameRouter := &apiRouterWithCnameSupport{s.testRouter}
	cnames, err := cnameRouter.CNames("mybackend")
	c.Assert(err, check.IsNil)
	c.Assert(len(cnames), check.Equals, 2)
}

func (s *S) TestCNamesBackendNotFound(c *check.C) {
	cnameRouter := &apiRouterWithCnameSupport{s.testRouter}
	cnames, err := cnameRouter.CNames("invalid")
	c.Assert(err, check.DeepEquals, router.ErrBackendNotFound)
	c.Assert(len(cnames), check.Equals, 0)
}

func (s *S) TestAddCertificate(c *check.C) {
	tlsRouter := &apiRouterWithTLSSupport{s.testRouter}
	err := tlsRouter.AddCertificate("cname.com", "cert", "key")
	c.Assert(err, check.IsNil)
	c.Assert(s.apiRouter.certificates["cname.com"], check.DeepEquals, certData{Certificate: "cert", Key: "key"})
}

func (s *S) TestRemoveCertificate(c *check.C) {
	tlsRouter := &apiRouterWithTLSSupport{s.testRouter}
	err := tlsRouter.AddCertificate("cname.com", "cert", "key")
	c.Assert(err, check.IsNil)
	err = tlsRouter.RemoveCertificate("cname.com")
	c.Assert(err, check.IsNil)
}

func (s *S) TestRemoveCertificateNotFound(c *check.C) {
	tlsRouter := &apiRouterWithTLSSupport{s.testRouter}
	err := tlsRouter.RemoveCertificate("cname.com")
	c.Assert(err, check.DeepEquals, router.ErrCertificateNotFound)
}

func (s *S) TestGetCertificate(c *check.C) {
	tlsRouter := &apiRouterWithTLSSupport{s.testRouter}
	err := tlsRouter.AddCertificate("cname.com", "cert", "key")
	c.Assert(err, check.IsNil)
	cert, err := tlsRouter.GetCertificate("cname.com")
	c.Assert(err, check.IsNil)
	c.Assert(cert, check.DeepEquals, "cert")
}

func (s *S) TestGetCertificateNotFound(c *check.C) {
	tlsRouter := &apiRouterWithTLSSupport{s.testRouter}
	cert, err := tlsRouter.GetCertificate("cname.com")
	c.Assert(err, check.DeepEquals, router.ErrCertificateNotFound)
	c.Assert(cert, check.DeepEquals, "")
}

func (s *S) TestSetHealthcheck(c *check.C) {
	hcRouter := &apiRouterWithHealthcheckSupport{s.testRouter}
	hc := router.HealthcheckData{Path: "/", Status: 200}
	err := hcRouter.SetHealthcheck("mybackend", hc)
	c.Assert(err, check.IsNil)
	c.Assert(s.apiRouter.backends["mybackend"].healthcheck, check.DeepEquals, hc)
}

func (s *S) TestHealcheckBackendNotFound(c *check.C) {
	hcRouter := &apiRouterWithHealthcheckSupport{s.testRouter}
	hc := router.HealthcheckData{Path: "/", Status: 200}
	err := hcRouter.SetHealthcheck("invalid", hc)
	c.Assert(err, check.DeepEquals, router.ErrBackendNotFound)
}

func (s *S) TestCreateRouterSupport(c *check.C) {
	tt := []struct {
		features    map[string]bool
		expectCname bool
		expectTLS   bool
		expectHC    bool
	}{
		{nil, false, false, false},
		{features: map[string]bool{"cname": true}, expectCname: true},
		{features: map[string]bool{"tls": true}, expectTLS: true},
		{features: map[string]bool{"healthcheck": true}, expectHC: true},
		{features: map[string]bool{"cname": true, "tls": true}, expectCname: true, expectTLS: true},
		{features: map[string]bool{"cname": true, "tls": true, "healthcheck": true}, expectCname: true, expectTLS: true, expectHC: true},
		{features: map[string]bool{"cname": true, "healthcheck": true}, expectCname: true, expectHC: true},
		{features: map[string]bool{"tls": true, "healthcheck": true}, expectTLS: true, expectHC: true},
	}
	var i int
	s.apiRouter.router.HandleFunc("/support/{name}", func(w http.ResponseWriter, r *http.Request) {
		f := tt[i]
		v := mux.Vars(r)
		if f.features == nil {
			w.WriteHeader(http.StatusNotFound)
			return
		}
		if b := f.features[v["name"]]; b {
			w.WriteHeader(http.StatusOK)
			return
		}
		w.WriteHeader(http.StatusNotFound)
	})
	for i = range tt {
		comment := check.Commentf("case %d: %v", i, tt[i])
		r, err := createRouter("myrouter", "routers:apirouter")
		c.Assert(err, check.IsNil, comment)
		_, ok := r.(router.CNameRouter)
		c.Assert(ok, check.Equals, tt[i].expectCname, comment)
		_, ok = r.(router.TLSRouter)
		c.Assert(ok, check.Equals, tt[i].expectTLS, comment)
		_, ok = r.(router.CustomHealthcheckRouter)
		c.Assert(ok, check.Equals, tt[i].expectHC, comment)
	}
}

func (s *S) TestCreateCustomHeaders(c *check.C) {
	s.apiRouter.router.HandleFunc("/custom", func(w http.ResponseWriter, r *http.Request) {
		if r.Header.Get("X-CUSTOM") == "" {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
	})
	config.Set("routers:apirouter:headers", map[interface{}]interface{}{"X-CUSTOM": "HI"})
	defer config.Unset("router:apirouter:headers")
	r, err := createRouter("apirouter", "routers:apirouter")
	c.Assert(err, check.IsNil)
	_, code, err := r.(*apiRouter).do(http.MethodGet, "/custom", nil)
	c.Assert(code, check.DeepEquals, http.StatusOK)
	c.Assert(err, check.IsNil)
}

func newFakeRouter(c *check.C) *fakeRouterAPI {
	api := &fakeRouterAPI{}
	r := mux.NewRouter()
	r.HandleFunc("/backend/{name}", api.getBackend).Methods(http.MethodGet)
	r.HandleFunc("/backend/{name}", api.addBackend).Methods(http.MethodPost)
	r.HandleFunc("/backend/{name}", api.updateBackend).Methods(http.MethodPut)
	r.HandleFunc("/backend/{name}", api.removeBackend).Methods(http.MethodDelete)
	r.HandleFunc("/backend/{name}/routes", api.getRoutes).Methods(http.MethodGet)
	r.HandleFunc("/backend/{name}/routes", api.addRoutes).Methods(http.MethodPost)
	r.HandleFunc("/backend/{name}/routes/remove", api.removeRoutes).Methods(http.MethodPost)
	r.HandleFunc("/backend/{name}/swap", api.swap).Methods(http.MethodPost)
	r.HandleFunc("/backend/{name}/cname", api.getCnames).Methods(http.MethodGet)
	r.HandleFunc("/backend/{name}/cname/{cname}", api.setCname).Methods(http.MethodPost)
	r.HandleFunc("/backend/{name}/cname/{cname}", api.unsetCname).Methods(http.MethodDelete)
	r.HandleFunc("/backend/{name}/healthcheck", api.setHealthcheck).Methods(http.MethodPut)
	r.HandleFunc("/certificate/{cname}", api.getCertificate).Methods(http.MethodGet)
	r.HandleFunc("/certificate/{cname}", api.addCertificate).Methods(http.MethodPut)
	r.HandleFunc("/certificate/{cname}", api.removeCertificate).Methods(http.MethodDelete)
	listener, err := net.Listen("tcp", "127.0.0.1:0")
	c.Assert(err, check.IsNil)
	api.listener = listener
	api.endpoint = fmt.Sprintf("http://%s", listener.Addr().String())
	api.router = r
	go http.Serve(listener, r)
	return api
}

type backend struct {
	addr        string
	addresses   []string
	cnames      []string
	swapWith    string
	cnameOnly   bool
	healthcheck router.HealthcheckData
	opts        map[string]string
}

type fakeRouterAPI struct {
	listener     net.Listener
	backends     map[string]*backend
	certificates map[string]certData
	endpoint     string
	router       *mux.Router
}

func (f *fakeRouterAPI) getBackend(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	name := vars["name"]
	backend, ok := f.backends[name]
	if !ok {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	resp := &backendResp{Address: backend.addr}
	json.NewEncoder(w).Encode(resp)
}

func (f *fakeRouterAPI) addBackend(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	name := vars["name"]
	_, ok := f.backends[name]
	if ok {
		w.WriteHeader(http.StatusConflict)
		return
	}
	var req map[string]string
	json.NewDecoder(r.Body).Decode(&req)
	f.backends[name] = &backend{opts: req, addr: name + ".apirouter.com"}
}

func (f *fakeRouterAPI) updateBackend(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	name := vars["name"]
	backend, ok := f.backends[name]
	if !ok {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	var req map[string]string
	json.NewDecoder(r.Body).Decode(&req)
	backend.opts = req
}

func (f *fakeRouterAPI) removeBackend(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	name := vars["name"]
	backend, ok := f.backends[name]
	if !ok {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	if backend.swapWith != "" {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte(router.ErrBackendSwapped.Error()))
		return
	}
	delete(f.backends, name)
}

func (f *fakeRouterAPI) getRoutes(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	name := vars["name"]
	backend, ok := f.backends[name]
	if !ok {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	resp := &routesReq{}
	resp.Addresses = backend.addresses
	json.NewEncoder(w).Encode(resp)
}

func (f *fakeRouterAPI) addRoutes(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	name := vars["name"]
	backend, ok := f.backends[name]
	if !ok {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	req := &routesReq{}
	err := json.NewDecoder(r.Body).Decode(req)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	rMap := make(map[string]struct{})
	addressToKey := func(a string) string {
		u, _ := url.Parse(a)
		return u.Host + ":" + u.Port()
	}
	for _, a := range backend.addresses {
		rMap[addressToKey(a)] = struct{}{}
	}
	for i, a := range req.Addresses {
		if _, ok := rMap[addressToKey(a)]; ok {
			continue
		}
		rMap[addressToKey(a)] = struct{}{}
		backend.addresses = append(backend.addresses, req.Addresses[i])
	}
}

func (f *fakeRouterAPI) removeRoutes(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	name := vars["name"]
	backend, ok := f.backends[name]
	if !ok {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	req := &routesReq{}
	err := json.NewDecoder(r.Body).Decode(req)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	addressToKey := func(a string) string {
		u, _ := url.Parse(a)
		return u.Host + ":" + u.Port()
	}
	addrMap := make(map[string]string)
	for _, b := range backend.addresses {
		addrMap[addressToKey(b)] = b
	}
	for _, b := range req.Addresses {
		delete(addrMap, addressToKey(b))
	}
	backend.addresses = nil
	for _, b := range addrMap {
		backend.addresses = append(backend.addresses, b)
	}
}

func (f *fakeRouterAPI) swap(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	name := vars["name"]
	targetName := r.FormValue("target")
	cnameOnly := r.FormValue("cnameOnly")
	backend, ok := f.backends[name]
	if !ok {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	target, ok := f.backends[targetName]
	if !ok {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	if backend.swapWith == targetName {
		backend.swapWith = ""
		target.swapWith = ""
	} else {
		backend.swapWith = targetName
		target.swapWith = name
	}
	backend.cnameOnly, _ = strconv.ParseBool(cnameOnly)
	target.cnameOnly = backend.cnameOnly
}

func (f *fakeRouterAPI) setCname(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	name := vars["name"]
	cname := vars["cname"]
	backend, ok := f.backends[name]
	if !ok {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	if strings.HasSuffix(cname, fmt.Sprintf(".%s.apirouter.com", name)) {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	var hasCname bool
	for _, c := range backend.cnames {
		if c == cname {
			hasCname = true
			break
		}
	}
	if hasCname {
		w.WriteHeader(http.StatusConflict)
		w.Write([]byte(router.ErrCNameExists.Error()))
		return
	}
	backend.cnames = append(backend.cnames, cname)
}

func (f *fakeRouterAPI) unsetCname(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	name := vars["name"]
	cname := vars["cname"]
	backend, ok := f.backends[name]
	if !ok {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	var newCnames []string
	var found bool
	for _, c := range backend.cnames {
		if c == cname {
			found = true
			continue
		}
		newCnames = append(newCnames, c)
	}
	if !found {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte(router.ErrCNameNotFound.Error()))
		return
	}
	backend.cnames = newCnames
}

func (f *fakeRouterAPI) getCnames(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	name := vars["name"]
	backend, ok := f.backends[name]
	if !ok {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	resp := cnamesResp{Cnames: backend.cnames}
	json.NewEncoder(w).Encode(&resp)
}

func (f *fakeRouterAPI) getCertificate(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	cname := vars["cname"]
	cert, ok := f.certificates[cname]
	if !ok {
		w.WriteHeader(http.StatusNotFound)
		w.Write([]byte(router.ErrCertificateNotFound.Error()))
		return
	}
	json.NewEncoder(w).Encode(&cert.Certificate)
}

func (f *fakeRouterAPI) addCertificate(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	cname := vars["cname"]
	var cert certData
	json.NewDecoder(r.Body).Decode(&cert)
	f.certificates[cname] = cert
	w.WriteHeader(http.StatusOK)
}

func (f *fakeRouterAPI) removeCertificate(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	cname := vars["cname"]
	if _, ok := f.certificates[cname]; !ok {
		w.WriteHeader(http.StatusNotFound)
		w.Write([]byte(router.ErrCertificateNotFound.Error()))
		return
	}
	delete(f.certificates, cname)
}

func (f *fakeRouterAPI) setHealthcheck(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	name := vars["name"]
	b, ok := f.backends[name]
	if !ok {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	hc := router.HealthcheckData{}
	json.NewDecoder(r.Body).Decode(&hc)
	b.healthcheck = hc
}

func (f *fakeRouterAPI) stop() {
	f.listener.Close()
}


text:
module Geoincident
  module ActsAsIncident
    extend ActiveSupport::Concern

    module ClassMethods

      def acts_as_incident options = {}

        define_method "geoincident_options" do
          {
            :lat_column => options[:lat] || 'latitude',
            :lng_column => options[:lng] || 'longitude'
          }
        end
      end

    end

  end
end


text:
using CryptoExchange.Net.Interfaces;
using CryptoExchange.Net.Interfaces.CommonClients;
using System;

namespace Binance.Net.Interfaces.Clients.CoinFuturesApi
{
    /// <summary>
    /// Binance Coin futures API endpoints
    /// </summary>
    public interface IBinanceClientCoinFuturesApi : IDisposable
    {
        /// <summary>
        /// The factory for creating requests. Used for unit testing
        /// </summary>
        IRequestFactory RequestFactory { get; set; }

        /// <summary>
        /// Endpoints related to account settings, info or actions
        /// </summary>
        public IBinanceClientCoinFuturesApiAccount Account { get; }

        /// <summary>
        /// Endpoints related to retrieving market data
        /// </summary>
        public IBinanceClientCoinFuturesApiExchangeData ExchangeData { get; }

        /// <summary>
        /// Endpoints related to orders and trades
        /// </summary>
        public IBinanceClientCoinFuturesApiTrading Trading { get; }

        /// <summary>
        /// Get the IFuturesClient for this client. This is a common interface which allows for some basic operations without knowing any details of the exchange.
        /// </summary>
        /// <returns></returns>
        public IFuturesClient CommonFuturesClient { get; }
    }
}


text:
class PluginAlreadyRegistered(Exception):
    pass

class PluginNotRegistered(Exception):
    pass

class PluginLimitReached(Exception):
    """
    Gets triggered when a placeholder has reached it's plugin limit.
    """
    pass

class AppAlreadyRegistered(Exception):
    pass

class ToolbarAlreadyRegistered(Exception):
    pass

class NotImplemented(Exception):
    pass

class SubClassNeededError(Exception):
    pass

class MissingFormError(Exception):
    pass

class NoHomeFound(Exception):
    pass

class PermissionsException(Exception):
    """Base permission exception
    """

class NoPermissionsException(PermissionsException):
    """Can be fired when some violate action is performed on permission system.
    """

class PublicIsUnmodifiable(Exception):
    """A method was invoked on the public copy, but is only valid for the
    draft version"""
    pass

class Deprecated(Exception): pass

class DuplicatePlaceholderWarning(Warning): pass

class DontUsePageAttributeWarning(Warning): pass

class CMSDeprecationWarning(Warning): pass

class LanguageError(Exception): pass


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _Node2 = require('../Node');

var _Node3 = _interopRequireDefault(_Node2);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

// TODO: create JSXBoundaryElement?

var JSXOpeningElement = function (_Node) {
    (0, _inherits3.default)(JSXOpeningElement, _Node);

    function JSXOpeningElement(childNodes) {
        (0, _classCallCheck3.default)(this, JSXOpeningElement);
        return (0, _possibleConstructorReturn3.default)(this, (0, _getPrototypeOf2.default)(JSXOpeningElement).call(this, 'JSXOpeningElement', childNodes));
    }

    (0, _createClass3.default)(JSXOpeningElement, [{
        key: '_acceptChildren',
        value: function _acceptChildren(children) {
            var attributes = [];
            var selfClosing = false;

            children.passToken('Punctuator', '<');
            children.skipNonCode();
            var name = children.passOneOfNode(['JSXIdentifier', 'JSXMemberExpression', 'JSXNamespacedName']);
            children.skipNonCode();

            while (true) {
                if (children.isNode('JSXAttribute')) {
                    children.skipNonCode();
                    attributes.push(children.passNode('JSXAttribute'));
                    children.skipNonCode();
                } else if (children.isNode('JSXSpreadAttribute')) {
                    children.skipNonCode();
                    attributes.push(children.passNode('JSXSpreadAttribute'));
                    children.skipNonCode();
                } else {
                    break;
                }
            }

            if (children.isToken('Punctuator', '/')) {
                children.skipNonCode();
                children.passToken('Punctuator', '/');
                selfClosing = true;
                children.skipNonCode();
            }

            children.passToken('Punctuator', '>');
            children.assertEnd();

            this.name = name;
            this.attributes = attributes;
            this.selfClosing = selfClosing;
        }
    }]);
    return JSXOpeningElement;
}(_Node3.default);

exports.default = JSXOpeningElement;
//# sourceMappingURL=JSXOpeningElement.js.map