text:
package com.hazelcast.map.impl.operation;

import com.hazelcast.map.EntryProcessor;
import com.hazelcast.map.impl.MapDataSerializerHook;
import com.hazelcast.map.impl.MapService;
import com.hazelcast.map.impl.MapServiceContext;
import com.hazelcast.map.impl.query.Query;
import com.hazelcast.map.impl.query.QueryResult;
import com.hazelcast.map.impl.query.QueryResultRow;
import com.hazelcast.map.impl.query.QueryRunner;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.query.Predicate;
import com.hazelcast.query.TruePredicate;
import com.hazelcast.spi.NodeEngine;
import com.hazelcast.spi.Operation;
import com.hazelcast.spi.impl.operationservice.impl.operations.PartitionAwareOperationFactory;
import com.hazelcast.spi.partition.IPartitionService;
import com.hazelcast.util.IterationType;
import com.hazelcast.util.collection.InflatableSet;
import com.hazelcast.util.collection.InflatableSet.Builder;
import com.hazelcast.util.collection.Int2ObjectHashMap;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.hazelcast.map.impl.MapService.SERVICE_NAME;
import static com.hazelcast.util.MapUtil.createInt2ObjectHashMap;
import static com.hazelcast.util.collection.InflatableSet.newBuilder;

public class PartitionWideEntryWithPredicateOperationFactory extends PartitionAwareOperationFactory {

    private String name;
    private EntryProcessor entryProcessor;
    private Predicate predicate;

    /**
     * Entry keys grouped by partition ID. This map is constructed from data
     * fetched by querying the map from non-partition threads. Because of
     * concurrent migrations, the query running on non-partition threads might
     * fail. In this case, the map is {@code null}.
     */
    private transient Map<Integer, List<Data>> partitionIdToKeysMap;

    public PartitionWideEntryWithPredicateOperationFactory() {
    }

    public PartitionWideEntryWithPredicateOperationFactory(String name, EntryProcessor entryProcessor, Predicate predicate) {
        this.name = name;
        this.entryProcessor = entryProcessor;
        this.predicate = predicate;
    }

    private PartitionWideEntryWithPredicateOperationFactory(String name, EntryProcessor entryProcessor, Predicate predicate,
                                                            Map<Integer, List<Data>> partitionIdToKeysMap) {
        this(name, entryProcessor, predicate);
        this.partitionIdToKeysMap = partitionIdToKeysMap;
    }

    @Override
    public PartitionAwareOperationFactory createFactoryOnRunner(NodeEngine nodeEngine, int[] partitions) {
        Set<Data> keys = tryToObtainKeysFromIndexes(nodeEngine);
        Map<Integer, List<Data>> partitionIdToKeysMap = groupKeysByPartition(keys, nodeEngine.getPartitionService(), partitions);

        return new PartitionWideEntryWithPredicateOperationFactory(name, entryProcessor, predicate, partitionIdToKeysMap);
    }

    @Override
    public Operation createPartitionOperation(int partition) {
        if (partitionIdToKeysMap == null) {
            // Index query failed to run because of ongoing migrations or we are
            // creating an operation on the caller node.
            return new PartitionWideEntryWithPredicateOperation(name, entryProcessor, predicate);
        }

        // index query succeeded
        List<Data> keyList = partitionIdToKeysMap.get(partition);
        assert keyList != null : "unexpected partition " + partition + ", expected partitions " + partitionIdToKeysMap.keySet();
        Set<Data> keys = keyList.isEmpty() ? Collections.<Data>emptySet() : newBuilder(keyList).build();
        return new MultipleEntryWithPredicateOperation(name, keys, entryProcessor, predicate);
    }

    @Override
    public void writeData(ObjectDataOutput out) throws IOException {
        out.writeUTF(name);
        out.writeObject(entryProcessor);
        out.writeObject(predicate);
    }

    @Override
    public void readData(ObjectDataInput in) throws IOException {
        name = in.readUTF();
        entryProcessor = in.readObject();
        predicate = in.readObject();
    }

    /**
     * Attempts to get keys by running an index query. This method may return
     * {@code null} if there is an ongoing migration, which means that it is not
     * safe to return results from a non-partition thread. The caller must then
     * run a partition query to obtain the results.
     *
     * @param nodeEngine nodeEngine of this cluster node
     * @return the set of keys or {@code null} if we failed to fetch the keys
     * because of ongoing migrations
     */
    private Set<Data> tryToObtainKeysFromIndexes(NodeEngine nodeEngine) {
        // Do not use index in this case, because it requires full-table-scan.
        if (predicate == TruePredicate.INSTANCE) {
            return null;
        }

        MapService mapService = nodeEngine.getService(SERVICE_NAME);
        MapServiceContext mapServiceContext = mapService.getMapServiceContext();

        QueryRunner runner = mapServiceContext.getMapQueryRunner(name);
        Query query = Query.of().mapName(name).predicate(predicate).iterationType(IterationType.KEY).build();
        final QueryResult result = (QueryResult) runner.runIndexQueryOnOwnedPartitions(query);
        if (result.getPartitionIds() == null) {
            // failed to run query because of ongoing migrations
            return null;
        }

        final Builder<Data> setBuilder = InflatableSet.newBuilder(result.size());
        for (QueryResultRow row : result.getRows()) {
            setBuilder.add(row.getKey());
        }
        return setBuilder.build();
    }

    private Map<Integer, List<Data>> groupKeysByPartition(Set<Data> keys, IPartitionService partitionService, int[] partitions) {
        if (keys == null) {
            return null;
        }

        // Even if the keys are successfully fetched from indexes, we need to
        // filter them to exclude the keys belonging to partitions on which we
        // weren't asked to operate on. Moreover, we need to include the
        // partitions on which we were asked to operate on and for which we
        // don't have any keys since this may indicate an out-migrated partition
        // and we want OperationRunner to throw WrongTargetException to notify
        // the caller about such situations.

        // Using the type of Int2ObjectHashMap allows the get and put operations
        // to avoid auto-boxing.
        final Int2ObjectHashMap<List<Data>> partitionToKeys = createInt2ObjectHashMap(partitions.length);

        // Pre-populate the map with the requested partitions to use it as a set
        // to filter out possible unrequested partitions encountered among the
        // fetched keys.
        for (int partition : partitions) {
            partitionToKeys.put(partition, Collections.<Data>emptyList());
        }

        for (Data key : keys) {
            int partitionId = partitionService.getPartitionId(key);
            List<Data> keyList = partitionToKeys.get(partitionId);
            if (keyList == null) {
                // we weren't asked to run on this partition
                continue;
            }

            if (keyList.isEmpty()) {
                // we have a first key for this partition
                keyList = new ArrayList<Data>();
                partitionToKeys.put(partitionId, keyList);
            }
            keyList.add(key);
        }
        return partitionToKeys;
    }

    @Override
    public Operation createOperation() {
        return new PartitionWideEntryWithPredicateOperation(name, entryProcessor, predicate);
    }

    @Override
    public int getFactoryId() {
        return MapDataSerializerHook.F_ID;
    }

    @Override
    public int getId() {
        return MapDataSerializerHook.PARTITION_WIDE_PREDICATE_ENTRY_FACTORY;
    }
}


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

import com.amazonaws.AmazonServiceException;

/**
 * <p>
 * The specified options are incompatible.
 * </p>
 */
public class IncompatibleOrderableOptionsException extends AmazonServiceException {
    private static final long serialVersionUID = 1L;

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

}

redpajama_set_name: RedPajamaGithub


text:
namespace GoogleARCore.Examples.ObjectManipulation
{
    using GoogleARCore.Examples.ObjectManipulationInternal;
    using UnityEngine;

#if UNITY_EDITOR
    // Set up touch input propagation while using Instant Preview in the editor.
    using Input = GoogleARCore.InstantPreviewInput;
#endif

    /// <summary>
    /// Gesture for when the user performs a drag motion on the touch screen.
    /// </summary>
    public class DragGesture : Gesture<DragGesture>
    {
        /// <summary>
        /// Constructs a DragGesture gesture.
        /// </summary>
        /// <param name="recognizer">The gesture recognizer.</param>
        /// <param name="touch">The touch that started this gesture.</param>
        public DragGesture(DragGestureRecognizer recognizer, Touch touch) : base(recognizer)
        {
            FingerId = touch.fingerId;
            StartPosition = touch.position;
            Position = StartPosition;
        }

        /// <summary>
        /// Gets the id of the finger used in this gesture.
        /// </summary>
        public int FingerId { get; private set; }

        /// <summary>
        /// Gets the screen position where the gesture started.
        /// </summary>
        public Vector2 StartPosition { get; private set; }

        /// <summary>
        /// Gets the current screen position of the gesture.
        /// </summary>
        public Vector2 Position { get; private set; }

        /// <summary>
        /// Gets the delta screen position of the gesture.
        /// </summary>
        public Vector2 Delta { get; private set; }

        /// <summary>
        /// Returns true if this gesture can start.
        /// </summary>
        /// <returns>True if the gesture can start.</returns>
        protected internal override bool CanStart()
        {
            if (GestureTouchesUtility.IsFingerIdRetained(FingerId))
            {
                Cancel();
                return false;
            }

            if (Input.touches.Length > 1)
            {
                for (int i = 0; i < Input.touches.Length; i++)
                {
                    Touch currentTouch = Input.touches[i];
                    if (currentTouch.fingerId != FingerId
                        && !GestureTouchesUtility.IsFingerIdRetained(currentTouch.fingerId))
                    {
                        return false;
                    }
                }
            }

            Touch touch;
            if (GestureTouchesUtility.TryFindTouch(FingerId, out touch))
            {
                Vector2 pos = touch.position;
                float diff = (pos - StartPosition).magnitude;
                if (GestureTouchesUtility.PixelsToInches(diff) >=
                    (Recognizer as DragGestureRecognizer).SlopInches)
                {
                    return true;
                }
            }
            else
            {
                Cancel();
            }

            return false;
        }

        /// <summary>
        /// Action to be performed when this gesture is started.
        /// </summary>
        protected internal override void OnStart()
        {
            GestureTouchesUtility.LockFingerId(FingerId);

            RaycastHit hit;
            if (GestureTouchesUtility.RaycastFromCamera(StartPosition, out hit))
            {
                var gameObject = hit.transform.gameObject;
                if (gameObject != null)
                {
                    TargetObject = gameObject.GetComponentInParent<Manipulator>().gameObject;
                }
            }

            Touch touch;
            GestureTouchesUtility.TryFindTouch(FingerId, out touch);
            Position = touch.position;
        }

        /// <summary>
        /// Updates this gesture.
        /// </summary>
        /// <returns>True if the update was successful.</returns>
        protected internal override bool UpdateGesture()
        {
            Touch touch;
            if (GestureTouchesUtility.TryFindTouch(FingerId, out touch))
            {
                if (touch.phase == TouchPhase.Moved)
                {
                    Delta = touch.position - Position;
                    Position = touch.position;
                    return true;
                }
                else if (touch.phase == TouchPhase.Ended)
                {
                    Complete();
                }
                else if (touch.phase == TouchPhase.Canceled)
                {
                    Cancel();
                }
            }
            else
            {
                Cancel();
            }

            return false;
        }

        /// <summary>
        /// Action to be performed when this gesture is cancelled.
        /// </summary>
        protected internal override void OnCancel()
        {
        }

        /// <summary>
        /// Action to be performed when this gesture is finished.
        /// </summary>
        protected internal override void OnFinish()
        {
            GestureTouchesUtility.ReleaseFingerId(FingerId);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Metadata.Edm;
using OpenRiaServices.DomainServices.Tools;

namespace OpenRiaServices.VisualStudio.DomainServices.Tools
{
    /// <summary>
    /// Subclass of <see cref="BusinessLogicContext"/> that handles the LinqToEntities type of domain service
    /// </summary>
    public abstract class LinqToEntitiesContextBase : BusinessLogicContext
    {
        private Dictionary<ComplexType, Type> _complexTypes;
        private readonly HashSet<Type> _visitedComplexTypes = new HashSet<Type>();

        public Dictionary<ComplexType, Type> ComplexTypes
        {
            get
            {
                if (this._complexTypes == null)
                {
                    this._complexTypes = new Dictionary<ComplexType, Type>();
                }
                return this._complexTypes;
            }
        }

        /// <summary>
        /// Creates a new instance
        /// </summary>
        /// <param name="contextType">The CLR type of the <see cref="ObjectContext>"/></param>
        public LinqToEntitiesContextBase(Type contextType)
            : base(contextType, contextType.Name)
        {
            this.PopulateComplexTypesInObjectContext();
        }

        /// <summary>
        /// Gets the name of the DAL technology of this context
        /// </summary>
        public override string DataAccessLayerName
        {
            get
            {
                return Resources.BusinessLogicClass_EntityFramework;
            }
        }

        /// <summary>
        /// Gets a <see cref="MetadataWorkspace"/> for this context.
        /// </summary>
        public abstract MetadataWorkspace MetadataWorkspace
        {
            get;
        }

        /// <summary>
        /// Invoked to create the entities known to this context
        /// </summary>
        /// <returns>The list of entities</returns>
        protected override IEnumerable<IBusinessLogicEntity> CreateEntities()
        {
            List<BusinessLogicEntity> entities = new List<BusinessLogicEntity>();

            Dictionary<EntityType, Type> entitiesInContext = this.GetEntityTypesInContext();
            foreach (KeyValuePair<EntityType, Type> pair in entitiesInContext)
            {
                entities.Add(new LinqToEntitiesEntity(this, pair.Key, pair.Value));
            }
            return entities;
        }

        /// <summary>
        /// Gets a dictionary of all entity types associated with the current DbContext type.
        /// The key is the EntityType (CSpace) and the value is the CLR type of the generated entity.
        /// </summary>
        /// <returns>A dictionary keyed by entity type and returning corresponding CLR type</returns>
        private Dictionary<EntityType, Type> GetEntityTypesInContext()
        {
            Dictionary<EntityType, Type> entities = new Dictionary<EntityType, Type>();
            ObjectItemCollection itemCollection = this.MetadataWorkspace.GetItemCollection(DataSpace.OSpace) as ObjectItemCollection;
            foreach (EntityType objectSpaceEntityType in itemCollection.GetItems<EntityType>())
            {
                Type clrType = itemCollection.GetClrType(objectSpaceEntityType);

                // Skip the EF CodeFirst specific EdmMetadata type
                if (DbContextUtilities.CompareWithSystemType(clrType, BusinessLogicClassConstants.EdmMetadataTypeName))
                {
                    continue;
                }

                StructuralType edmEntityType;
                if (this.MetadataWorkspace.TryGetEdmSpaceType(objectSpaceEntityType, out edmEntityType))
                {
                    entities[(EntityType)edmEntityType] = clrType;
                }
            }
            return entities;
        }

        /// <summary>
        /// Populates the ComplexTypes and GeneratedComplexTypes dictionaries from the MetadataWorkspace.
        /// </summary>
        private void PopulateComplexTypesInObjectContext()
        {
            ObjectItemCollection itemCollection = this.MetadataWorkspace.GetItemCollection(DataSpace.OSpace) as ObjectItemCollection;
            foreach (ComplexType objectSpaceEntityType in itemCollection.GetItems<ComplexType>())
            {
                Type clrType = itemCollection.GetClrType(objectSpaceEntityType);
                StructuralType edmComplexType;
                if (this.MetadataWorkspace.TryGetEdmSpaceType(objectSpaceEntityType, out edmComplexType))
                {
                    this.ComplexTypes[(ComplexType)edmComplexType] = clrType;
                }
            }
        }

        /// <summary>
        /// Determines whether a property of the given type should be generated
        /// in the associated metadata class.
        /// </summary>
        /// <remarks>
        /// This logic is meant to strip out DAL-level properties that will not appear
        /// on the client.
        /// </remarks>
        /// <param name="type">The type to test</param>
        /// <returns><c>true</c> if it is legal to generate this property type in the business logic class.</returns>
        protected override bool CanGeneratePropertyOfType(Type type)
        {
            if (base.CanGeneratePropertyOfType(type))
            {
                return true;
            }
            if (this.ComplexTypes.ContainsValue(type))
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// If the entity contains properties of complex types, then this class generates metadata classes for those complex types.
        /// </summary>
        /// <param name="codeGenContext">The context to use to generate code.</param>
        /// <param name="optionalSuffix">If not null, optional suffix to class name and namespace</param>
        /// <param name="entity">The entity for which to generate the additional metadata.</param>
        /// <returns><c>true</c> means at least some code was generated.</returns>
        protected override bool GenerateAdditionalMetadataClasses(ICodeGenContext codeGenContext, string optionalSuffix, BusinessLogicEntity entity)
        {
            LinqToEntitiesEntity linqToEntitiesEntity = (LinqToEntitiesEntity)entity;
            bool generatedCode = this.GenerateMetadataClassesForComplexTypes(codeGenContext, optionalSuffix, linqToEntitiesEntity.EntityType.Properties);
            return generatedCode;
        }

        /// <summary>
        /// Recursively generates metadata classes for properties of complex types.
        /// </summary>
        /// <param name="codeGenContext">The context to use to generate code.</param>
        /// <param name="optionalSuffix">If not null, optional suffix to class name and namespace</param>
        /// <param name="properties">The list of properties for which to generate metadata classes.</param>
        /// <returns><c>true</c> means at least some code was generated.</returns>
        private bool GenerateMetadataClassesForComplexTypes(ICodeGenContext codeGenContext, string optionalSuffix, IEnumerable<EdmProperty> properties)
        {
            bool generatedCode = false;
            foreach (var prop in properties)
            {
                EdmType propEdmType = prop.TypeUsage.EdmType;
                if (propEdmType.BuiltInTypeKind == BuiltInTypeKind.ComplexType)
                {
                    Type propClrType;
                    ComplexType propComplexType = (ComplexType)propEdmType;
                    if (this.ComplexTypes.TryGetValue(propComplexType, out propClrType) && !this._visitedComplexTypes.Contains(propClrType))
                    {
                        generatedCode |= this.GenerateMetadataClass(codeGenContext, optionalSuffix, propClrType);
                        this._visitedComplexTypes.Add(propClrType);

                        // Recursively generate Metadata classes for properties of complex types on this comples type.
                        generatedCode |= this.GenerateMetadataClassesForComplexTypes(codeGenContext, optionalSuffix, propComplexType.Properties);
                    }
                }
            }
            return generatedCode;
        }
    }
}


text:
module Dspace
	class MetadataValue < ActiveRecord::Base
		self.table_name = "metadatavalue"
	end
end


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

	namespace Edde\Api\File;

	use IteratorAggregate;

	interface IDirectory extends IteratorAggregate {
		/**
		 * return string path of this directory (can be non-existent)
		 *
		 * @return string
		 */
		public function getDirectory(): string;

		/**
		 * return directory name
		 *
		 * @return string
		 */
		public function getName(): string;

		/**
		 * return iterator over file list in the current directory
		 *
		 * @return string[]
		 */
		public function getFileList();

		/**
		 * @return IDirectory[]
		 */
		public function getDirectoryList();

		/**
		 * normalize directory path
		 *
		 * @return IDirectory
		 */
		public function normalize(): IDirectory;

		/**
		 * execute realpath on directory to check if everything is correct (directory must exists)
		 *
		 * @return IDirectory
		 */
		public function realpath(): IDirectory;

		/**
		 * create a file with the given name in this directory
		 *
		 * @param string $file
		 * @param string $content
		 *
		 * @return IFile
		 */
		public function save(string $file, string $content): IFile;

		/**
		 * get contents of a given file (in this directory)
		 *
		 * @param string $file
		 *
		 * @return string
		 */
		public function get(string $file): string;

		/**
		 * create filename (shortcut for $this->getDirectory.'\\'.$file)
		 *
		 * @param string $file
		 *
		 * @return string
		 */
		public function filename(string $file): string;

		/**
		 * return a File object
		 *
		 * @param string $file
		 *
		 * @return IFile
		 */
		public function file(string $file): IFile;

		/**
		 * create all directories until the current one
		 *
		 * @return IDirectory
		 */
		public function create(): IDirectory;

		/**
		 * recreate directory in place effectively clean all it's contents
		 *
		 * @return IDirectory
		 */
		public function purge(): IDirectory;

		/**
		 * physically remove the directory
		 *
		 * @return IDirectory
		 */
		public function delete(): IDirectory;

		/**
		 * @return bool
		 */
		public function exists(): bool;

		/**
		 * return directory based on a current path
		 *
		 * @param string $directory
		 * @param string $class directory class; sometimes it's useful return non default IDirectory interface
		 *
		 * @return IDirectory
		 */
		public function directory(string $directory, string $class = null): IDirectory;

		/**
		 * return parent directory
		 *
		 * @return IDirectory
		 */
		public function parent(): IDirectory;

		/**
		 * a bit more talkative iterator
		 *
		 * @return IFile[]
		 */
		public function files();

		/**
		 * @return IFile[]
		 */
		public function getIterator();
	}


text:
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { HashRouter } from 'react-router-dom';
import './index.css';
import registerServiceWorker from './registerServiceWorker';
import configureStore from './configureStore';
import App from 'app';

const reducers = {
    example: (state = {}) => state,
};
const store = configureStore(reducers);
console.log('store', store.getState());

function renderRoot(Root) {
    render(
        <Provider store={store}>
            <HashRouter>
                <Root />
            </HashRouter>
        </Provider>,
        document.getElementById('root')
    );
}

renderRoot(App);
registerServiceWorker();

if (module.hot) {
    module.hot.accept('app', () => {
        const NewApp = require('app').default;
        renderRoot(NewApp);
    });
}


text:
package hydrograph.ui.graph.action;

import hydrograph.ui.common.util.Constants;
import hydrograph.ui.common.util.XMLConfigUtil;
import hydrograph.ui.graph.Messages;
import hydrograph.ui.graph.controller.ComponentEditPart;

import org.eclipse.gef.ui.actions.SelectionAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;

public class ComponentHelpAction extends SelectionAction {

	public ComponentHelpAction(IWorkbenchPart part) {
		super(part);
		setLazyEnablementCalculation(true);
	}
	@Override
	protected void init() {
		super.init();
		setText(Messages.HELP);
		setId(Constants.HELP_ID);
		setEnabled(false);
	}

	@Override
	protected boolean calculateEnabled() {
		ISelection selection = getSelection();
		if(selection instanceof IStructuredSelection){
		IStructuredSelection currentSelectedComponent = (IStructuredSelection) getSelection();
		if (currentSelectedComponent.getFirstElement() instanceof ComponentEditPart)
			return true;
		}
		return false;
	}

	@Override
	public void run() {
		super.run();
		IStructuredSelection currentSelectedComponent = (IStructuredSelection) getSelection();
		if (currentSelectedComponent.getFirstElement() instanceof ComponentEditPart) {
			String componentName = ((ComponentEditPart) currentSelectedComponent.getFirstElement()).getCastedModel()
					.getComponentName();
			String helpFilePath = XMLConfigUtil.INSTANCE.getComponent(componentName).getHelpFilePath();
			PlatformUI.getWorkbench().getHelpSystem().displayHelpResource(helpFilePath);
		}
	}

}


text:
export default function bindReducers(handles) {
  return function(state={}, action) {
    let handle = handles[action.type];
    return handle && handle(state, action) || state;
  }
}


text:
package io.goodway.navitia_android;

import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;

/**
 * @author Alexis Robin
 * @version 0.6
 * Licensed under the Apache2 license
 */
public class Home extends Address implements Parcelable {

    public Home(String name, int icon){
        super(name, icon);
    }
    public Home(String name, int icon, double lat, double lon){
        super(name, icon, lat, lon);
    }
}


text:
describe Unidom::Geo::Locating, type: :model do

  before :each do
  end

  after :each do
  end

  context do

    model_attributes = {
      location_id:  SecureRandom.uuid,
      located_id:   SecureRandom.uuid,
      located_type: 'Unidom::Geo::Located::Mock',
      locator_id:   SecureRandom.uuid,
      locator_type: 'Unidom::Geo::Locator::Mock'
    }

    it_behaves_like 'Unidom::Common::Concerns::ModelExtension', model_attributes

    location_attributes = {
      region_id:         SecureRandom.uuid,
      region_type:       'Unidom::Geo::Region::Mock',
      longitude:         120.000000,
      latitude:          31.000000,
      postal_address:    'Somewhere',
      postal_code:       '812345',
      minimum_longitude: 119.990000,
      minimum_latitude:  30.990000,
      maximum_longitude: 120.010000,
      maximum_latitude:  31.010000
    }

    it_behaves_like 'belongs_to', model_attributes, :location, Unidom::Geo::Location, location_attributes

    it_behaves_like 'monomorphic scope', model_attributes, :location_is, :location

  end

end


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

     Copyright 2014-2016 CyberVision, Inc.

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.

-->

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/titleLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingRight="15dp"
    android:gravity="center_horizontal"
    android:orientation="horizontal">
    <ImageView
        android:id="@+id/addDeviceIcon"
        android:layout_width="@dimen/device_icon_size"
        android:layout_height="match_parent"
        android:src="@drawable/card_connect"
        />
    <TextView
        android:id="@+id/addDeviceText"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:paddingLeft="15dp"
        android:paddingStart="15dp"
        android:textColor="@android:color/white"
        android:textSize="36sp"
        android:ellipsize="marquee"
        android:fadingEdge="horizontal"
        android:singleLine="true"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:lines="1"
        android:text="@string/connect"
        android:gravity="center_vertical"
        />
</LinearLayout>


text:
- Fix regression in TypeMap support (thanks [@mikfoo](https://github.com/mikfoo)) [PR #235](https://github.com/avantcredit/gql2ts/pull/235)

## 1.10.0

- Fix nullable arrays in `@gql2ts/from-schema` (thanks [@mikfoo](https://github.com/mikfoo)) [Issue #197](https://github.com/avantcredit/gql2ts/issues/197) [PR #230](https://github.com/avantcredit/gql2ts/pull/230)

## 1.9.0

- Support `graphql@^14` [PR #222](https://github.com/avantcredit/gql2ts/pull/222)

## 1.8.2

- Remove dependency on Typescript for `@gql2ts/language-typescript` [PR #209](https://github.com/avantcredit/gql2ts/pull/209)

## 1.8.1

- Export enums as consts in `@gql2ts/from-schema` so they are available to the Typescript compiler. [Issue #179](https://github.com/avantcredit/gql2ts/issues/179) [PR #202](https://github.com/avantcredit/gql2ts/pull/202)

- Only append a semicolon to 'enums' when they are declared as union types and not Typescript `enum` types. [Issue #179](https://github.com/avantcredit/gql2ts/issues/179) [PR #202](https://github.com/avantcredit/gql2ts/pull/202)

## 1.8.0

- Add specific `__typename` value for `@gql2ts/from-query` [Issue #165](https://github.com/avantcredit/gql2ts/issues/165) [PR #168](https://github.com/avantcredit/gql2ts/pull/168)

- Import TypeMap from language packages [PR #175](https://github.com/avantcredit/gql2ts/pull/175) [PR #176](https://github.com/avantcredit/gql2ts/pull/176)

## 1.7.2

- Fix fragment spread inside of inline fragment for `@gql2ts/from-query` [Issue #76](https://github.com/avantcredit/gql2ts/issues/76) [PR #162](https://github.com/avantcredit/gql2ts/issues/162)

## 1.7.1

- Run default fields (`IGraphQLRootResponse`, etc.) through provided formatters [#159](https://github.com/avantcredit/gql2ts/pull/159)

## 1.7.0

- Use native enums in Typescript instead of union type [#116](https://github.com/avantcredit/gql2ts/pull/116)

## 1.6.0

- Improve documentation generation [#154](https://github.com/avantcredit/gql2ts/pull/154)
- Add new line in between Argument Interfaces [#157](https://github.com/avantcredit/gql2ts/pull/157)

## 1.5.2

- Add graphql as dependency for CLI

## 1.5.1

- Move graphql to peer-dependency [#156](https://github.com/avantcredit/gql2ts/pull/156)

## 1.5.0

- Generate Argument Interfaces in `@gql2ts/from-schema` [#148](https://github.com/avantcredit/gql2ts/pull/148)

For example:

```graphql
type Query {
  test(arg1: String!, arg2: Boolean): String
}
```

will output

```typescript
interface ITestOnQueryArguments {
  arg1: string;
  arg2?: boolean;
}
```

- Only warn about prettier once in `@gql2ts/language-typescript` [#147](https://github.com/avantcredit/gql2ts/pull/147)

## 1.4.4

- Loosen `graphql` version restriction to `< 1.0.0` [#152](https://github.com/avantcredit/gql2ts/pull/152)

## 1.4.3

- Fix 1.4.2 release

## 1.4.2

- [#137](https://github.com/avantcredit/gql2ts/pull/137)
  - Remove Typescript 2.7.0 lock
  - Add optional [`prettier`](https://github.com/prettier/prettier) integration to typescript package to pretty-print code
  - Remove custom Typescript formatter

## 1.4.1

- Lock Typescript to <2.7.0 [#132](https://github.com/avantcredit/gql2ts/pull/132)

## 1.4.0

- Allow custom `TypeMap` in `@gql2ts/from-schema`, similar to `@gql2ts/from-query` [#109](https://github.com/avantcredit/gql2ts/pull/109)

## 1.3.0

- Allow GraphQL Schema Language input in CLI

## 1.2.2

- Fix Default Export / CommonJS for `-e` flag on CLI [#99](https://github.com/avantcredit/gql2ts/pull/99)
- Add description JSDoc to individual fields [#96](https://github.com/avantcredit/gql2ts/pull/96)
- Update Some DevDependencies [#94](https://github.com/avantcredit/gql2ts/pull/94)

## 1.2.1

- Pin version of `graphql` to `^0.10.5` in all packages [#89](https://github.com/avantcredit/gql2ts/pull/89)

## 1.2.0

### Breaking Changes

- Use string literal for `__typename` [#87](https://github.com/avantcredit/gql2ts/pull/87), for instance:

```ts
interface IWhatever {
  __typename: "Whatever";
}
```

## 1.1.3

- Fix [Issue #85](https://github.com/avantcredit/gql2ts/issues/85) [#86](https://github.com/avantcredit/gql2ts/pull/86)

## 1.1.2

- Expose `ignoreTypeNameDeclaration` in the CLI. Use `--ignore-type-name-declaration` to enable it [#81](https://github.com/avantcredit/gql2ts/pull/81)

## 1.1.1

- Merge back changes from `1.0.3`

## 1.1.0 (botched)

### @gql2ts/from-schema

- Add option `ignoreTypeNameDeclaration` to not add `__typename` to all fields (thanks [@epicallan](https://github.com/epicallan)) [#72](https://github.com/avantcredit/gql2ts/pull/72)

## 1.0.3

- Update `graphql` dependency to `0.10.1`

## 1.0.2

- Fix the fix for unions from `1.0.1`

## 1.0.1

- Fix `@gql2ts/from-schema` not handling Unions properly [#66](https://github.com/avantcredit/gql2ts/pull/66)

## 1.0.0

- Use lerna to manage multiple packages
- Rewrite in Typescript
- Introduce `@gql2ts/from-query` which generates definitions from a schema and a query
- Extract common code to `@gql2ts/util`
- Accept more objects from a schema
  - `{ data: IntrospectionQuery }`
  - `IntrospectionQuery`
  - `GraphQLSchema` object
  - GraphQL Language Schema

### Breaking Changes

- Drop support for node v4/v5

## 0.6.1

- Fix bug where the help was outputted when `stdin` and `stdout` are used with no options

## 0.6.0

- Can now accept input from `stdin`
- Can now write to `stdout`

### Breaking Changes

- Output will now default to `stdout`, must specify `-o` to write to a file

## 0.5.1

- Add `tslint:disable` to generated files - [@AdirAmsalem](https://github.com/AdirAmsalem) [#38](https://github.com/avantcredit/gql2ts/pull/38)
- Update `graphql` dependency [#29](https://github.com/avantcredit/gql2ts/pull/29)

## 0.5.0

- Adds support for nullability attributes inside derived interfaces - [@neelance](https://github.com/neelance) [@orta](https://github.com/orta) [#34](https://github.com/avantcredit/gql2ts/pull/34).
  - Note that for older versions of TypeScript, you can use the CLI flag `--legacy` to get output without nullability references.

## 0.4.0

- Stop extending `GraphQLInterface`s with their possible types. (thanks [@tomaba](https://github.com/tomaba)) [#25](https://github.com/avantcredit/gql2ts/pull/25)
  - Previously, if two possible types implement a similar field, but with a different type it will cause an error

## 0.3.1

- Accept `__schema` at the top level [#20](https://github.com/avantcredit/gql2ts/pull/20)

## 0.3.0

### Breaking Changes

- Change from `module` to `namespace` [#14](https://github.com/avantcredit/gql2ts/pull/14)
- Removed `-m`/`--module-name` flag in favor of `-n`/`--namespace`

### Patches

- Fix for `Int` Scalar Type (thanks [@valorize](https://github.com/valorize)) [#15](https://github.com/avantcredit/gql2ts/pull/15)

## 0.2.1

- Fix Version number in command line

## 0.2.0

- Add support for Enums

## 0.1.0

- Add Root Entry Points & Error Map
- Add `__typename` to the generated interfaces

## 0.0.4

- Include polyfill `Array.prototype.includes` for node v4/v5 compatibility
- Add test suite

## 0.0.3

- Fix for node v5 strict mode

## 0.0.2

- Add information to npm

## 0.0.1

- Initial Release


text:
namespace boost
{
    namespace this_thread
    {
        void BOOST_THREAD_DECL interruption_point();
    }

    namespace thread_cv_detail
    {
        template<typename MutexType>
        struct lock_on_exit
        {
            MutexType* m;

            lock_on_exit():
                m(0)
            {}

            void activate(MutexType& m_)
            {
                m_.unlock();
                m=&m_;
            }
            ~lock_on_exit()
            {
                if(m)
                {
                    m->lock();
                }
           }
        };
    }

    inline void condition_variable::wait(unique_lock<mutex>& m)
    {
        int res=0;
        {
            thread_cv_detail::lock_on_exit<unique_lock<mutex> > guard;
            detail::interruption_checker check_for_interruption(&internal_mutex,&cond);
            guard.activate(m);
            do {
              res = pthread_cond_wait(&cond,&internal_mutex);
            } while (res == EINTR);
        }
        this_thread::interruption_point();
        if(res)
        {
            boost::throw_exception(condition_error(res, "boost:: condition_variable constructor failed in pthread_cond_wait"));
        }
    }

    inline bool condition_variable::do_timed_wait(
                unique_lock<mutex>& m,
                struct timespec const &timeout)
    {
        if (!m.owns_lock())
            boost::throw_exception(condition_error(EPERM, "condition_variable do_timed_wait: mutex not locked"));

        thread_cv_detail::lock_on_exit<unique_lock<mutex> > guard;
        int cond_res;
        {
            detail::interruption_checker check_for_interruption(&internal_mutex,&cond);
            guard.activate(m);
            cond_res=pthread_cond_timedwait(&cond,&internal_mutex,&timeout);
        }
        this_thread::interruption_point();
        if(cond_res==ETIMEDOUT)
        {
            return false;
        }
        if(cond_res)
        {
            boost::throw_exception(condition_error(cond_res, "condition_variable failed in pthread_cond_timedwait"));
        }
        return true;
    }

    inline void condition_variable::notify_one() BOOST_NOEXCEPT
    {
        boost::pthread::pthread_mutex_scoped_lock internal_lock(&internal_mutex);
        BOOST_VERIFY(!pthread_cond_signal(&cond));
    }

    inline void condition_variable::notify_all() BOOST_NOEXCEPT
    {
        boost::pthread::pthread_mutex_scoped_lock internal_lock(&internal_mutex);
        BOOST_VERIFY(!pthread_cond_broadcast(&cond));
    }

    class condition_variable_any
    {
        pthread_mutex_t internal_mutex;
        pthread_cond_t cond;

    public:
        BOOST_THREAD_NO_COPYABLE(condition_variable_any)
        condition_variable_any()
        {
            int const res=pthread_mutex_init(&internal_mutex,NULL);
            if(res)
            {
                boost::throw_exception(thread_resource_error(res, "condition_variable_any failed in pthread_mutex_init"));
            }
            int const res2=pthread_cond_init(&cond,NULL);
            if(res2)
            {
                BOOST_VERIFY(!pthread_mutex_destroy(&internal_mutex));
                boost::throw_exception(thread_resource_error(res, "condition_variable_any failed in pthread_cond_init"));
            }
        }
        ~condition_variable_any()
        {
            BOOST_VERIFY(!pthread_mutex_destroy(&internal_mutex));
            BOOST_VERIFY(!pthread_cond_destroy(&cond));
        }

        template<typename lock_type>
        void wait(lock_type& m)
        {
            int res=0;
            {
                thread_cv_detail::lock_on_exit<lock_type> guard;
                detail::interruption_checker check_for_interruption(&internal_mutex,&cond);
                guard.activate(m);
                res=pthread_cond_wait(&cond,&internal_mutex);
            }
            this_thread::interruption_point();
            if(res)
            {
                boost::throw_exception(condition_error(res, "condition_variable_any failed in pthread_cond_wait"));
            }
        }

        template<typename lock_type,typename predicate_type>
        void wait(lock_type& m,predicate_type pred)
        {
            while(!pred()) wait(m);
        }

        template<typename lock_type>
        bool timed_wait(lock_type& m,boost::system_time const& wait_until)
        {
            struct timespec const timeout=detail::get_timespec(wait_until);
            return do_timed_wait(m, timeout);
        }
        template<typename lock_type>
        bool timed_wait(lock_type& m,xtime const& wait_until)
        {
            return timed_wait(m,system_time(wait_until));
        }

        template<typename lock_type,typename duration_type>
        bool timed_wait(lock_type& m,duration_type const& wait_duration)
        {
            return timed_wait(m,get_system_time()+wait_duration);
        }

        template<typename lock_type,typename predicate_type>
        bool timed_wait(lock_type& m,boost::system_time const& wait_until,predicate_type pred)
        {
            while (!pred())
            {
                if(!timed_wait(m, wait_until))
                    return pred();
            }
            return true;
        }

        template<typename lock_type,typename predicate_type>
        bool timed_wait(lock_type& m,xtime const& wait_until,predicate_type pred)
        {
            return timed_wait(m,system_time(wait_until),pred);
        }

        template<typename lock_type,typename duration_type,typename predicate_type>
        bool timed_wait(lock_type& m,duration_type const& wait_duration,predicate_type pred)
        {
            return timed_wait(m,get_system_time()+wait_duration,pred);
        }

#ifdef BOOST_THREAD_USES_CHRONO
        template <class lock_type,class Duration>
        cv_status
        wait_until(
                lock_type& lock,
                const chrono::time_point<chrono::system_clock, Duration>& t)
        {
          using namespace chrono;
          typedef time_point<system_clock, nanoseconds> nano_sys_tmpt;
          wait_until(lock,
                        nano_sys_tmpt(ceil<nanoseconds>(t.time_since_epoch())));
          return system_clock::now() < t ? cv_status::no_timeout :
                                             cv_status::timeout;
        }

        template <class lock_type, class Clock, class Duration>
        cv_status
        wait_until(
                lock_type& lock,
                const chrono::time_point<Clock, Duration>& t)
        {
          using namespace chrono;
          system_clock::time_point     s_now = system_clock::now();
          typename Clock::time_point  c_now = Clock::now();
          wait_until(lock, s_now + ceil<nanoseconds>(t - c_now));
          return Clock::now() < t ? cv_status::no_timeout : cv_status::timeout;
        }

        template <class lock_type, class Clock, class Duration, class Predicate>
        bool
        wait_until(
                lock_type& lock,
                const chrono::time_point<Clock, Duration>& t,
                Predicate pred)
        {
            while (!pred())
            {
                if (wait_until(lock, t) == cv_status::timeout)
                    return pred();
            }
            return true;
        }

        template <class lock_type, class Rep, class Period>
        cv_status
        wait_for(
                lock_type& lock,
                const chrono::duration<Rep, Period>& d)
        {
          using namespace chrono;
          system_clock::time_point s_now = system_clock::now();
          steady_clock::time_point c_now = steady_clock::now();
          wait_until(lock, s_now + ceil<nanoseconds>(d));
          return steady_clock::now() - c_now < d ? cv_status::no_timeout :
                                                   cv_status::timeout;

        }

        template <class lock_type, class Rep, class Period, class Predicate>
        bool
        wait_for(
                lock_type& lock,
                const chrono::duration<Rep, Period>& d,
                Predicate pred)
        {
          while (!pred())
          {
              if (wait_for(lock, d) == cv_status::timeout)
                  return pred();
          }
          return true;
        }

        template <class lock_type>
        inline void wait_until(
            lock_type& lk,
            chrono::time_point<chrono::system_clock, chrono::nanoseconds> tp)
        {
            using namespace chrono;
            nanoseconds d = tp.time_since_epoch();
            timespec ts;
            seconds s = duration_cast<seconds>(d);
            ts.tv_sec = static_cast<long>(s.count());
            ts.tv_nsec = static_cast<long>((d - s).count());
            do_timed_wait(lk, ts);
        }
#endif

        void notify_one() BOOST_NOEXCEPT
        {
            boost::pthread::pthread_mutex_scoped_lock internal_lock(&internal_mutex);
            BOOST_VERIFY(!pthread_cond_signal(&cond));
        }

        void notify_all() BOOST_NOEXCEPT
        {
            boost::pthread::pthread_mutex_scoped_lock internal_lock(&internal_mutex);
            BOOST_VERIFY(!pthread_cond_broadcast(&cond));
        }
    private: // used by boost::thread::try_join_until

        template <class lock_type>
        inline bool do_timed_wait(
          lock_type& m,
          struct timespec const &timeout)
        {
          int res=0;
          {
              thread_cv_detail::lock_on_exit<lock_type> guard;
              detail::interruption_checker check_for_interruption(&internal_mutex,&cond);
              guard.activate(m);
              res=pthread_cond_timedwait(&cond,&internal_mutex,&timeout);
          }
          this_thread::interruption_point();
          if(res==ETIMEDOUT)
          {
              return false;
          }
          if(res)
          {
              boost::throw_exception(condition_error(res, "condition_variable_any failed in pthread_cond_timedwait"));
          }
          return true;
        }

    };

}

#include <boost/config/abi_suffix.hpp>

#endif


text:
/// <reference path="../_definitions.ts" />

module Phaser.Components {

    export class AnimationManager {

        /**
         * AnimationManager constructor
         * Create a new AnimationManager.
         *
         * @param parent {Sprite} Owner sprite of this manager.
         */
        constructor(parent: Phaser.Sprite) {

            this._parent = parent;
            this.game = parent.game;
            this._anims = {};

        }

        /**
         * Reference to Phaser.Game
         */
        public game: Phaser.Game;

        /**
         * Local private reference to its parent game object.
         */
        private _parent: Phaser.Sprite;

        /**
         * Animation key-value container.
         */
        private _anims: {};

        /**
         * Index of current frame.
         * @type {number}
         */
        private _frameIndex: number;

        /**
         * Data contains animation frames.
         * @type {FrameData}
         */
        private _frameData: FrameData = null;

        /**
         * When an animation frame changes you can choose to automatically update the physics bounds of the parent Sprite
         * to the width and height of the new frame. If you've set a specific physics bounds that you don't want changed during
         * animation then set this to false, otherwise leave it set to true.
         * @type {bool}
         */
        public autoUpdateBounds: bool = true;

        /**
         * Keeps track of the current animation being played.
         */
        public currentAnim: Phaser.Animation;

        /**
         * Keeps track of the current frame of animation.
         */
        public currentFrame: Phaser.Frame = null;

        /**
         * Load animation frame data.
         * @param frameData Data to be loaded.
         */
        public loadFrameData(frameData: Phaser.FrameData) {

            this._frameData = frameData;

            this.frame = 0;

        }

        /**
         * Add a new animation.
         * @param name {string} What this animation should be called (e.g. "run").
         * @param frames {any[]} An array of numbers/strings indicating what frames to play in what order (e.g. [1, 2, 3] or ['run0', 'run1', run2]).
         * @param frameRate {number} The speed in frames per second that the animation should play at (e.g. 60 fps).
         * @param loop {bool} Whether or not the animation is looped or just plays once.
         * @param useNumericIndex {bool} Use number indexes instead of string indexes?
         * @return {Animation} The Animation that was created
         */
        public add(name: string, frames: any[] = null, frameRate: number = 60, loop: bool = false, useNumericIndex: bool = true): Phaser.Animation {

            if (this._frameData == null)
            {
                return;
            }

            //  Create the signals the AnimationManager will emit
            if (this._parent.events.onAnimationStart == null)
            {
                this._parent.events.onAnimationStart = new Phaser.Signal;
                this._parent.events.onAnimationComplete = new Phaser.Signal;
                this._parent.events.onAnimationLoop = new Phaser.Signal;
            }

            if (frames == null)
            {
                frames = this._frameData.getFrameIndexes();
            }
            else
            {
                if (this.validateFrames(frames, useNumericIndex) == false)
                {
                    throw Error('Invalid frames given to Animation ' + name);
                    return;
                }
            }

            if (useNumericIndex == false)
            {
                frames = this._frameData.getFrameIndexesByName(frames);
            }

            this._anims[name] = new Animation(this.game, this._parent, this._frameData, name, frames, frameRate, loop);

            this.currentAnim = this._anims[name];
            this.currentFrame = this.currentAnim.currentFrame;

            return this._anims[name];

        }

        /**
         * Check whether the frames is valid.
         * @param frames {any[]} Frames to be validated.
         * @param useNumericIndex {bool} Does these frames use number indexes or string indexes?
         * @return {bool} True if they're valid, otherwise return false.
         */
        private validateFrames(frames: any[], useNumericIndex: bool): bool {

            for (var i = 0; i < frames.length; i++)
            {
                if (useNumericIndex == true)
                {
                    if (frames[i] > this._frameData.total)
                    {
                        return false;
                    }
                }
                else
                {
                    if (this._frameData.checkFrameName(frames[i]) == false)
                    {
                        return false;
                    }
                }
            }

            return true;

        }

        /**
         * Play animation with specific name.
         * @param name {string} The string name of the animation you want to play.
         * @param frameRate {number} FrameRate you want to specify instead of using default.
         * @param loop {bool} Whether or not the animation is looped or just plays once.
         */
        public play(name: string, frameRate: number = null, loop: bool = null): Phaser.Animation {

            if (this._anims[name])
            {
                if (this.currentAnim == this._anims[name])
                {
                    if (this.currentAnim.isPlaying == false)
                    {
                        return this.currentAnim.play(frameRate, loop);
                    }
                }
                else
                {
                    this.currentAnim = this._anims[name];
                    return this.currentAnim.play(frameRate, loop);
                }
            }

        }

        /**
         * Stop animation by name.
         * Current animation will be automatically set to the stopped one.
         */
        public stop(name: string) {

            if (this._anims[name])
            {
                this.currentAnim = this._anims[name];
                this.currentAnim.stop();
            }

        }

        /**
         * Update animation and parent sprite's bounds.
         */
        public update() {

            if (this.currentAnim && this.currentAnim.update() == true)
            {
                this.currentFrame = this.currentAnim.currentFrame;
                this._parent.texture.width = this.currentFrame.width;
                this._parent.texture.height = this.currentFrame.height;
            }

        }

        public get frameData(): FrameData {
            return this._frameData;
        }

        public get frameTotal(): number {

            if (this._frameData)
            {
                return this._frameData.total;
            }
            else
            {
                return -1;
            }
        }

        public get frame(): number {
            return this._frameIndex;
        }

        /**
         *
         * @param value
         */
        public set frame(value: number) {

            if (this._frameData && this._frameData.getFrame(value) !== null)
            {
                this.currentFrame = this._frameData.getFrame(value);

                this._parent.texture.width = this.currentFrame.width;
                this._parent.texture.height = this.currentFrame.height;

                if (this.autoUpdateBounds && this._parent['body'])
                {
                    this._parent.body.bounds.width = this.currentFrame.width;
                    this._parent.body.bounds.height = this.currentFrame.height;
                }

                this._frameIndex = value;
            }

        }

        public get frameName(): string {
            return this.currentFrame.name;
        }

        public set frameName(value: string) {

            if (this._frameData && this._frameData.getFrameByName(value))
            {
                this.currentFrame = this._frameData.getFrameByName(value);

                this._parent.texture.width = this.currentFrame.width;
                this._parent.texture.height = this.currentFrame.height;

                this._frameIndex = this.currentFrame.index;
            }
            else
            {
                throw new Error("Cannot set frameName: " + value);
            }

        }

        /**
         * Removes all related references
         */
        public destroy() {

            this._anims = {};
            this._frameData = null;
            this._frameIndex = 0;
            this.currentAnim = null;
            this.currentFrame = null;

        }

    }

}


text:
from django.http import HttpResponse
from django.conf.urls import url

from wagtail.contrib.wagtailroutablepage.models import RoutablePage, route

def routable_page_external_view(request, arg="ARG NOT SET"):
    return HttpResponse("EXTERNAL VIEW: " + arg)

class OldStyleRoutablePageTest(RoutablePage):
    subpage_urls = (
        url(r'^$', 'main', name='main'),
        url(r'^archive/year/(\d+)/$', 'archive_by_year', name='archive_by_year'),
        url(r'^archive/author/(?P<author_slug>.+)/$', 'archive_by_author', name='archive_by_author'),
        url(r'^external/(.+)/$', routable_page_external_view, name='external_view')
    )

    # Don't show deprecation warning for this class to keep test log clean
    _disable_subpage_urls_deprecation_warning = True

    def archive_by_year(self, request, year):
        return HttpResponse("ARCHIVE BY YEAR: " + str(year))

    def archive_by_author(self, request, author_slug):
        return HttpResponse("ARCHIVE BY AUTHOR: " + author_slug)

    def main(self, request):
        return HttpResponse("MAIN VIEW")

class NewStyleRoutablePageTest(RoutablePage):
    @route(r'^$')
    def main(self, request):
        return HttpResponse("MAIN VIEW")

    @route(r'^archive/year/(\d+)/$')
    def archive_by_year(self, request, year):
        return HttpResponse("ARCHIVE BY YEAR: " + str(year))

    @route(r'^archive/author/(?P<author_slug>.+)/$')
    def archive_by_author(self, request, author_slug):
        return HttpResponse("ARCHIVE BY AUTHOR: " + author_slug)

    @route(r'^external/(.+)/$')
    @route(r'^external-no-arg/$')
    def external_view(self, *args, **kwargs):
        return routable_page_external_view(*args, **kwargs)

    # By default, the method name would be used as the url name but when the
    # "name" kwarg is specified, this should override the default.
    @route(r'^override-name-test/$', name='name_overridden')
    def override_name_test(self, request):
        pass


text:
layout: single

title: Writing an Angular Factory for the Particle Cloud
subtitle: ".Success == .FAIL and here's why"
excerpt: "The Ionic Framework is built on AngularJS so starting at the 'bottom' of the MVC stack we will begin with an Angular Factory to do all the heavy lifting of interacting with the Particle Cloud API"
categories:
  - Particle
  - Ionic
tags:
  - angularjs
  - api
  - rest
header:
  image: combined_header.jpg
  teaser: combined_teaser.jpg
---
{% include toc %}

**Warning:** I am not an expert in any of the things I write about except perhaps Infrastructure so be mindful when following advice and using code snippets found in this post.
{: .notice--warning}

I often run into outdated or "good enough" tutorials/code when trying to accomplish different things in my Lemmy Light project and this is one I really struggled to find the correct answer.  When you are writing the code behind an [Ionic Framework](http://ionicframework.com) app you are in essence working in [AngularJS](http://angularjs.org) so oftentimes you can find answers by searching for "code problem angular" instead of Ionic but Ionic will net results as well.  The Lemmy Light app needs to consume data from [Particle's](http://particle.io) REST API in order to perform a number of user initiated actions like setting schedules, reading sensor data and more so I needed to write an angularjs controller and factory to connect to Particle and consume their JSON responses in the app.  Let's start with the factory.
{: style="text-align: left;"}

**Note:** You will see me use factory and service interchangably throughout this post which isn't technically correct but both factories and services syntactic sugar on top of the Angular provider.
{: .notice--info}

### AngularJS Factory
I won't go into a detailed explanation of what a factory is or what it does because it is well documented in many locations, what made it click for me is this great blog post [AngularJS: Factory vs Service vs Provider by Tyler McGinnis](https://tylermcginnis.com/angularjs-factory-vs-service-vs-provider-5f426cfe6b8c#.o3xhbot7l), so let's get into the details of the factory I use to interact with the Particle API.
{: style="text-align: left;"}

~~~js
appServices.factory('pDevices', function($http, localstorage) {
  //Factory Variables and Private Methods
  root_url = 'https://api.particle.io/v1/',
  auth_url = 'https://api.particle.io/oauth/token',
  clientID_pass = 'Basic cGFydGljbGU6cGFydGljbGU=',
  device_id = localstorage.getItem('device_id'),
  access_token = localstorage.getItem('access_token');
~~~

As you can see I am using an appServices variable that was defined in my controllers.js and the starter.services module is injected in my app.js so I can inject services/factories as needed and keep my code modular.

~~~js
<!--From controllers.js-->
var appServices = angular.module('starter.services', []);
<!--From app.js-->
angular.module('starter', ['ionic','ngIOS9UIWebViewPatch', 'starter.controllers', 'starter.services', 'ngMaterial', 'ngMessages', 'ngCordova'])
~~~

In this factory you can also see that I am injecting $http and another service named localstorage into my factory.  You will see where they become relevant shortly.  The first three variables should really be injected as angular constants but for now they are included in the service.  The device_id and access_token variables are two values we are looking to get from the [Particle Cloud API](https://docs.particle.io/reference/api/) but they could be any JSON result that you wish to use in your own app.  When the factory is instantiated it will attempt to locate a device_id by executing the localstorage.getItem method with 'device_id' as the key.  If no value exists device_id value will be null.  The same process is used to determine if an existing access_token has already been acquired.

**Warning:** Depending on the type of data you are storing, localstorage may not be secure enough.  An appropriate secure storage solution will need to be used.  One example would be [cordova-plugin-secure-storage](https://github.com/Crypho/cordova-plugin-secure-storage).
{: .notice--warning}


text:
//
//  GMYHotSpotViewBetterLayout.m
//  GMYHotSpotView
//
//  Created by 郭妙友 on 15/7/26.
//  Copyright (c) 2015年 miaoyou.gmy. All rights reserved.
//

#import "GMYHotSpotViewBetterLayout.h"
#import "GMYHotSpotView.h"
#import "GMYHotSpot.h"
#import "UIView+EX.h"
#import "GMYHotSpotViewDefines.h"
typedef long long Int64;
typedef unsigned long uInt64;

@implementation GMYHotSpotViewBetterLayout
@synthesize hotspotView = _hotspotView;
#pragma mark - Override
- (void)layoutHotSpotView:(NSArray<id<GMYHotSpot> > *)hotspots eachLineCompletion:(eachLineCompletion)completion{
    NSMutableArray *models = [NSMutableArray arrayWithArray:hotspots];
    NSInteger count = models.count;
    int line = 0;
    [_hotspotView.hotspots removeAllObjects];
    while (count > 0) {
        NSArray *arr = [self adjustHotspotsSort:models limitWidth:_hotspotView.width];
        [_hotspotView.hotspots addObjectsFromArray:arr];
        [arr enumerateObjectsUsingBlock:^(id<GMYHotSpot> obj, NSUInteger idx, BOOL *stop) {
            obj.line = line;
        }];
        completion(line,arr);
        line++;
        count -= arr.count;
        [models removeObjectsInArray:arr];
    }
}

- (void)updateHotSpotViewLayoutByRemoveHotspot:(id<GMYHotSpot>)hotspot withRemovedSpot:(UIView *)spotView{
    NSUInteger index = spotView.tag - kGMYHotSpotViewTagBaseIndex;
    NSRange range = NSMakeRange(index , _hotspotView.hotspots.count - index);

    NSMutableArray *modelShoots = [_hotspotView.hotspots mutableCopy];
    NSMutableArray *models = [[_hotspotView.hotspots subarrayWithRange:range] mutableCopy];
    NSMutableArray *rejusetViews = [NSMutableArray arrayWithCapacity:models.count];
    [_hotspotView.hotspots removeObjectsInRange:range];
    __block CGFloat offsetX = spotView.left;
    NSUInteger nowLine = hotspot.line;
    NSArray *adjustModels = [self adjustHotspotsSort:models limitWidth:_hotspotView.width - offsetX];
    [adjustModels enumerateObjectsUsingBlock:^(id<GMYHotSpot> obj, NSUInteger idx, BOOL *stop) {
        UIView *view = [_hotspotView viewWithTag:[modelShoots indexOfObject:obj] + kGMYHotSpotViewTagBaseIndex];

        [UIView animateWithDuration:0.3f animations:^{
            view.point = CGPointMake(offsetX, nowLine*_hotspotView.buttonHeight + nowLine*_hotspotView.minimumLineSpacing);
        }];

        [rejusetViews addObject:view];
        offsetX += (view.width + _hotspotView.minimumInteritemSpacing);
        obj.line = nowLine;
    }];
    nowLine++;
    offsetX = 0.f;
    [models removeObjectsInArray:adjustModels];
    [_hotspotView.hotspots addObjectsFromArray:adjustModels];

    while (models.count >= 1) {
        NSArray *adjustModels = [self adjustHotspotsSort:models limitWidth:_hotspotView.width];

        [adjustModels enumerateObjectsUsingBlock:^(id<GMYHotSpot> obj, NSUInteger idx, BOOL *stop) {
            UIView *view = [_hotspotView viewWithTag:[modelShoots indexOfObject:obj] + kGMYHotSpotViewTagBaseIndex];

            [UIView animateWithDuration:0.3f animations:^{
                view.point = CGPointMake(offsetX, nowLine*_hotspotView.buttonHeight + nowLine*_hotspotView.minimumLineSpacing);
            }];

            [rejusetViews addObject:view];
            offsetX += (view.width + _hotspotView.minimumInteritemSpacing);
            obj.line = nowLine;
        }];
        nowLine++;
        offsetX = 0.f;
        [models removeObjectsInArray:adjustModels];
        [_hotspotView.hotspots addObjectsFromArray:adjustModels];
    }

    [rejusetViews enumerateObjectsUsingBlock:^(UIView *obj, NSUInteger idx, BOOL *stop) {
        obj.tag = idx + spotView.tag;
    }];

    if(_hotspotView.hotspots.count >= 1){
        id<GMYHotSpot> lastHotSpot = [_hotspotView.hotspots lastObject];
        _hotspotView.height = (lastHotSpot.line+1) * _hotspotView.buttonHeight + lastHotSpot.line*_hotspotView.minimumLineSpacing;
    }
    else{
        _hotspotView.height = 0;
    }
}

- (CGFloat)calculateViewHeightWithHotSpot:(NSArray *)hotspots{
    NSUInteger line = 0;
    NSMutableArray *models = [NSMutableArray arrayWithArray:hotspots];
    NSUInteger count = models.count;
    while (line < _hotspotView.maxLines && count > 0) {
        NSArray *arr = [self adjustHotspotsSort:models limitWidth:CGRectGetWidth(_hotspotView.frame)];
        count -= arr.count;
        [models removeObjectsInArray:arr];
        line++;
    }
    return (MAX(0, line - 1) * _hotspotView.minimumLineSpacing + line* _hotspotView.buttonHeight);
}

#pragma mark - 01 背包
/**
 *  f[i,j] = Max{f[i-1,j-Wi]+Pi( j >= Wi ),  f[i-1,j]}
 *  f[i,j] 表示在前i件物品中选择若干件放在承重为 j 的背包中,可以取得的最大价值。
 *  *承重j为 limitWidth, CGRectgetWidth(hotspotView),即视图的宽度
 *  *Wi 为第i个hotspot所占的宽度, boundingRectWithSize....
 *  *Pi 为第i个hotspot的价值,这里我们也用自身的宽度表示, 因为我们希望一个好的热点布局,一行是没有剩余空间的(类似内存对齐的概念)
 *
 *  @param hotspots   所有物品
 *  @param limitWidth 背包容量
 *
 *  @return 当前所有物品中 能放入背包且总价值最高的 物品组合
 */
- (NSArray *)adjustHotspotsSort:(NSArray *)hotspots limitWidth:(CGFloat)limitWidth{
    NSMutableArray *ans = [[NSMutableArray alloc] initWithCapacity:5];
    /**
     *  @Discussion 类型转换,存在 浮点数转整型丢失精度问题。
     */
    uInt64 v = limitWidth;
    uInt64 n = hotspots.count;
    uInt64 itemspace =_hotspotView.minimumInteritemSpacing;
    uInt64 *value = (uInt64 *)malloc(n * sizeof(uInt64));
    uInt64 *weight = (uInt64 *)malloc(n * sizeof(uInt64));
    uInt64 *dp = (uInt64 *)malloc(2 * v * sizeof(unsigned long));

    [hotspots enumerateObjectsUsingBlock:^(id<GMYHotSpot> obj, NSUInteger idx, BOOL *stop) {
        value[idx] = weight[idx] = ceilf(([obj.title boundingRectWithSize:CGSizeMake(limitWidth, _hotspotView.buttonHeight)
                                                            options:NSStringDrawingUsesLineFragmentOrigin
                                                         attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:_hotspotView.fontSize]}
                                                            context:nil].size.width + 2*_hotspotView.titleSpace ));
    }];

    memset(dp, 0,  2 * v * sizeof(uInt64));
    bool path[v][n];
    memset(path, false, sizeof(bool)*v*n);

    Int64 tmpval = 0;
    for(Int64 i = 0; i < n ; i++){
        for(Int64 j = v; j >= weight[i];j--){
            if(dp[j]) tmpval = weight[i] + itemspace;
            else tmpval = weight[i];

            if(j >= tmpval && dp[j - tmpval] + value[i] > dp[j]){
                dp[j] = dp[j - tmpval] + value[i];

                path[dp[j]][i] = true;
            }
        }
    }

    Int64 val = dp[v];
    unsigned index = 0;
    while (val > 0) {
        for(int i=0;i<n;i++){
            if(path[val][i]){
                index = i;
                break;
            }
        }
        [ans addObject:hotspots[index]];
        val -= weight[index];
    }

    free(value);
    free(weight);
    free(dp);
    return ans;
}

@end


text:
const LOAD = 'redux-example/auth/LOAD';
const LOAD_SUCCESS = 'redux-example/auth/LOAD_SUCCESS';
const LOAD_FAIL = 'redux-example/auth/LOAD_FAIL';
const SEARCH = 'redux-example/auth/SEARCH';
const SEARCH_SUCCESS = 'redux-example/auth/SEARCH_SUCCESS';
const SEARCH_FAIL = 'redux-example/auth/SEARCH_FAIL';
const LOGIN = 'redux-example/auth/LOGIN';
const LOGIN_SUCCESS = 'redux-example/auth/LOGIN_SUCCESS';
const LOGIN_FAIL = 'redux-example/auth/LOGIN_FAIL';
const LOGOUT = 'redux-example/auth/LOGOUT';
const LOGOUT_SUCCESS = 'redux-example/auth/LOGOUT_SUCCESS';
const LOGOUT_FAIL = 'redux-example/auth/LOGOUT_FAIL';

const initialState = {
  loaded: false
};

export default function reducer(state = initialState, action = {}) {
  switch (action.type) {
    case LOAD:
      return {
        ...state,
        loading: true
      };
    case LOAD_SUCCESS:
      return {
        ...state,
        loading: false,
        loaded: true,
        practices: action.result
      };
    case LOAD_FAIL:
      return {
        ...state,
        loading: false,
        loaded: false,
        error: action.error
      };
    case SEARCH:
      return {
        ...state,
        loading: true
      };
    case SEARCH_SUCCESS:
      return {
        ...state,
        loading: false,
        loaded: true,
        practices: action.result.Practice,
        selectedTime: action.result.Time
      };
    case SEARCH_FAIL:
      return {
        ...state,
        loading: false,
        loaded: false,
        error: action.error
      };
    case LOGIN:
      return {
        ...state,
        loggingIn: true
      };
    case LOGIN_SUCCESS:
      return {
        ...state,
        loggingIn: false,
        user: action.result
      };
    case LOGIN_FAIL:
      return {
        ...state,
        loggingIn: false,
        user: null,
        loginError: action.error
      };
    case LOGOUT:
      return {
        ...state,
        loggingOut: true
      };
    case LOGOUT_SUCCESS:
      return {
        ...state,
        loggingOut: false,
        user: null
      };
    case LOGOUT_FAIL:
      return {
        ...state,
        loggingOut: false,
        logoutError: action.error
      };
    default:
      return state;
  }
}

export function isLoaded(globalState) {
  return globalState.auth && globalState.auth.loaded;
}

export function load() {
  return {
    types: [LOAD, LOAD_SUCCESS, LOAD_FAIL],
    promise: (client) => client.get('/practices')
  };
}
export function search(name, neighborhood, time) {
  // console.log("name", name);
  // console.log("neighborhood", neighborhood);
  return {
    types: [SEARCH, SEARCH_SUCCESS, SEARCH_FAIL],
    promise: (client) => client.get('/search', {
      params: {
        name: name,
        neighborhood: neighborhood,
        time: time
      }
    })
  };
}

export function login(name) {
  return {
    types: [LOGIN, LOGIN_SUCCESS, LOGIN_FAIL],
    promise: (client) => client.post('/login', {
      data: {
        name: name
      }
    })
  };
}

export function logout() {
  return {
    types: [LOGOUT, LOGOUT_SUCCESS, LOGOUT_FAIL],
    promise: (client) => client.get('/logout')
  };
}


text:
package de.ploing.osgitest.greetingservice.service1;

import de.ploing.osgitest.greetingservice.GreetingService;

public class GreetingService1 implements GreetingService {
    @Override
    public String getGreeting() {
        return "Greeting from service 1";
    }
}


text:
<?php
require_once '../lib/Controller.php';
require_once '../lib/View.php';
require_once '../model/tipobibliografia.php';

class tipobibliografiaController extends Controller {
    public function index()
    {
        if (!isset($_GET['p'])){$_GET['p']=1;}
        if(!isset($_GET['q'])){$_GET['q']="";}
        if(!isset($_GET['criterio'])){$_GET['criterio']="descripcion_tipobibliografia";}
        $obj = new tipobibliografia();
        $data = array();
        $data['data'] = $obj->index($_GET['q'],$_GET['p'],$_GET['criterio']);
        $data['query'] = $_GET['q'];
        $data['pag'] = $this->Pagination(array('rows'=>$data['data']['rowspag'],'url'=>'index.php?controller=tipobibliografia&action=index','query'=>$_GET['q']));
        $cols = array("idtipo_bibliografia","descripcion_tipobibliografia");

        $opt = array("descripcion_tipobibliografia"=>"Nombre tipobibliografia");
        $data['grilla'] = $this->grilla("tipobibliografia",$cols, $data['data']['rows'],$opt,$data['pag'],true,true);
        $view = new View();
        $view->setData($data);
        $view->setTemplate( '../view/tipobibliografia/_Index.php' );
        $view->setLayout( '../template/Layout.php' );
        $view->render();
    }

    public function edit() {
        $obj = new tipobibliografia();
        $data = array();
        $view = new View();
        $obj = $obj->edit($_GET['id']);
        $data['obj'] = $obj;
        $data['tipobibliografiaPadres'] = $this->Select(array('id'=>'idpadre','name'=>'idpadre','table'=>'vista_tipobibliografia','code'=>$obj->idpadre));
        $view->setData($data);
        $view->setTemplate( '../view/tipobibliografia/_Form.php' );
        $view->setLayout( '../template/Layout.php' );
        $view->render();
    }
    public function save(){
        $obj = new tipobibliografia();
        if ($_POST['idtipo_bibliografia']=='') {
            $p = $obj->insert($_POST);
            if ($p[0]){
                header('Location: index.php?controller=tipobibliografia');
            } else {
            $data = array();
            $view = new View();
            $data['msg'] = $p[1];
            $data['url'] =  'index.php?controller=tipobibliografia';
            $view->setData($data);
            $view->setTemplate( '../view/_Error_App.php' );
            $view->setLayout( '../template/Layout.php' );
            $view->render();
            }
        } else {
            $p = $obj->update($_POST);
            if ($p[0]){
                header('Location: index.php?controller=tipobibliografia');
            } else {
            $data = array();
            $view = new View();
            $data['msg'] = $p[1];
            $data['url'] =  'index.php?controller=tipobibliografia';
            $view->setData($data);
            $view->setTemplate( '../view/_Error_App.php' );
            $view->setLayout( '../template/Layout.php' );
            $view->render();
            }
        }
    }
    public function delete(){
        $obj = new tipobibliografia();
        $p = $obj->delete($_GET['id']);
        if ($p[0]){
            header('Location: index.php?controller=tipobibliografia');
        } else {
        $data = array();
        $view = new View();
        $data['msg'] = $p[1];
        $data['url'] =  'index.php?controller=tipobibliografia';
        $view->setData($data);
        $view->setTemplate( '../view/_Error_App.php' );
        $view->setLayout( '../template/Layout.php' );
        $view->render();
        }
    }
    public function create() {
        $data = array();
        $view = new View();
        $data['tipobibliografiasPadres'] = $this->Select(array('id'=>'idpadre','name'=>'idpadre','table'=>'vista_tipobibliografia'));
        $view->setData($data);
        $view->setTemplate( '../view/tipobibliografia/_Form.php' );
        $view->setLayout( '../template/Layout.php' );
        $view->render();
    }

}
?>


text:
static FATFS fatfs;

int test_sdhc_fat(void) {
  if(CLOCK_GetBusClkFreq() < SD_CLOCK_25MHZ) {
    PRINTF("- SDHC requirement (bus clock: %d < %d)\r\n", CLOCK_GetBusClkFreq(), SD_CLOCK_25MHZ);
    return -1;
  }

  sdhc_init();
  MPU_Enable(MPU, false);

  uint32_t card_inserted = GPIO_ReadPinInput(BOARD_SDHC_DET_GPIO, BOARD_SDHC_DET_PIN);
  ASSERT_TRUE(card_inserted);
  //  delay(1000U);

  const TCHAR driverNumberBuffer[3U] = {SDDISK + '0', ':', '/'};
  ASSERT_TRUE(f_mount(&fatfs, driverNumberBuffer, 0U) == FR_OK);
  ASSERT_TRUE(f_chdrive((char const *) &driverNumberBuffer[0U]) == FR_OK);

  FIL testFileObject;
  uint8_t buffer[128];
  UINT size;
  memset(buffer, 0U, sizeof(buffer));
  for (int i = 0; i < sizeof(buffer); i++) buffer[i] = (uint8_t) (' ' + i);
  f_unlink(_T("/test.txt"));
  ASSERT_TRUE(!f_open(&testFileObject, _T("/test.txt"), FA_CREATE_ALWAYS | FA_WRITE));
  ASSERT_TRUE(!f_write(&testFileObject, buffer, sizeof(buffer), &size));
  ASSERT_TRUE(!f_close(&testFileObject));
  ASSERT_TRUE(size == 128);

  memset(buffer, 0U, sizeof(buffer));
  ASSERT_TRUE(!f_open(&testFileObject, _T("/test.txt"), FA_READ));
  ASSERT_TRUE(!f_read(&testFileObject, buffer, sizeof(buffer), &size));
  ASSERT_TRUE(size != 0);
  ASSERT_TRUE(size == 128);

  ASSERT_TRUE(!f_close(&testFileObject));

  return 0;
}

#else
int test_sdhc_fat(void) {
  return 0;
}
#endif


text:
require File.join(File.dirname(__FILE__), "..", "spec_helper")

describe "project:create" do

	before do
		create_project_dir
	end

	after do
		delete_project_dir
	end

	it "should not create a new project if no valid directory is supplied" do
		expect { Glyph.run! 'project:create', 'test_dir' }.to raise_error
	end

	it "should create a new project if an existing empty directory is supplied" do
		expect { Glyph.run! 'project:create', Glyph::PROJECT }.not_to raise_error
		expect((Glyph::PROJECT/'lib').exist?).to eq(true)
		expect((Glyph::PROJECT/'document.glyph').exist?).to eq(true)
		expect((Glyph::PROJECT/'config.yml').exist?).to eq(true)
		expect((Glyph::PROJECT/'text').exist?).to eq(true)
		expect((Glyph::PROJECT/'styles').exist?).to eq(true)
		expect((Glyph::PROJECT/'images').exist?).to eq(true)
		expect((Glyph::PROJECT/'output').exist?).to eq(true)
	end

	it "should create a project in a directory containing just Gemfiles or hidden files" do
		file_write Glyph::PROJECT/".test", "..."
		file_write Glyph::PROJECT/"Gemfile", "..."
		expect { Glyph.run! 'project:create', Glyph::PROJECT }.not_to raise_error
	end
end

describe "project:add" do

	before do
		create_project_dir
	end

	after do
		delete_project_dir
	end

	it "should add new files to project" do
		create_project
		expect { Glyph.run 'project:add', 'test.textile'}.not_to raise_error
		expect((Glyph::PROJECT/'text/test.textile').exist?).to eq(true)
		expect { Glyph.run 'project:add', 'test.textile'}.to raise_error
		expect { Glyph.run 'project:add', 'chapter1/test.textile'}.not_to raise_error
		expect((Glyph::PROJECT/'text/chapter1/test.textile').exist?).to eq(true)
	end

end


text:
require "dm_ecommerce/engine"

module DmEcommerce
end


text:
require 'uri'

module Banzai
  module Filter
    # HTML filter that "fixes" links to pages/files in a wiki.
    # Rewrite rules are documented in the `WikiPipeline` spec.
    #
    # Context options:
    #   :project_wiki
    class WikiLinkFilter < HTML::Pipeline::Filter
      def call
        return doc unless project_wiki?

        doc.search('a:not(.gfm)').each do |el|
          process_link_attr el.attribute('href')
        end

        doc
      end

      protected

      def project_wiki?
        !context[:project_wiki].nil?
      end

      def process_link_attr(html_attr)
        return if html_attr.blank?

        html_attr.value = apply_rewrite_rules(html_attr.value)
      rescue URI::Error, Addressable::URI::InvalidURIError
        # noop
      end

      def apply_rewrite_rules(link_string)
        Rewriter.new(link_string, wiki: context[:project_wiki], slug: context[:page_slug]).apply_rules
      end
    end
  end
end


text:
package archive

import (
	"context"

	"go-common/app/admin/main/videoup/model/archive"
	"go-common/library/database/sql"
	"go-common/library/log"
)

const (
	_taskUserCheckInSQL  = "INSERT INTO task_consumer (uid,state) VALUES (?,1) ON DUPLICATE KEY UPDATE state = 1"
	_taskUserCheckOffSQL = "UPDATE task_consumer SET state = 0 WHERE uid=?"
	_consumersSQL        = "SELECT id,uid,state,ctime,mtime FROM task_consumer where state=1"
	_isConsumerOnSQL     = "SELECT state FROM task_consumer WHERE uid=?"
)

// TaskUserCheckIn insert or update task consumer check state
func (d *Dao) TaskUserCheckIn(c context.Context, uid int64) (rows int64, err error) {
	res, err := d.db.Exec(c, _taskUserCheckInSQL, uid)
	if err != nil {
		log.Error("tx.Exec(%s, %d) error(%v)", _taskUserCheckInSQL, uid, err)
		return
	}
	return res.RowsAffected()
}

// TaskUserCheckOff update task consumer check state
func (d *Dao) TaskUserCheckOff(c context.Context, uid int64) (rows int64, err error) {
	res, err := d.db.Exec(c, _taskUserCheckOffSQL, uid)
	if err != nil {
		log.Error("tx.Exec(%s, %d) error(%v)", _taskUserCheckOffSQL, uid, err)
		return
	}
	return res.RowsAffected()
}

// Consumers 用户列表
func (d *Dao) Consumers(c context.Context) (cms []*archive.Consumers, err error) {
	rows, err := d.rddb.Query(c, _consumersSQL)
	if err != nil {
		log.Error("d.rddb.Query(%s) error(%v)", _consumersSQL, err)
		return
	}
	defer rows.Close()
	for rows.Next() {
		cm := new(archive.Consumers)
		err = rows.Scan(&cm.ID, &cm.UID, &cm.State, &cm.Ctime, &cm.Mtime)
		if err != nil {
			log.Error("rows.Scan error(%v)", err)
			return
		}
		cms = append(cms, cm)
	}
	return
}

// IsConsumerOn 判断是否登入
func (d *Dao) IsConsumerOn(c context.Context, uid int64) (state int8) {
	err := d.rddb.QueryRow(c, _isConsumerOnSQL, uid).Scan(&state)
	if err != nil {
		if err != sql.ErrNoRows {
			log.Error("d.rddb.QueryRow error(%v)", err)
		}
	}
	return
}


text:
As the Commander (developer), you planned a few set of operations. You expect them
to run smoothly when you're not there (outside of your environement).
But this was without counting Juan (user). This charimastic pain in this ass
will mess with everything you planned, he will push everyone to the edge
if possible at the multiple times and concurrently. eventually, Elvira,
you beloved daugther will come back to you after an emotional crash (report).

This Framework is all about providing you an easy fluent api, to define operations in
your code (for instance viewmodels), and avoid Juan messing with you once and for all
so you may rest in peace !

If you don't get this introduction, pleas read the `Get Started` or
read `Dom Juan` from the french write `Molière` or rush on your next
local Opera playing of `Don Gionvanni` from the infamous `Mozart`.

## Get Started

Let's say you have a `ViewModel` for a quote wich exposes to methods
one to delete the quote one to place the order.
```csharp
public Task Order();
public Task Delete();
```

It's quite common sense that both operations cannot be executed at the
same time. With tradionnal programming you may start adding booleans,
binding to them and so on. But this create quite a lot of boilerplate
each time you need it (event with tradionnal commands things can get messy).

With Commander, you may write the following :
```csharp

public QuoteViewModel() {

	this.Order = Operation.For(OnOrder);
	this.Delete = Operation.For(OnDelete).Exclusive(this.Order);
}

public IOperation Order { get; }
public IOperation Delete { get; }

private Task OnOrder();
private Task OnDelete();
```

With the following code, `Delete` won't be callable while Order
is processing.

## Features

* Fire and Forget tooling to prevent friendly fire and back fire.
* Cancellability support
* Exclusive execution: One way exclusive execution
* Exclusivity sets [Coming soon] : easily implement mutually exclusive set of operation
* Polly support [Coming soon]
* `ICommand` bridge
* Xamarin.IOS operation linker [Coming soon] (so you can use us with or without an MVVM Framework)
* Xamarin.Android operation linker [Coming soon]


text:
import { getRandomArbitrary } from "utils";
import { SpriteWidth, SpriteHeight, Border } from "Constants";

import Chandelier from "objects/Chandelier";

const MaxChandelier = 5;

class ChandelierLayer extends Phaser.Group {

  constructor(game, parent, name) {
    super(game, parent, name);
    const nbChandelier = getRandomArbitrary(0, MaxChandelier);
    for(let i = 0; i < nbChandelier; i++) {
      const x = getRandomArbitrary(2 * Border, game.world.bounds.width - SpriteWidth - 2 * Border);
      const y = getRandomArbitrary(2 * Border, game.world.bounds.height - SpriteHeight - 2 * Border);
      this.addChandelier(x,y);
    }
  }

  addChandelier(x, y) {
    const chandelier = new Chandelier(this.game, x, y);
    this.add(chandelier);
  }

  clear() {
    this.children.forEach(chandelier => {
      this.remove(chandelier);
    });
  }

}

export default ChandelierLayer;


text:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';

import App from './ui/app';
import store from './store';

const container = document.getElementById('app-container');

window.onload = () => {
    setTimeout(() => {
        const isMobile = /mobile/i.test(navigator.userAgent);

        const width = isMobile ? window.innerWidth : 320;
        const height = isMobile ? window.innerHeight : 568;

        const style = {
            display: 'flex',
            flexDirection: 'column',
            height: isMobile ? height : '100vh',
            width: isMobile ? width : '100%',
            alignItems: 'center',
            justifyContent: 'center',
        };

        const provider = <Provider store={store}>
            <div style={style} onMouseDown={e => e.preventDefault()}>
                <App width={width} height={height} />
            </div>
        </Provider>;

        ReactDOM.render(provider, container);
    }, 50);
};


text:
var $list = document.getElementById("search");
$list.onclick = function()
{
  window.location.href = "add.html";
}

var $about = document.getElementById("about");
$about.onclick = function()
{
  window.location.href = "about.html";
}

function List_FH_from_localStorage()
{
  var fiche_horaire = {};
  var fiche_horaire_json;

  LSlength = localStorage.length;
  if (LSlength == 0)
  {
    document.getElementById("liste").innerHTML = "
\

Vous n'avez pas de fiches horaires enregistrées. Commencez par rechercher un arrêt

"
  }
  else
  {
    document.getElementById("liste").innerHTML = '';
    for (i=0; i<LSlength; i++)
    {
      if (localStorage.key(i).indexOf(FH_version) == -1)
      {
        alert("une nouvelle version de l'application est disponible, vos favoris ont été réinitialisés.");
        localStorage.clear();
        document.getElementById("liste").innerHTML = "

Vous n'avez pas de fiches horaires enregistrées. Commencez par rechercher un arrêt

"
      }
      else
      {
          fiche_horaire = $.parseJSON(localStorage[localStorage.key(i)]);
          var div_list = document.createElement("div");
          dep_id = "departure_" + fiche_horaire.code_route + "_" + fiche_horaire.code_arret;
          lien = 'FH.html#fromliste?route='+ fiche_horaire.code_route +'&arret='+ fiche_horaire.code_arret;
          div_list.className = "panel panel-warning";
          var div_header = document.createElement("div");
          div_header.className = "panel-heading";
          div_header.innerHTML = ''+fiche_horaire.arret+'';
          div_list.appendChild(div_header);

          var div_content = document.createElement("div");
          div_content.className = "panel-body";
          div_content.innerHTML += '
Bus '+fiche_horaire.ligne+' ('+fiche_horaire.reseau+')
'
          div_content.innerHTML += '
vers '+fiche_horaire.direction+'
'
          div_content.innerHTML += '' + '--' + '
'
          div_content.innerHTML += 'Supprimer'
          div_content.innerHTML += 'Tous les horaires'
          div_list.appendChild(div_content);

          document.getElementById("liste").appendChild(div_list);

          Navitia_get_next_dep(fiche_horaire.code_arret, fiche_horaire.code_route)

          //gestion de la suppression
          document.getElementById(localStorage.key(i)).onclick = function()
          {
            localStorage.removeItem(this.id);
            alert('Cette fiche horaire a bien été supprimée');
            List_FH_from_localStorage();
          }
      }
    }
  }
}

function Navitia_get_next_dep(code_arret,code_route)  {
   console.log('appel navitia : récupération des prochains passages')
   var now = new Date()
   var navitia_params = "routes/" + code_route + "/stop_areas/" + code_arret + "/departures?from_datetime=" + now.toISOString();
   //console.log(navitia_params);
   $.ajax({
        url: "https://api.navitia.io/v1/coverage/"+ navitia_coverage + "/" + navitia_params,
        dataType: 'json',
        global: true,
        error: function(data) {console.log("échec de l'appel navitia - on doit être hors ligne'")},
        success: function(data) {
            //console.log(data['departures']) //DEBUG
            var next_dep = "";
            //je ne veux garder que le prochain passage
            for (var i = 0; i < 1; ++i) {
                heures = data['departures'][i]['stop_date_time']['departure_date_time'].slice(9, 11).toString();
                minutes = data['departures'][i]['stop_date_time']['departure_date_time'].slice(11, 13).toString();
                next_dep += " -->" + heures + "h" + minutes;
                }
            dep_id = "departure_" + code_route + "_" + code_arret
            document.getElementById(dep_id).innerHTML = next_dep

            }
        });

}

/* intelligence de la page */
$(document).ready(function(){
    $.material.init();
    $.ajaxSetup( {
       beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "Basic " + btoa(navitia_api_key + ":" )); }
       });

    List_FH_from_localStorage();

});


text:
module FileReaderTest
  module Getbyte
    def test_getbyte
      file = file_containing("pīhoihoi")

      assert_equal 0x70, file.getbyte
      assert_equal 0xC4, file.getbyte
      assert_equal 0xAB, file.getbyte
    end

    def test_getbyte_increments_pos
      file = file_containing("tauhou")

      file.getbyte
      assert_equal 1, file.pos
      file.getbyte
      assert_equal 2, file.pos
    end

    def test_getbyte_at_eof_returns_nil
      assert_nil file_at_eof.getbyte
    end

    def test_cannot_getbyte_when_closed
      assert_raises IOError do
        closed_file.getbyte
      end
    end
  end
end