text:
var htmlEditorObject = function() {
  var that = {};
  that.mainTarget = y$('mainTarget');
  that.status = y$('status');

  /* DragAndDrop */
  that.componentDropped = function(aDraggedElement) {
    var componentName = aDraggedElement.getAttribute("data-component");
    var newId = function() {
      return dec2hex(Math.floor(((new Date()).getTime() - 1542657731593) / 10));
    }

    var addButtons = function(parentNode) {
      var c = 0;
      var buttonsSpace = document.createElement("div");
      var buttons = ['fa-times', 'fa-caret-square-o-left', 'fa-caret-square-o-right', 'fa-wrench'];
      var buttonsClass = ['btn-warning', 'btn-success', 'btn-success', 'btn-info'];

      var classNameT = "target-" + newId();
      var classDefinitionT = extractStyleRule('.target-model');
      createStyleRule(classNameT, classDefinitionT);

      var classNameBO = "button-overlap-" + newId();
      var classDefinitionBO = extractStyleRule('.button-overlap-model');
      createStyleRule(classNameBO, classDefinitionBO);

      createStyleRule("{0}:hover {1}".format(classNameT, classNameBO));

      buttonsSpace.addClass(classNameBO);
      for (c = 0; c < buttons.length; c++) {
        buttonsSpace.innerHTML += "<button type='button' class='btn-xs {0}'></button>".format(buttonsClass[c], buttons[c]);
      }
      parentNode.appendChild(buttonsSpace);
      parentNode.addClass(classNameT);
    }

    if (componentName == "rowsplace") {
      var colDef = (y$('rowplace').value || '').replace(/\ \ /g, " ");
      var columns = colDef.split(' ');
      var c, t = 0;
      for (c = 0; c < columns.length; c++) {
        t += str2int(columns[c]);
      }
      if ((t > 0) && (t <= 12)) {
        var row = document.createElement("div");
        this.appendChild(row);
        row.addClass("row");
        row.addClass("target");
        row.ondrop = that.componentDropped;
        row.ondragover = that.componentDraggedOver;

        for (c = 0; c < columns.length; c++) {
          if (str2int(columns[c])) {
            var col = document.createElement("div");
            col.addClass("col-md-{0}".format(columns[c]));
            col.addClass("target");
            col.setAttribute("droppable", "yes");
            col.ondrop = that.componentDropped;
            col.ondragover = that.componentDraggedOver;
            row.appendChild(col);
            addButtons(col);
          }
        }
      }
    } else {
      var re = /id\=([\"A-Za-z_\-0-9]+)/g;
      var innerHTML = aDraggedElement.innerHTML;
      var result;
      var shuffle = dec2hex(Math.floor(((new Date()).getTime() - 1542657731593) / 100));
      var replacements = [];
      while (result = re.exec(innerHTML)) {
        var toSearch = result[0];
        var id = (result[1] || '').unquote();
        var newId = id + "_" + shuffle;
        replacements[toSearch] = toSearch.replace(id, newId);
        replacements[id] = newId;
      }
      for (var rep in replacements) {
        if (replacements.hasOwnProperty(rep)) {
          var toReplace = new RegExp(rep, "g");
          innerHTML = innerHTML.replace(toReplace, replacements[rep]);
        }
      }
      var div = document.createElement("div");
      div.innerHTML = innerHTML;
      div.id = componentName + "_" + shuffle;
      div.addClass("editable-component");
      this.appendChild(div);
      var childs = div.getElementsByTagName("*");
      for (var i = 0; i < childs.length; i++) {
        if (childs[i].nodeName != "DIV")
          childs[i].setAttribute("contenteditable", "true");
      }
    }
  };

  that.componentDraggedOver = function(aDraggedElement) {
    var componentName = aDraggedElement.getAttribute("data-component");
    var canUseRow = (((this.hasClass('row')) || (this.id == 'mainTarget')) && (componentName == 'rowsplace'));
    var canUseCol = ((this.hasClass('col-*')) && (componentName != 'rowsplace'));
    var ret = (this.nodeName == 'DIV') &&
      (canUseRow || canUseCol);
    if (that.status) {
      that.status.innerHTML = "Component: {0} Target: {1}/{2} {3} or {4} = {5}".format(componentName, this.id, this.nodeName, bool2str(canUseRow), bool2str(canUseCol), bool2str(ret));
    }
    return ret;
  };

  /* fill columns per line */
  that.chooseRowColumns = function(e) {
    if (e) {
      e = e.target;
      if (e) {
        var columns = (e.innerHTML || '').split('+');
        var rowplace = y$('rowplace');
        if (rowplace) {
          rowplace.value = columns.join(" ");
        }
      }
    }
  };

  function process(str) {

    var div = document.createElement('div');
    div.innerHTML = str.trim().replace(/\s{2,}/g, ' ');

    return format(div, 0).innerHTML;
  }

  function format(node, level) {

    var indentBefore = new Array(level++ + 1).join('  '),
      indentAfter = new Array(level - 1).join('  '),
      textNode;

    for (var i = 0; i < node.children.length; i++) {

      textNode = document.createTextNode('\n' + indentBefore);
      node.insertBefore(textNode, node.children[i]);

      format(node.children[i], level);

      if (node.lastElementChild == node.children[i]) {
        textNode = document.createTextNode('\n' + indentAfter);
        node.appendChild(textNode);
      }
    }

    return node;
  }

  that.prepareToDownload = function(e) {
    var mainTarget = y$("mainTarget");
    var buttons=getElementsByClassName(mainTarget, 'div', 'button-overlap-*');
    var b=buttons.length;
    while (b>0) {
      var btn=buttons[b-1].parentNode;
      btn.removeChild(buttons[b-1]);
      b--;
    }

    var html = mainTarget.innerHTML;
    html=html.replace(/class\=\"editable-component\"/gim, ' ' );
    html=html.replace(/contenteditable\=\"true\"/gim, ' ' );
    html=html.replace(/droppable\=\"yes\"/gim, ' ' );
    html=html.replace(/target\-[0-9,a-z\_]+/gim, ' ' );
    html=html.replace(/target\b/gim, ' ' );
    html=html.replace(/\ \"/gim, '"' );
    y$("textToDownload").innerText = process(html);
  }

  function download(filename, text) {
    var element = document.createElement('a');
    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    element.setAttribute('download', filename);

    element.style.display = 'none';
    document.body.appendChild(element);

    element.click();

    document.body.removeChild(element);
  }

  that.downloadSourceCode = function() {
    var filename=y$('blockOfCodeFilename').value.trim();
    if (filename>'') {
      download(filename, y$("textToDownload").innerText);
    }
  }

  var init = function() {
    mainTarget.ondrop = that.componentDropped;
    mainTarget.ondragover = that.componentDraggedOver;
    addEvent(".btn-choose-rowcolumns", "click", that.chooseRowColumns);
    addEvent("btnDownladPage", "click", that.prepareToDownload);
    addEvent("btnSaveSourceCode", "click", that.downloadSourceCode);
    return that;
  }

  return init();
}

var htmlEditor;

addOnLoadManager(function() {
  htmlEditor = htmlEditorObject();
});


text:
<?php
namespace Vidal\MainBundle\Service;

use Symfony\Component\Form\ChoiceList\LegacyChoiceListAdapter;
use Sonata\AdminBundle\Form\ChoiceList\ModelChoiceList;

class PatchedModelsToArrayTransformer extends \Sonata\AdminBundle\Form\DataTransformer\ModelsToArrayTransformer
{
    public function __construct($choiceList)
    {
        if ($choiceList instanceof LegacyChoiceListAdapter) {
            $this->choiceList = $choiceList->getAdaptedList();
        } else if ($choiceList instanceof ModelChoiceList) {
            $this->choiceList = $choiceList;
        } else {
            throw new \InvalidArgumentException('Argument 1 must be an instance of Sonata\AdminBundle\Form\ChoiceList\ModelChoiceList or Symfony\Component\Form\ChoiceList\LegacyChoiceListAdapter');
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
You can pass parameters to your build script using the "parameters" parameter of the Invoke-psake function.  The following is an example:

 C:\PS>Invoke-psake .\parameters.ps1 -parameters @{"p1"="v1";"p2"="v2"}

The example above runs the build script called "parameters.ps1" and passes in parameters 'p1' and 'p2' with values 'v1' and 'v2'.  The parameter value for the "parameters" parameter (say that 10 times really fast!) is a PowerShell hashtable where the name and value of each parameter is specified. Note:  You don't need to use the "$" character when specifying the parameter names in the hashtable.

The "parameters.ps1" build script looks like this:

properties {
  $my_property = $p1 + $p2
}

task default -depends TestParams

task TestParams {
  Assert ($my_property -ne $null) '$my_property should not be null'
}


text:
//
//  TCloudCall.h
//  TYJYCloudCall
//
//  Created by DF on 16/6/13.
//  Copyright © 2016年 tyjy. All rights reserved.
//

#import <Foundation/Foundation.h>

/** remain

 0      :操作成功
 1000   :业务类型不支持
 1001   :加密错误
 1002   :参数错误/带入参数异常
 1003   :无效产品ID
 1004   :未审核产品
 1005   :审核失败的产品
 1006   :暂停使用的产品ID
 1007   :未授权的ip
 1008   :无可以使用的小号资源
 1009   :无权操作

 **/

typedef void(^bindingHandler)(id responseObject, NSInteger remain, NSString *returnMessage);
typedef void(^unBindingHandler)(NSInteger remain, NSString *returnMessage);

/** TCloudCall:开发者使用主类(API)
 */
@interface TCloudCall : NSObject

/** 初始化云通话模块
 @param appKey 云通讯appKey.
 @return void
 */
+ (void)startWithAppkey:(NSString *)appKey;

/** 双盲通话:设备主号绑定小号
 @param mainPhone 本机主叫号码
 @param calledPhone 被叫号码
 @param handle remain为0表示正常,为-1时表示异常,message 返回错误提示
 @return void
 */
+ (void)bindingCloudPhone:(NSString *)mainPhone calledPhone:(NSString *)calledPhone response:(bindingHandler)handle;

/** 双盲通话:设备主号解绑小号
 @param mainPhone 本机主叫号码
 @param calledPhone 被叫号码
 @param handle remain为0表示正常,为-1时表示异常,message 返回错误提示
 @return void
 */
+ (void)unBindingCloudPhone:(NSString *)mainPhone calledPhone:(NSString *)calledPhone response:(unBindingHandler)handle;

/** 隐私通话:设备主号绑定小号
 @param mainPhone 本机主叫号码
 @param handle remain为0表示正常,为-1时表示异常,message 返回错误提示
 @return void
 */
+ (void)bindingCloudPhone:(NSString *)mainPhone response:(bindingHandler)handle;

/** 隐私通话:设备主号解绑小号
 @param mainPhone 本机主叫号码
 @param handle remain为0表示正常,为-1时表示异常,message 返回错误提示
 @return void
 */
+ (void)unBindingCloudPhone:(NSString *)mainPhone response:(unBindingHandler)handle;

@end


text:
import { getWrapperWithMap, see } from '@/tests/test-helpers';
import LControlZoom from '@/components/LControlZoom.vue';

describe('component: LControlZoom.vue', () => {
  test('LControlZoom.vue has a mapObject', () => {
    const { wrapper } = getWrapperWithMap(LControlZoom);

    expect(wrapper.vm.mapObject).toBeDefined();
  });

  // Leaflet Control options

  test('LControlZoom.vue accepts and uses the Leaflet position option', () => {
    const { wrapper } = getWrapperWithMap(LControlZoom, { position: 'bottomleft' });

    expect(wrapper.vm.mapObject.getPosition()).toBe('bottomleft');
  });

  // Leaflet Control.Zoom options

  test('LControlZoom.vue includes "zoomInText" in rendered html', async () => {
    const { mapWrapper } = getWrapperWithMap(LControlZoom, { zoomInText: 'BIGGER' });

    see(mapWrapper, 'BIGGER');
  });

  test('LControlZoom.vue includes "zoomInTitle" in rendered html', () => {
    const { mapWrapper } = getWrapperWithMap(LControlZoom, { zoomInTitle: 'zoom in more' });

    see(mapWrapper, 'zoom in more');
  });

  test('LControlZoom.vue includes "zoomOutText" in rendered html', () => {
    const { mapWrapper } = getWrapperWithMap(LControlZoom, { zoomOutText: 'smaller' });

    see(mapWrapper, 'smaller');
  });

  test('LControlZoom.vue includes "zoomOutTitle" in rendered html', () => {
    const { mapWrapper } = getWrapperWithMap(LControlZoom, { zoomOutTitle: 'zoom out a bit' });

    see(mapWrapper, 'zoom out a bit');
  });

  // Leaflet Control set* methods

  test('LControlZoom.vue updates the mapObject when the "position" prop is set', async () => {
    const { wrapper } = getWrapperWithMap(LControlZoom, { position: 'bottomleft' });
    wrapper.setProps({ position: 'topright' });
    await wrapper.vm.$nextTick();

    expect(wrapper.vm.mapObject.getPosition()).toBe('topright');
  });
});


text:
import { EventEmitter } from '@angular/core';

import { Component, ElementRef, Input, OnDestroy, Output } from '@angular/core';
import 'rxjs/add/operator/delay';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import { DejaTile } from './tile.class';
import { IDejaTilesModelEvent } from './tiles.event';

@Component({
    selector: 'deja-tile',
    styleUrls: [
        './tile.component.scss',
    ],
    templateUrl: './tile.component.html',
})
export class DejaTileComponent implements OnDestroy {
    @Input() public template;
    @Input() public designMode;
    @Output() public modelChanged = new EventEmitter<IDejaTilesModelEvent>();
    @Output() public close = new EventEmitter<Event>();

    public element: HTMLElement;

    private _tile: DejaTile;
    private subscriptions = [] as Subscription[];

    constructor(el: ElementRef) {
        this.element = el.nativeElement as HTMLElement;
        this.element.setAttribute('hidden', '0');
    }

    @Input()
    public set tile(tile: DejaTile) {
        this._tile = tile;

        if (tile) {
            const toogleAttribute = (attribute: string, value: string | boolean) => {
                if (value) {
                    this.element.setAttribute(attribute, value.toString());
                } else {
                    this.element.removeAttribute(attribute);
                }
            };

            if (tile.fading) {
                this.element.setAttribute('fading', '0');
            }

            this.subscriptions.push(Observable.from(tile.pixelBounds$)
                .first()
                .filter(() => tile.fading)
                .do(() => this.element.setAttribute('fading', '1'))
                .delay(200)
                .subscribe(() => {
                    this.element.removeAttribute('fading');
                }));

            this.subscriptions.push(Observable.from(tile.pixelBounds$)
                .subscribe((bounds) => {
                    if (!tile.isHidden) {
                        this.element.removeAttribute('hidden');
                    }
                    this.element.style.left = `${bounds.left}px`;
                    this.element.style.top = `${bounds.top}px`;
                    this.element.style.width = `${bounds.width}px`;
                    this.element.style.height = `${bounds.height}px`;
                }));

            this.subscriptions.push(Observable.from(tile.pressed$).subscribe((value) => toogleAttribute('pressed', value)));
            this.subscriptions.push(Observable.from(tile.selected$).subscribe((value) => toogleAttribute('selected', value)));
            this.subscriptions.push(Observable.from(tile.dragging$).subscribe((value) => toogleAttribute('drag', value)));
            this.subscriptions.push(Observable.from(tile.dropping$).subscribe((value) => toogleAttribute('drop', value)));
            this.subscriptions.push(Observable.from(tile.cutted$).subscribe((value) => toogleAttribute('cutted', value)));
            this.subscriptions.push(Observable.from(tile.expanded$).subscribe((value) => toogleAttribute('expanded', value)));

            this.subscriptions.push(Observable.from(tile.deleted$).subscribe(() => this.element.remove()));

            const tooogleHide$ = Observable.from(tile.hidden$)
                .do((value) => {
                    toogleAttribute('hidden', value ? '1' : '2');
                });

            // Hide
            this.subscriptions.push(tooogleHide$
                .debounceTime(1000)
                .filter((value) => value)
                .subscribe(() => this.element.setAttribute('hidden', '0')));

            // Show
            this.subscriptions.push(tooogleHide$
                .debounceTime(1)
                .filter((value) => !value)
                .subscribe(() => this.element.removeAttribute('hidden')));

        } else {
            this.subscriptions.forEach((subscription) => subscription.unsubscribe());
            this.subscriptions = [];
        }
    }

    public get tile() {
        return this._tile;
    }

    public ngOnDestroy() {
        this.subscriptions.forEach((subscription) => subscription.unsubscribe());
    }
}


text:
Class ProjectRef
{
    [string] $ProjectLocation;
    [string] $TestsLocation;
    ProjectRef([string] $project, [string] $tests)
    {
        $this.ProjectLocation = $project;
        $this.TestsLocation = $tests;
    }

    BuildAndTest([string] $name)
    {
        Write-Host "Building packages for project '$name'";
        dotnet build $this.ProjectLocation -c Release | Write-Host -ForegroundColor DarkGray;
        if ($LastExitCode -ne 0)
        {
            Write-Host "Failed to build project" -ForegroundColor Red;
            return;
        }

        if (-not [String]::IsNullOrEmpty($this.TestsLocation))
        {
            Write-Host "Testing project '$name'";
            dotnet test $this.TestsLocation -c Release | Write-Host -ForegroundColor DarkGray;
            if ($LastExitCode -ne 0)
            {
                Write-Host "Package not published because of failed tests" -ForegroundColor Red;
                return;
            }
        }

        Write-Host "Packing project '$name'";
        dotnet pack $this.ProjectLocation -c Release -o D:\nugets | Write-Host -ForegroundColor DarkGray;
        if ($LastExitCode -ne 0)
        {
            Write-Host "Packing failed" -ForegroundColor Red;
            return;
        }
    }
}

if ($args.Length -eq 0)
{
    Write-Host "No args given.";
    return;
}

$projects = @{
    "MpGame" = [ProjectRef]::new("src\Discord.Addons.MpGame\Discord.Addons.MpGame.csproj", "test\MpGame.Tests\MpGame.Tests.csproj");
    "Preconditions" = [ProjectRef]::new("src\Discord.Addons.Preconditions\Discord.Addons.Preconditions.csproj", [String]::Empty);
    "SimplePermissions" = [ProjectRef]::new("src\Discord.Addons.SimplePermissions\Discord.Addons.SimplePermissions.csproj", [String]::Empty);
    "EFProvider" = [ProjectRef]::new("src\Discord.Addons.SimplePermissions.EFProvider\Discord.Addons.SimplePermissions.EFProvider.csproj", [String]::Empty);
};

# if ($args.Length -eq 1 -and $args[0] -eq "-clean")
# {
    # Write-Host "Cleaning up bins.";
    # foreach ($dir in [Directory]::EnumerateDirectories("src\", "bin", [SearchOption]::AllDirectories))
    # {
        # [Directory]::Delete($dir, true);
    # }

    # Write-Host "Cleaning up objs.";
    # foreach ($dir in [Directory]::EnumerateDirectories("src\", "obj", [SearchOption]::AllDirectories))
    # {
        # [Directory]::Delete($dir, true);
    # }

    # Write-Host "Cleaning up docs.";
    # foreach ($file in [Directory]::EnumerateFiles("docs\api\", "*.yml"))
    # {
        # [File]::Delete($file);
    # }
    # foreach ($file in [Directory]::EnumerateFiles("docs\site\api\", "*.html"))
    # {
        # [File]::Delete($file);
    # }

    # return;
# }

if ($args.Length -eq 1 -and $args[0] -eq "-all")
{
    foreach ($key in $projects.Keys)
    {
        $projects[$key].BuildAndTest($key);
    }
}
else
{
    foreach ($arg in $args)
    {
        if ($projects.ContainsKey($arg))
        {
            $projects[$arg].BuildAndTest($arg);
        }
    }
}

if ($LastExitCode -eq 0)
{
    Write-Host "Building docs";
    docfx "docs\docfx.json" | Write-Host -ForegroundColor DarkGray;
    if ($LastExitCode -ne 0)
    {
        Write-Host "Docs building failed" -ForegroundColor Red;
        return;
    }
}


text:
set -e

chown -R celery:celery /var/lib/celery
if [ "$1" = '/opt/django-venv/bin/gunicorn' ]; then
    dockerize -wait tcp://postgres:5432
    /opt/django-venv/bin/python /opt/app/manage.py migrate --noinput
    /opt/django-venv/bin/python /opt/app/manage.py collectstatic --noinput
    exec "$@"
fi

exec "$@"


text:
package com.eaw1805.data.managers.beans;

import com.eaw1805.data.model.Nation;
import com.eaw1805.data.model.army.ArmyType;

import java.util.List;

/**
 * The interface of the ArmyTypeManager.
 */
public interface ArmyTypeManagerBean extends EntityBean {

    /**
     * get the ArmyType from the database that corresponds to the input id.
     *
     * @param entityID the id of the Entity object.
     * @return an Entity object.
     */
    ArmyType getByID(final int entityID);

    /**
     * get the ArmyType from the database that corresponds to the input short-name and nation.
     *
     * @param entityShortName the name of the Entity object.
     * @param entityNation    the nation of the Entity object.
     * @return an Entity object.
     */
    ArmyType getByShortName(final String entityShortName, final Nation entityNation);

    /**
     * get the ArmyType from the database that corresponds to the input short-name and nation.
     *
     * @param intID        the internal ID of the Entity object.
     * @param entityNation the nation of the Entity object.
     * @return an Entity object.
     */
    ArmyType getByIntID(final int intID, final Nation entityNation);

    /**
     * adding a new entry into the database, according to the input object it
     * receives.
     *
     * @param value the ArmyType tha we want to add.
     */
    void add(final ArmyType value);

    /**
     * updating an entry into the database, according to the input object it
     * receives.
     *
     * @param value the ArmyType tha we want to update.
     */
    void update(final ArmyType value);

    /**
     * Delete the input ArmyType from the database.
     *
     * @param value the ArmyType tha we want to delete.
     */
    void delete(final ArmyType value);

    /**
     * Listing all the ArmyTypes from the database.
     *
     * @return a list of all the ArmyTypes that exist inside the table.
     */
    List<ArmyType> list();

    /**
     * Listing all the ArmyTypes from the database for the particular nation.
     *
     * @param entityNation the nation of the Entity object.
     * @return a list of all the ArmyTypes that exist inside the table TBL_ARMYTYPES.
     */
    List<ArmyType> list(final Nation entityNation);

}


text:
package com.b2international.snowowl.datastore.cdo;

import static com.google.common.base.Preconditions.checkNotNull;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.eclipse.emf.cdo.common.branch.CDOBranch;
import org.eclipse.emf.cdo.common.id.CDOID;
import org.eclipse.emf.cdo.common.revision.CDORevision;
import org.eclipse.emf.cdo.common.revision.delta.CDOFeatureDelta;
import org.eclipse.emf.cdo.common.revision.delta.CDORevisionDelta;
import org.eclipse.emf.cdo.common.revision.delta.CDOSetFeatureDelta;
import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision;
import org.eclipse.emf.cdo.transaction.CDOTransaction;
import org.eclipse.emf.cdo.view.CDOView;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.spi.cdo.DefaultCDOMerger;
import org.eclipse.emf.spi.cdo.DefaultCDOMerger.ChangedInTargetAndDetachedInSourceConflict;
import org.eclipse.emf.spi.cdo.DefaultCDOMerger.Conflict;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.b2international.commons.platform.Extensions;
import com.b2international.commons.time.TimeUtil;
import com.b2international.snowowl.core.exceptions.ConflictException;
import com.b2international.snowowl.core.exceptions.MergeConflictException;
import com.b2international.snowowl.core.merge.MergeConflict;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Stopwatch;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;

/**
 * Abstract superclass for {@link ICDOConflictProcessor}s that only want to report a subset of possible application-level conflicts.
 */
public abstract class AbstractCDOConflictProcessor implements ICDOConflictProcessor {

	protected static final Logger LOGGER = LoggerFactory.getLogger(ICDOConflictProcessor.class);

	private static final Map<EClass, EAttribute> EMPTY_MAP = ImmutableMap.of();

	private final String repositoryUuid;
	private final Map<EClass, EAttribute> releasedAttributeMap;

	private final IMergeConflictRuleProvider conflictRuleProvider;

	protected AbstractCDOConflictProcessor(final String repositoryUuid) {
		this(repositoryUuid, EMPTY_MAP);
	}

	protected AbstractCDOConflictProcessor(final String repositoryUuid, final Map<EClass, EAttribute> releasedAttributeMap) {
		checkNotNull(repositoryUuid, "Repository identifier may not be null.");
		checkNotNull(releasedAttributeMap, "EClass to released attribute map may not be null.");

		this.repositoryUuid = repositoryUuid;
		this.releasedAttributeMap = releasedAttributeMap;

		conflictRuleProvider = initializeConflictRuleProvider(repositoryUuid);
	}

	@Override
	public final String getRepositoryUuid() {
		return repositoryUuid;
	}

	/**
	 * {@inheritDoc}
	 *

	 * The default case will allow the add by returning {@code sourceRevision} (a {@link CDORevision}).
	 */
	@Override
	public Object addedInSource(final CDORevision sourceRevision, final Map<CDOID, Object> targetMap) {
		return sourceRevision;
	}

	/**
	 * {@inheritDoc}
	 *

	 * The default case will allow the add by returning {@code targetRevision} (a {@link CDORevision}).
	 */
	@Override
	public Object addedInTarget(final CDORevision targetRevision, final Map<CDOID, Object> sourceMap) {
		return targetRevision;
	}

	@Override
	public Object detachedInSource(CDOID id) {
		return id;
	}

	@Override
	public Object detachedInTarget(CDOID id) {
		return id;
	}

	protected Set<CDOID> getDetachedIds(final Map<CDOID, Object> revisionMap) {
		return ImmutableSet.copyOf(Iterables.filter(revisionMap.values(), CDOID.class));
	}

	protected Set<InternalCDORevision> getNewRevisions(final Map<CDOID, Object> revisionMap) {
		return ImmutableSet.copyOf(Iterables.filter(revisionMap.values(), InternalCDORevision.class));
	}

	@Override
	public Collection<MergeConflict> handleCDOConflicts(final CDOView sourceView, final CDOView targetView, final Map<CDOID, Conflict> conflicts) {
		if (!conflicts.isEmpty()) {
			return FluentIterable.from(conflicts.values()).transform(new Function<Conflict, MergeConflict>() {
				@Override public MergeConflict apply(Conflict input) {
					return ConflictMapper.convert(input);
				}
			}).toList();
		}
		return Collections.emptySet();
	}

	@Override
	public void preProcess(Map<CDOID, Object> sourceMap, Map<CDOID, Object> targetMap, CDOBranch sourceBranch, CDOBranch targetBranch, boolean isRebase) {
	}

	@Override
	public void postProcess(final CDOTransaction transaction) throws ConflictException {

		LOGGER.info("Post-processing merge/rebase operation...");
		Stopwatch stopwatch = Stopwatch.createStarted();

		List<MergeConflict> conflicts = FluentIterable.from(getConflictRules())
				.transformAndConcat(new Function<IMergeConflictRule, Collection<MergeConflict>>() {
					@Override
					public Collection<MergeConflict> apply(IMergeConflictRule input) {
						return input.validate(transaction);
					}
				}).toList();

		LOGGER.info("Post-processing took {}", TimeUtil.toString(stopwatch));

		if (!conflicts.isEmpty()) {
			throw new MergeConflictException(conflicts, "Domain specific conflicts detected while post-processing merge changes.");
		}
	}

	@Override
	public Collection<IMergeConflictRule> getConflictRules() {
		return conflictRuleProvider.getRules();
	}

	/**
	 * {@inheritDoc}
	 *

	 * The default case implements the same behavior as {@link DefaultCDOMerger.PerFeature}.
	 */
	@Override
	public CDOFeatureDelta changedInSourceAndTargetSingleValued(CDORevisionDelta targetDelta, CDOFeatureDelta targetFeatureDelta,
			CDORevisionDelta sourceDelta, CDOFeatureDelta sourceFeatureDelta) {

		if (targetFeatureDelta.isStructurallyEqual(sourceFeatureDelta)) {
			return targetFeatureDelta;
		}

		return null;
	}

	/**
	 * {@inheritDoc}
	 *

	 * The default case will check if the change did not involve releasing the component, and if so, reports a
	 * conflict; allows the removal otherwise.
	 */
	@Override
	public Object changedInTargetAndDetachedInSource(final CDORevisionDelta targetDelta) {

		final Conflict conflict = checkIsReleasedState(targetDelta);

		if (conflict != null) {
			return conflict;
		}

		return targetDelta.getID();
	}

	private Conflict checkIsReleasedState(final CDORevisionDelta revisionDelta) {

		final EClass eClass = revisionDelta.getEClass();

		Optional<EClass> releasableClass = FluentIterable.from(releasedAttributeMap.keySet()).firstMatch(new Predicate<EClass>() {
			@Override public boolean apply(EClass input) {
				return input.isSuperTypeOf(eClass);
			}
		});

		if (releasableClass.isPresent() && isReleased(revisionDelta, releasedAttributeMap.get(releasableClass.get()))) {
			return new ChangedInTargetAndDetachedInSourceConflict(revisionDelta);
		}

		return null;
	}

	private boolean isReleased(final CDORevisionDelta revisionDelta, final EAttribute releasedAttribute) {

		final CDOFeatureDelta releasedFeatureDelta = revisionDelta.getFeatureDelta(releasedAttribute);

		if (releasedFeatureDelta instanceof CDOSetFeatureDelta) {
			return (boolean) ((CDOSetFeatureDelta) releasedFeatureDelta).getValue();
		}

		return false;
	}

	private IMergeConflictRuleProvider initializeConflictRuleProvider(final String repositoryUuid) {

		Collection<IMergeConflictRuleProvider> ruleProviders = Extensions.getExtensions(IMergeConflictRuleProvider.EXTENSION_ID, IMergeConflictRuleProvider.class);
		Optional<IMergeConflictRuleProvider> ruleProvider = FluentIterable.from(ruleProviders).firstMatch(new Predicate<IMergeConflictRuleProvider>() {
			@Override
			public boolean apply(IMergeConflictRuleProvider ruleProvider) {
				return ruleProvider.getRepositoryUUID().equals(repositoryUuid);
			}
		});

		return ruleProvider.isPresent() ? ruleProvider.get() : new IMergeConflictRuleProvider.NullImpl(repositoryUuid);
	}
}


text:
<?php

namespace DTS\eBaySDK\MerchantData\Types;

/**
 *
 * @property string $RefundOption
 * @property string $Refund
 * @property string $ReturnsWithinOption
 * @property string $ReturnsWithin
 * @property string $ReturnsAcceptedOption
 * @property string $ReturnsAccepted
 * @property string $Description
 * @property string $WarrantyOfferedOption
 * @property string $WarrantyOffered
 * @property string $WarrantyTypeOption
 * @property string $WarrantyType
 * @property string $WarrantyDurationOption
 * @property string $WarrantyDuration
 * @property string $EAN
 * @property string $ShippingCostPaidByOption
 * @property string $ShippingCostPaidBy
 * @property string $RestockingFeeValue
 * @property string $RestockingFeeValueOption
 * @property boolean $ExtendedHolidayReturns
 */
class ReturnPolicyType extends \DTS\eBaySDK\Types\BaseType
{
    /**
     * @var array Properties belonging to objects of this class.
     */
    private static $propertyTypes = array(
        'RefundOption' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'RefundOption'
        ),
        'Refund' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'Refund'
        ),
        'ReturnsWithinOption' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'ReturnsWithinOption'
        ),
        'ReturnsWithin' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'ReturnsWithin'
        ),
        'ReturnsAcceptedOption' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'ReturnsAcceptedOption'
        ),
        'ReturnsAccepted' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'ReturnsAccepted'
        ),
        'Description' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'Description'
        ),
        'WarrantyOfferedOption' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'WarrantyOfferedOption'
        ),
        'WarrantyOffered' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'WarrantyOffered'
        ),
        'WarrantyTypeOption' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'WarrantyTypeOption'
        ),
        'WarrantyType' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'WarrantyType'
        ),
        'WarrantyDurationOption' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'WarrantyDurationOption'
        ),
        'WarrantyDuration' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'WarrantyDuration'
        ),
        'EAN' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'EAN'
        ),
        'ShippingCostPaidByOption' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'ShippingCostPaidByOption'
        ),
        'ShippingCostPaidBy' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'ShippingCostPaidBy'
        ),
        'RestockingFeeValue' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'RestockingFeeValue'
        ),
        'RestockingFeeValueOption' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'RestockingFeeValueOption'
        ),
        'ExtendedHolidayReturns' => array(
            'type' => 'boolean',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'ExtendedHolidayReturns'
        )
    );

    /**
     * @param array $values Optional properties and values to assign to the object.
     */
    public function __construct(array $values = array())
    {
        list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values);

        parent::__construct($parentValues);

        if (!array_key_exists(__CLASS__, self::$properties)) {
            self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes);
        }

        if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) {
            self::$xmlNamespaces[__CLASS__] = 'urn:ebay:apis:eBLBaseComponents';
        }

        $this->setValues(__CLASS__, $childValues);
    }
}


text:
"""
Find an Android device with a given ABI.

The name of the Android device is printed to stdout.

Optionally configure and launch an emulator if there's no existing device for a
given ABI. Will download and install Android SDK components as needed.
"""

import optparse
import os
import re
import sys
import traceback
import utils

DEBUG = False
VERBOSE = False

def BuildOptions():
    result = optparse.OptionParser()
    result.add_option(
        "-a",
        "--abi",
        action="store",
        type="string",
        help="Desired ABI. armeabi-v7a or x86.")
    result.add_option(
        "-b",
        "--bootstrap",
        help=
        'Bootstrap - create an emulator, installing SDK packages if needed.',
        default=False,
        action="store_true")
    result.add_option(
        "-d",
        "--debug",
        help='Turn on debugging diagnostics.',
        default=False,
        action="store_true")
    result.add_option(
        "-v",
        "--verbose",
        help='Verbose output.',
        default=False,
        action="store_true")
    return result

def ProcessOptions(options):
    global DEBUG
    DEBUG = options.debug
    global VERBOSE
    VERBOSE = options.verbose
    if options.abi is None:
        sys.stderr.write('--abi not specified.\n')
        return False
    return True

def ParseAndroidListSdkResult(text):
    """
  Parse the output of an 'android list sdk' command.

  Return list of (id-num, id-key, type, description).
  """
    header_regex = re.compile(
        r'Packages available for installation or update: \d+\n')
    packages = re.split(header_regex, text)
    if len(packages) != 2:
        raise utils.Error("Could not get a list of packages to install")
    entry_regex = re.compile(
        r'^id\: (\d+) or "([^"]*)"\n\s*Type\: ([^\n]*)\n\s*Desc\: (.*)')
    entries = []
    for entry in packages[1].split('----------\n'):
        match = entry_regex.match(entry)
        if match == None:
            continue
        entries.append((int(match.group(1)), match.group(2), match.group(3),
                        match.group(4)))
    return entries

def AndroidListSdk():
    return ParseAndroidListSdkResult(
        utils.RunCommand(["android", "list", "sdk", "-a", "-e"]))

def AndroidSdkFindPackage(packages, key):
    """
  Args:
    packages: list of (id-num, id-key, type, description).
    key: (id-key, type, description-prefix).
  """
    (key_id, key_type, key_description_prefix) = key
    for package in packages:
        (package_num, package_id, package_type, package_description) = package
        if (package_id == key_id and package_type == key_type and
                package_description.startswith(key_description_prefix)):
            return package
    return None

def EnsureSdkPackageInstalled(packages, key):
    """
  Makes sure the package with a given key is installed.

  key is (id-key, type, description-prefix)

  Returns True if the package was not already installed.
  """
    entry = AndroidSdkFindPackage(packages, key)
    if entry is None:
        raise utils.Error("Could not find a package for key %s" % key)
    packageId = entry[0]
    if VERBOSE:
        sys.stderr.write('Checking Android SDK package %s...\n' % str(entry))
    out = utils.RunCommand(
        ["android", "update", "sdk", "-a", "-u", "--filter",
         str(packageId)])
    return '\nInstalling Archives:\n' in out

def SdkPackagesForAbi(abi):
    packagesForAbi = {
        'armeabi-v7a': [
            # The platform needed to install the armeabi ABI system image:
            ('android-15', 'Platform', 'Android SDK Platform 4.0.3'),
            # The armeabi-v7a ABI system image:
            ('sysimg-15', 'SystemImage', 'Android SDK Platform 4.0.3')
        ],
        'x86': [
            # The platform needed to install the x86 ABI system image:
            ('android-15', 'Platform', 'Android SDK Platform 4.0.3'),
            # The x86 ABI system image:
            ('sysimg-15', 'SystemImage', 'Android SDK Platform 4.0.4')
        ]
    }

    if abi not in packagesForAbi:
        raise utils.Error('Unsupported abi %s' % abi)
    return packagesForAbi[abi]

def TargetForAbi(abi):
    for package in SdkPackagesForAbi(abi):
        if package[1] == 'Platform':
            return package[0]

def EnsureAndroidSdkPackagesInstalled(abi):
    """Return true if at least one package was not already installed."""
    abiPackageList = SdkPackagesForAbi(abi)
    installedSomething = False
    packages = AndroidListSdk()
    for package in abiPackageList:
        installedSomething |= EnsureSdkPackageInstalled(packages, package)
    return installedSomething

def ParseAndroidListAvdResult(text):
    """
  Parse the output of an 'android list avd' command.
  Return List of {Name: Path: Target: ABI: Skin: Sdcard:}
  """
    text = text.split('Available Android Virtual Devices:\n')[-1]
    text = text.split(
        'The following Android Virtual Devices could not be loaded:\n')[0]
    result = []
    line_re = re.compile(r'^\s*([^\:]+)\:\s*(.*)$')
    for chunk in text.split('\n---------\n'):
        entry = {}
        for line in chunk.split('\n'):
            line = line.strip()
            if len(line) == 0:
                continue
            match = line_re.match(line)
            if match is None:
                sys.stderr.write('Match fail %s\n' % str(line))
                continue
                #raise utils.Error('Match failed')
            entry[match.group(1)] = match.group(2)
        if len(entry) > 0:
            result.append(entry)
    return result

def AndroidListAvd():
    """Returns a list of available Android Virtual Devices."""
    return ParseAndroidListAvdResult(
        utils.RunCommand(["android", "list", "avd"]))

def FindAvd(avds, key):
    for avd in avds:
        if avd['Name'] == key:
            return avd
    return None

def CreateAvd(avdName, abi):
    out = utils.RunCommand([
        "android", "create", "avd", "--name", avdName, "--target",
        TargetForAbi(abi), '--abi', abi
    ],
                           input="no\n")
    if out.find('Created AVD ') < 0:
        if VERBOSE:
            sys.stderr.write('Could not create AVD:\n%s\n' % out)
        raise utils.Error('Could not create AVD')

def AvdExists(avdName):
    avdList = AndroidListAvd()
    return FindAvd(avdList, avdName) is not None

def EnsureAvdExists(avdName, abi):
    if AvdExists(avdName):
        return
    if VERBOSE:
        sys.stderr.write('Checking SDK packages...\n')
    if EnsureAndroidSdkPackagesInstalled(abi):
        # Installing a new package could have made a previously invalid AVD valid
        if AvdExists(avdName):
            return
    CreateAvd(avdName, abi)

def StartEmulator(abi, avdName, pollFn):
    """
  Start an emulator for a given abi and svdName.

  Echo the emulator's stderr and stdout output to our stderr.

  Call pollFn repeatedly until it returns False. Leave the emulator running
  when we return.

  Implementation note: Normally we would call the 'emulator' binary, which
  is a wrapper that launches the appropriate abi-specific emulator. But there
  is a bug that causes the emulator to exit immediately with a result code of
  -11 if run from a ssh shell or a No Machine shell. (And only if called from
  three levels of nested python scripts.) Calling the ABI-specific versions
  of the emulator directly works around this bug.
  """
    emulatorName = {'x86': 'emulator-x86', 'armeabi-v7a': 'emulator-arm'}[abi]
    command = [emulatorName, '-avd', avdName, '-no-boot-anim', '-no-window']
    utils.RunCommand(
        command,
        pollFn=pollFn,
        killOnEarlyReturn=False,
        outStream=sys.stderr,
        errStream=sys.stderr)

def ParseAndroidDevices(text):
    """Return Dictionary [name] -> status"""
    text = text.split('List of devices attached')[-1]
    lines = [line.strip() for line in text.split('\n')]
    lines = [line for line in lines if len(line) > 0]
    devices = {}
    for line in lines:
        lineItems = line.split('\t')
        devices[lineItems[0]] = lineItems[1]
    return devices

def GetAndroidDevices():
    return ParseAndroidDevices(utils.RunCommand(["adb", "devices"]))

def FilterOfflineDevices(devices):
    online = {}
    for device in devices.keys():
        status = devices[device]
        if status != 'offline':
            online[device] = status
    return online

def GetOnlineAndroidDevices():
    return FilterOfflineDevices(GetAndroidDevices())

def GetAndroidDeviceProperty(device, property):
    return utils.RunCommand(["adb", "-s", device, "shell", "getprop",
                             property]).strip()

def GetAndroidDeviceAbis(device):
    abis = []
    for property in ['ro.product.cpu.abi', 'ro.product.cpu.abi2']:
        out = GetAndroidDeviceProperty(device, property)
        if len(out) > 0:
            abis.append(out)
    return abis

def FindAndroidRunning(abi):
    for device in GetOnlineAndroidDevices().keys():
        if abi in GetAndroidDeviceAbis(device):
            return device
    return None

def AddSdkToolsToPath():
    script_dir = os.path.dirname(sys.argv[0])
    dart_root = os.path.realpath(os.path.join(script_dir, '..', '..'))
    third_party_root = os.path.join(dart_root, 'third_party')
    android_tools = os.path.join(third_party_root, 'android_tools')
    android_sdk_root = os.path.join(android_tools, 'sdk')
    android_sdk_tools = os.path.join(android_sdk_root, 'tools')
    android_sdk_platform_tools = os.path.join(android_sdk_root,
                                              'platform-tools')
    os.environ['PATH'] = ':'.join(
        [os.environ['PATH'], android_sdk_tools, android_sdk_platform_tools])
    # Remove any environment variables that would affect our build.
    for i in [
            'ANDROID_NDK_ROOT', 'ANDROID_SDK_ROOT', 'ANDROID_TOOLCHAIN', 'AR',
            'BUILDTYPE', 'CC', 'CXX', 'GYP_DEFINES', 'LD_LIBRARY_PATH', 'LINK',
            'MAKEFLAGS', 'MAKELEVEL', 'MAKEOVERRIDES', 'MFLAGS', 'NM'
    ]:
        if i in os.environ:
            del os.environ[i]

def FindAndroid(abi, bootstrap):
    if VERBOSE:
        sys.stderr.write(
            'Looking for an Android device running abi %s...\n' % abi)
    AddSdkToolsToPath()
    device = FindAndroidRunning(abi)
    if not device:
        if bootstrap:
            if VERBOSE:
                sys.stderr.write("No emulator found, try to create one.\n")
            avdName = 'dart-build-%s' % abi
            EnsureAvdExists(avdName, abi)

            # It takes a while to start up an emulator.
            # Provide feedback while we wait.
            pollResult = [None]

            def pollFunction():
                if VERBOSE:
                    sys.stderr.write('.')
                pollResult[0] = FindAndroidRunning(abi)
                # Stop polling once we have our result.
                return pollResult[0] != None

            StartEmulator(abi, avdName, pollFunction)
            device = pollResult[0]
    return device

def Main():
    # Parse options.
    parser = BuildOptions()
    (options, args) = parser.parse_args()
    if not ProcessOptions(options):
        parser.print_help()
        return 1

    # If there are additional arguments, report error and exit.
    if args:
        parser.print_help()
        return 1

    try:
        device = FindAndroid(options.abi, options.bootstrap)
        if device != None:
            sys.stdout.write("%s\n" % device)
            return 0
        else:
            if VERBOSE:
                sys.stderr.write('Could not find device\n')
            return 2
    except utils.Error as e:
        sys.stderr.write("error: %s\n" % e)
        if DEBUG:
            traceback.print_exc(file=sys.stderr)
        return -1

if __name__ == '__main__':
    sys.exit(Main())


text:
package org.hyperledger.indy.sdk.ledger;

import org.hyperledger.indy.sdk.ErrorCode;
import org.hyperledger.indy.sdk.IndyException;

/**
 * Exception thrown when consensus was not reached during a ledger operation.
 */
public class ConsensusException extends IndyException
{
	private static final long serialVersionUID = -6503578332467229584L;
	private final static String message = "No consensus was reached during the ledger operation.";

	/**
	 * Initializes a new ConsensusException.
	 */
	public ConsensusException()
	{
		super(message, ErrorCode.LedgerNoConsensusError.value());
	}
}


text:
// Copyright 2015-present, Cyrill @ Schumacher.fm and the CoreStore contributors
//
// 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.

/*
Package config, abbrev. cfg, handles the configuration and its scopes.

A configuration holds many path.Paths which contains a route, a scope and a scope ID.

A route is defined as a minimum 3 level deep string separated by a slash. For example
catalog/product/enable_flat.

ScopePerm are default, website, group and store. Scope IDs are stored in the core_website,
core_group or core_store tables for M1 and store_website, store_group and store for M2.

Underlying storage can be a simple in memory map (default), MySQL table core_config_data
itself (package config/db) or etcd (package config/etcd) or consul (package todo) or ...

If you use any other configuration storage engine besides config/db package all values
gets bi-directional automatically synchronized (todo).

Elements

The package config/element contains more detailed information.

Scope Values

To get a value from the configuration Service via any type method you have to provide a
path.Path. If you use the ScopedGetter via function makeScoped() you can only provide a
path.Route to the type methods String(), Int(), Float64(), etc.

The examples show the overall best practices.
*/
// Package cfgpath handles the configuration paths.
//
// It contains two main types: Path and Route:
//
//    +-------+ +-----+ +----------+ +-----+ +----------------+
//    |       | |     | |          | |     | |                |
//    | Scope | |  /  | | Scope ID | |  /  | | Route/to/Value |
//    |       | |     | |          | |     | |                |
//    +-------+ +-----+ +----------+ +-----+ +----------------+
//
//    +                                      +                +
//    |                                      |                |
//    | <--------------+ Path +-----------------------------> |
//    |                                      |                |
//    +                                      + <- Route ----> +
//
// Scope
//
// A scope can only be default, websites or stores. Those three strings are
// defined by constants in package store/scope.
//
// Scope ID
//
// Refers to the database auto increment ID of one of the tables core_website
// and core_store for M1 and store_website plus store for M2.
//
// Type Path
//
// A Path contains always the scope, its scope ID and the route.
// If scope and ID haven't been provided they fall back to scope "default"
// and ID zero (0).
// Configuration paths are mainly used in table core_config_data.
//
// Type Route
//
// A route contains bytes and does not know anything about a scope or an ID.
// In the majority of use cases a route contains three parts to package
// config/element types for building a hierarchical tree structure:
//    element.Section.ID / element.Group.ID / element.Field.ID
// To add little bit more confusion: A route can either be a short one
// like aa/bb/cc or a fully qualified path like
//     scope/scopeID/element.Section.ID/element.Group.ID/element.Field.ID
// But the route always consists of a minimum of three parts.
//
// A route can have only three groups of [a-zA-Z0-9_] characters
// split by '/'. The limitation to [a-zA-Z0-9_] is a M1/M2 thing and can be
// maybe later removed.
// Minimal length per part 2 characters. Case sensitive.
//
// The route parts are used as an ID in element.Section, element.Group and
// element.Field types. See following text.
//
// The following diagram shows the tree structure:
//    +---------+
//    | Section |
//    +---------+
//    |
//    |   +-------+
//    +-->+ Group |
//    |   +-------+
//    |   |
//    |   |    +--------+
//    |   +--->+ Field  |
//    |   |    +--------+
//    |   |
//    |   |    +--------+
//    |   +--->+ Field  |
//    |   |    +--------+
//    |   |
//    |   |    +--------+
//    |   +--->+ Field  |
//    |        +--------+
//    |
//    |   +-------+
//    +-->+ Group |
//    |   +-------+
//    |   |
//    |   |    +--------+
//    |   +--->+ Field  |
//    |   |    +--------+
//    |   |
//    |   |    +--------+
//    |   +--->+ Field  |
//    |   |    +--------+
//    |   |
//    |   |    +--------+
//    |   +--->+ Field  |
//    |        +--------+
//    |
//    http://asciiflow.com/
//
// The three elements Section, Group and Field represents front-end
// configuration fields and more important default values and their permissions.
// A permission is of type scope.Perm and defines which of elements in which
// scope can be shown.
//
// Those three elements represents the tree in function NewConfigStructure()
// which can be found in any package.
//
// Unclear: Your app which includes the cs must merge all
// "PackageConfiguration"s into a single slice. You should submit all default
// values (interface config.Sectioner) to the config.Service.ApplyDefaults()
// function.
//
// The JSON encoding of the three elements Section, Group and Field are intended
// to use on the backend REST API and for debugging and testing. Only used in
// non performance critical parts.package config
package config


text:
{% extends "base.html" %}

{% block content %}

    {% if current_user.is_super %}
create new user
{% endif %}

    {% for user in users %}

{{ user.id }}

created : {{ user.created_date }}

    {% endfor %}

{% endblock %}


text:
import setuptools

def get_readme():
    with open('README.rst') as f:
        return f.read()

setuptools.setup(
    # the first three fields are a must according to the documentation
    name="pytsv",
    version="0.1.67",
    packages=[
        "pytsv",
    ],
    # from here all is optional
    description="pytsv is a module to help with all things TSV",
    long_description=get_readme(),
    long_description_content_type="text/x-rst",
    author="Mark Veltzer",
    author_email="mark.veltzer@gmail.com",
    maintainer="Mark Veltzer",
    maintainer_email="mark.veltzer@gmail.com",
    keywords=[
        "python",
        "tsv",
        "format",
        "csv",
    ],
    url="https://veltzer.github.io/pytsv",
    download_url="https://github.com/veltzer/pytsv",
    license="MIT",
    platforms=[
        "python3",
    ],
    install_requires=[
        "pytconf",
        "tqdm",
        "pyanyzip",
        "numpy",
        "pandas",
        "pylogconf",
        "attrs",
    ],
    classifiers=[
        "Development Status :: 4 - Beta",
        "Environment :: Console",
        "Operating System :: OS Independent",
        "Programming Language :: Python",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3 :: Only",
        "Programming Language :: Python :: 3.8",
        "Programming Language :: Python :: 3.9",
        "Programming Language :: Python :: 3.10",
        "Topic :: Utilities",
        "License :: OSI Approved :: MIT License",
    ],
    entry_points={"console_scripts": [
        "pytsv=pytsv.main:main",
    ]},
)


text:
<?php
/**
 * This is a more specific redirect response, sending a 301 Moved Permanently status code.
 */
class PermanentRedirectResponse extends RedirectResponse {
	/**
	 * Initialize this response.
	 *
	 * @param string $location Location of the redirect relative to the web root.
	 */
	public function __construct ($location) {
		parent::__construct($location, 301);
	}
}
?>


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Label from 'shared/components/label/label';
import styles from './formInput.css';

class FormInput extends Component {
  constructor() {
    super();
    this.state = {
      text: '',
      isValid: true,
    };
  }

  handleChange = (event) => {
    const valid = this.validate(event.target.value);
    this.setState({ text: event.target.value, isValid: valid }, () => {
      if (this.props.onChange) {
        this.props.onChange(this.state.text, this.state.isValid);
      }
    });
  };

  validate = (text) => {
    if (this.props.validateFunc) {
      return this.props.validateFunc(text);
    } else if (text.length > 0 && this.props.validationRegex) {
      return this.props.validationRegex.test(text);
    } else if (text.length > 0) {
      return true;
    }
    return false;
  };

  revalidate() {
    const valid = this.validate(this.state.text);
    this.setState({ isValid: valid });
  }

  render() {
    return (

        {this.props.label && {this.props.label}}

        <input
          className={!this.state.isValid && styles.error}
          id={this.props.id}
          type={this.props.inputType}
          value={this.state.text}
          placeholder={this.props.placeholder}
          onChange={this.handleChange}
        />
        {!this.state.isValid && {this.props.validationErrorMessage}}

    );
  }
}

FormInput.propTypes = {
  label: PropTypes.string,
  placeholder: PropTypes.string,
  id: PropTypes.string.isRequired,
  validationRegex: PropTypes.instanceOf(RegExp),
  validationErrorMessage: PropTypes.string,
  validateFunc: PropTypes.func,
  onChange: PropTypes.func,
  inputType: PropTypes.string,
};

FormInput.defaultProps = {
  label: null,
  placeholder: null,
  validationRegex: null,
  validationErrorMessage: null,
  validateFunc: null,
  onChange: null,
  inputType: 'text',
};

export default FormInput;


text:
typedef void (^ZBPageResultBlock)(NSDictionary *result);

@interface UIViewController (PageResult)

@property (nonatomic, weak) id<ZBPageResultProtocol> zbDelegate;
@property (nonatomic, copy) ZBPageResultBlock zbPageResultBlock;
@property (nonatomic, strong) NSMutableDictionary *pageResult;

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

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

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
    ">

    <bean id="foo" class="org.apache.camel.processor.PolicyPerRouteTest$MyPolicy">
        <constructor-arg index="0" value="foo"/>
    </bean>

    <camelContext xmlns="http://camel.apache.org/schema/spring">
        <!-- START SNIPPET: e1 -->
        <route>
            <from uri="direct:start"/>
            <!-- wraps the entire route in the same policy,
                 notice how we have to wrap policy around the route -->
            <policy ref="foo">
                <to uri="mock:foo"/>
                <to uri="mock:bar"/>
                <to uri="mock:result"/>
            </policy>
        </route>
        <!-- END SNIPPET: e1 -->
        <route>
            <from uri="direct:send"/>
            <to uri="direct:start"/>
            <to uri="mock:response"/>
        </route>
    </camelContext>

</beans>


text:
<?php

namespace Ui\ActiveForm\Input;

class DynamicType extends \Ui\ActiveForm\Input {

    public function draw() {
        $inputName = $this->colName();
        $inputLabel = $this->colLabel();
        $inputOptions = [
            'value' => $this->value(),
            'disabled' => $this->readOnly()
        ];
        $preset = $this->preset();
        if ($preset !== null) {
            $inputOptions['disabled'] = true;
            $this->form->input('hidden', $inputName, '', $inputOptions);
            return true;
        }
        $inputType = 'text';

        switch ($this->colParams['typeSource']) {
            case 'selfMethod':
                $type = $this->activeForm->model->{$this->colParams['selfMethod']}();
                if (is_array($type)) {
                    $inputType = $type['type'];
                    if (strpos($type['relation'], ':')) {
                        $relationPath = explode(':', $type['relation']);
                        $relationName = array_pop($relationPath);
                        $item = $this->activeForm->model;
                        foreach ($relationPath as $path) {
                            $item = $item->$path;
                        }

                        $inputOptions['values'] = $item->{$relationName}(['forSelect' => true]);
                    } else {
                        $inputOptions['values'] = $this->activeForm->model->{$type['relation']}(['forSelect' => true]);
                    }
                }
                break;
        }
        $this->form->input($inputType, $inputName, $inputLabel, $inputOptions);
        return true;
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <artifactId>jms</artifactId>
        <groupId>org.glassfish.javaeetutorial</groupId>
        <version>7.0.5</version>
    </parent>

    <groupId>org.glassfish.javaeetutorial</groupId>
    <artifactId>clientmdbentity</artifactId>
    <packaging>pom</packaging>

    <name>clientmdbentity</name>

    <modules>
        <module>clientmdbentity-ear</module>
        <module>clientmdbentity-ejb</module>
        <module>clientmdbentity-appclient</module>
    </modules>
</project>


text:
// Copyright 2015 XLGAMES Inc.
//
// Distributed under the MIT License (See
// accompanying file "LICENSE" or the website
// http://www.opensource.org/licenses/mit-license.php)

#include "GeometryAlgorithm.h"
#include "../RenderCore/Assets/MeshDatabase.h"
#include "../Math/Geometry.h"
#include "../Math/Transformations.h"
#include "../Utility/MemoryUtils.h"
#include "../Utility/StringUtils.h"
#include "../Utility/ArithmeticUtils.h"

namespace RenderCore { namespace ColladaConversion
{
    using namespace RenderCore::Assets::GeoProc;

    Float3 CorrectAxisDirection(const Float3& input, const Float3& p0, const Float3& p1, const Float3& p2, float t0, float t1, float t2)
    {
        float A0 = Dot(p0 - p1, input);
        float A1 = Dot(p1 - p2, input);
        float A2 = Dot(p2 - p0, input);
        float a0 = t0 - t1;
        float a1 = t1 - t2;
        float a2 = t2 - t0;

        float w0 = XlAbs(A0 * a0);
        float w1 = XlAbs(A1 * a1);
        float w2 = XlAbs(A2 * a2);
        if (w0 > w1) {
            if (w0 > w2) return ((A0 > 0.f) == (a0 > 0.f)) ? input : -input;
            return ((A2 > 0.f) == (a2 > 0.f)) ? input : -input;
        } else {
            if (w1 > w2) return ((A1 > 0.f) == (a1 > 0.f)) ? input : -input;
            return ((A2 > 0.f) == (a2 > 0.f)) ? input : -input;
        }
    }

    void GenerateNormalsAndTangents(
        MeshDatabase& mesh,
        unsigned normalMapTextureCoordinateSemanticIndex,
        const void* rawIb, size_t indexCount, Metal::NativeFormat::Enum ibFormat)
	{
        using namespace RenderCore::Metal;

            // testing -- remove existing tangents & normals
        // mesh.RemoveStream(mesh.FindElement("NORMAL"));
        // mesh.RemoveStream(mesh.FindElement("TEXTANGENT"));
        // mesh.RemoveStream(mesh.FindElement("TEXBITANGENT"));

        auto tcElement = mesh.FindElement("TEXCOORD", normalMapTextureCoordinateSemanticIndex);
        if (tcElement == ~0u) return;   // if there are no texture coordinates, we could generate normals, but we can't generate tangents

        bool hasNormals = !!(mesh.HasElement("NORMAL") & 0x1);
        bool hasTangents = !!(mesh.HasElement("TEXTANGENT") & 0x1);
        bool hasBitangents = !!(mesh.HasElement("TEXBITANGENT") & 0x1);
        if ((hasNormals && hasTangents) || (hasTangents && hasBitangents)) return;

        auto posElement = mesh.FindElement("POSITION");

		struct Triangle
		{
			Float3 normal;
			Float3 tangent;
			Float3 bitangent;
		};

            //
            //      Note that when building normals and tangents, there are some
            //      cases were we might want to split a vertex into two...
            //      This can happen if we want to create a sharp edge in the model,
            //      or a seam in the texturing.
            //      However, this method never splits vertices... We only modify the
            //      input vertices. This can create stretching or warping in some
            //      models -- that can only be fixed by changing the input data.
            //
            //      Also note that this is an unweighted method... Which means that
            //      each vertex is influenced by all triangles it is part of evenly.
            //      Some other methods will weight the influence of triangles such
            //      that larger or more important triangles have a larger influence.
            //
        std::vector<Float3> normals(mesh.GetUnifiedVertexCount(), Zero<Float3>());
		std::vector<Float4> tangents(mesh.GetUnifiedVertexCount(), Zero<Float4>());
		std::vector<Float3> bitangents(mesh.GetUnifiedVertexCount(), Zero<Float3>());

        unsigned indexStride = 2;
        unsigned indexMask = 0xffff;
        if (ibFormat == Metal::NativeFormat::R32_UINT) { indexStride = 4; indexMask = 0xffffffff; }
        auto* ib = (const uint32*)rawIb;

		auto triangleCount = indexCount / 3;   // assuming index buffer is triangle-list format
		for (size_t c=0; c<triangleCount; c++) {
            unsigned v0 = (*ib) & indexMask; ib = PtrAdd(ib, indexStride);
            unsigned v1 = (*ib) & indexMask; ib = PtrAdd(ib, indexStride);
            unsigned v2 = (*ib) & indexMask; ib = PtrAdd(ib, indexStride);

            assert(v0 != v1 && v1 != v2 && v1 != v2);

			auto p0 = mesh.GetUnifiedElement<Float3>(v0, posElement);
			auto p1 = mesh.GetUnifiedElement<Float3>(v1, posElement);
			auto p2 = mesh.GetUnifiedElement<Float3>(v2, posElement);

            Float4 plane;
            if (PlaneFit_Checked(&plane, p0, p1, p2)) {
				Triangle tri;
                tri.normal = -Truncate(plane);

					/*	There is one natural tangent and one natural bitangent for each triangle, on the v=0 and u=0 axes
						in 3 space. We'll calculate them for this triangle here and then use a composite of triangle tangents
						for the vertex tangents below.

						Here's a good reference:
						http://www.terathon.com/code/tangent.html
						from "Mathematics for 3D Game Programming and Computer Graphics, 2nd ed."

						These equations just solve for v=0 and u=0 on the triangle surface.
					*/
				const auto UV0 = mesh.GetUnifiedElement<Float2>(v0, tcElement);
				const auto UV1 = mesh.GetUnifiedElement<Float2>(v1, tcElement);
				const auto UV2 = mesh.GetUnifiedElement<Float2>(v2, tcElement);
				auto Q1 = p1 - p0;
				auto Q2 = p2 - p0;
				auto st1 = UV1 - UV0;
				auto st2 = UV2 - UV0;
				float rr = (st1[0] * st2[1] + st2[0] * st1[1]);
				if (Equivalent(rr, 0.f, 1e-10f)) { tri.tangent = tri.bitangent = Zero<Float3>(); }
				else
				{
					float r = 1.f / rr;
					Float3 sAxis( (st2[1] * Q1 - st1[1] * Q2) * r );
					Float3 tAxis( (st1[0] * Q2 - st2[0] * Q1) * r );

                        // We may need to flip the direction of the s or t axis
                        // check the texture coordinates to find the correct direction
                        // for these axes...
                    sAxis = CorrectAxisDirection(sAxis, p0, p1, p2, UV0[0], UV1[0], UV2[0]);
                    tAxis = CorrectAxisDirection(tAxis, p0, p1, p2, UV0[1], UV1[1], UV2[1]);

                    auto sMagSq = MagnitudeSquared(sAxis);
                    auto tMagSq = MagnitudeSquared(tAxis);

                    float recipSMag, recipTMag;
                    if (XlRSqrt_Checked(&recipSMag, sMagSq) && XlRSqrt_Checked(&recipTMag, tMagSq)) {
                        tri.tangent = sAxis * recipSMag;
						tri.bitangent = tAxis * recipTMag;
                    } else {
                        tri.tangent = tri.bitangent = Zero<Float3>();
                    }

                    tri.tangent = sAxis;
                    tri.bitangent = tAxis;
				}

				assert( tri.tangent[0] == tri.tangent[0] );

                    // We add the influence of this triangle to all vertices
                    // each vertex should get an even balance of influences from
                    // all triangles it is part of.
                normals[v0] += tri.normal; normals[v1] += tri.normal; normals[v2] += tri.normal;
                tangents[v0] += Expand(tri.tangent, 0.f); tangents[v1] += Expand(tri.tangent, 0.f); tangents[v2] += Expand(tri.tangent, 0.f);
                bitangents[v0] += tri.bitangent; bitangents[v1] += tri.bitangent; bitangents[v2] += tri.bitangent;
			} else {
				    /* this triangle is so small we can't derive any useful information from it */
			}
		}

            //  Create new streams for the normal & tangent, and write the results to the mesh database
            //  If we already have tangents or normals, don't write the new ones

        if (!hasNormals) {
            for (size_t c=0; c<mesh.GetUnifiedVertexCount(); c++)
                normals[c] = Normalize(normals[c]);

            mesh.AddStream(
                CreateRawDataSource(
                    AsPointer(normals.cbegin()), AsPointer(normals.cend()),
                    Metal::NativeFormat::R32G32B32_FLOAT),
                std::vector<unsigned>(),
                "NORMAL", 0);
        }

        if (!hasTangents) {

            unsigned normalsElement = mesh.FindElement("NORMAL");

                //  normals and tangents will have fallen out of orthogonality by the blending above.
			    //  we can re-orthogonalize using the Gram-Schmidt process -- we won't modify the normal, we'd rather lift the tangent and bitangent
			    //  off the triangle surface that distort the normal direction too much.
                //  Note that we don't need to touch the bitangent here... We're not going to write the bitangent
                //  to the output, so it doesn't matter right now. All we need to do is calculate the "handiness"
                //  value and write it to the "w" part of the tangent vector.
            for (size_t c=0; c<mesh.GetUnifiedVertexCount(); c++) {
                auto t3 = Truncate(tangents[c]);
                auto handinessValue = 0.f;

                    // if we already had normals in the mesh, we should prefex
                    // those normals (over the ones we generated here)
                auto n = normals[c];
                if (hasNormals) n = mesh.GetUnifiedElement<Float3>(c, normalsElement);

                if (Normalize_Checked(&t3, Float3(t3 - n * Dot(n, t3)))) {
                    // handinessValue = Dot( Cross( bitangents[c], t3 ), n ) < 0.f ? -1.f : 1.f;
                    handinessValue = Dot( Cross( t3, n ), bitangents[c] ) < 0.f ? -1.f : 1.f;
                } else {
                    t3 = Zero<Float3>();
                }

                tangents[c] = Expand(t3, handinessValue);
            }

            mesh.AddStream(
                CreateRawDataSource(
                    AsPointer(tangents.begin()), AsPointer(tangents.cend()), Metal::NativeFormat::R32G32B32A32_FLOAT),
                std::vector<unsigned>(),
                "TEXTANGENT", 0);

        }

        // if (!hasBitangents) {
        //
        //     unsigned normalsElement = mesh.FindElement("NORMAL");
        //
        //     for (size_t c=0; c<mesh._unifiedVertexCount; c++) {
        //         auto t3 = bitangents[c];
        //
        //             // if we already had normals in the mesh, we should prefex
        //             // those normals (over the ones we generated here)
        //         auto n = normals[c];
        //         if (hasNormals) n = mesh.GetUnifiedElement<Float3>(c, normalsElement);
        //
        //         if (Normalize_Checked(&t3, Float3(t3 - n * Dot(n, t3)))) {
        //         } else {
        //             t3 = Zero<Float3>();
        //         }
        //
        //         bitangents[c] = t3;
        //     }
        //
        //     mesh.AddStream(
        //         AsPointer(bitangents.begin()), AsPointer(bitangents.cend()), Metal::NativeFormat::R32G32B32_FLOAT,
        //         Use16BitFloats ? Metal::NativeFormat::R16G16B16A16_FLOAT : Metal::NativeFormat::R32G32B32_FLOAT,
        //         "TEXBITANGENT", 0);
        //
        // }
	}

    template<typename Type>
        RenderCore::Metal::NativeFormat::Enum AsNativeFormat();

    template<> RenderCore::Metal::NativeFormat::Enum AsNativeFormat<float>()
        { return RenderCore::Metal::NativeFormat::R32_FLOAT; }
    template<> RenderCore::Metal::NativeFormat::Enum AsNativeFormat<Float2>()
        { return RenderCore::Metal::NativeFormat::R32G32_FLOAT; }
    template<> RenderCore::Metal::NativeFormat::Enum AsNativeFormat<Float3>()
        { return RenderCore::Metal::NativeFormat::R32G32B32_FLOAT; }
    template<> RenderCore::Metal::NativeFormat::Enum AsNativeFormat<Float4>()
        { return RenderCore::Metal::NativeFormat::R32G32B32A32_FLOAT; }

    // #define CHECK_FOR_NAN
    #if defined(CHECK_FOR_NAN)
        static void Check(float i) { assert(!std::isnan(i)); }
        static void Check(Float2 i) { assert(!std::isnan(i[0]) && !std::isnan(i[1])); }
        static void Check(Float3 i) { assert(!std::isnan(i[0]) && !std::isnan(i[1]) && !std::isnan(i[2])); }
        static void Check(Float4 i) { assert(!std::isnan(i[0]) && !std::isnan(i[1]) && !std::isnan(i[2]) && !std::isnan(i[3])); }
    #endif

    template<typename PivotType, typename TransformFn>
        std::shared_ptr<IVertexSourceData> TransformStream(
            const IVertexSourceData& src,
            const TransformFn& transform)
        {
            std::vector<uint8> tempBuffer;
            tempBuffer.resize(src.GetCount() * sizeof(PivotType));
            auto* dst = (PivotType*)AsPointer(tempBuffer.begin());
            for (unsigned c=0; c<src.GetCount(); ++c)
                dst[c] = GetVertex<PivotType>(src, c);

            #if defined(CHECK_FOR_NAN)
                for (unsigned c=0; c<src.GetCount(); ++c) Check(dst[c]);
            #endif

            transform(dst, &dst[src.GetCount()]);

            #if defined(CHECK_FOR_NAN)
                for (unsigned c=0; c<src.GetCount(); ++c) Check(dst[c]);
            #endif

                // Let's make sure the new stream data is in the same format
                // as the old one.
            auto finalStride = Metal::BitsPerPixel(src.GetFormat())/8;
            auto finalFormat = src.GetFormat();
            auto pivotFormat = AsNativeFormat<PivotType>();
            if (finalFormat != pivotFormat) {
                assert(finalStride <= sizeof(PivotType));  // we can do this in-place so long as the destination stride isn't bigger
                CopyVertexData(
                    AsPointer(tempBuffer.begin()), finalFormat, finalStride, tempBuffer.size(),
                    AsPointer(tempBuffer.begin()), pivotFormat, sizeof(PivotType), tempBuffer.size(),
                    unsigned(src.GetCount()));
            }

            return CreateRawDataSource(
                std::move(tempBuffer), src.GetCount(), finalStride, finalFormat);
        }

    template<typename PivotType, typename TransformFn>
        void TransformStream(
            RenderCore::Assets::GeoProc::MeshDatabase& mesh,
            unsigned streamIndex,
            const TransformFn& transform)
    {
        const auto& stream = mesh.GetStreams()[streamIndex];
        auto newStream = TransformStream<PivotType>(stream.GetSourceData(), transform);

            // swap the old stream with the new one.
        auto semanticName = stream.GetSemanticName();
        auto semanticIndex = stream.GetSemanticIndex();
        auto vertexMap = stream.GetVertexMap();
        mesh.RemoveStream(streamIndex);
        mesh.InsertStream(
            streamIndex, std::move(newStream),
            std::move(vertexMap), semanticName.c_str(), semanticIndex);
    }

    void Transform(
        RenderCore::Assets::GeoProc::MeshDatabase& mesh,
        const Float4x4& transform)
    {
        // For each stream in the mesh, we need to decide how to transform it.
        // We have 3 typical options:
        //      TransformPoint --
        //          This uses the full 4x4 transform
        //          (ie, this should be applied to POSITION)
        //      TransformUnitVector --
        //          This uses only the rotational element of the transform,
        //          with the scale and translation removed.
        //          (ie, this should be applied to NORMAL, TEXTANGENT, etc)
        //      None --
        //          No transform at all
        //          (ie, this should be applied to TEXCOORD)
        //
        // In the case of TransformUnitVector, we're going to assume a
        // well behaved 4x4 transform -- with no skew or wierd non-orthogonal
        // behaviour. Actually, we can get an arbitrarily complex 4x4 transform
        // from Collada... But let's just assume it's simple.

        for (unsigned s=0; s<mesh.GetStreams().size(); s++) {
            const auto& stream = mesh.GetStreams()[s];

            auto semanticName = stream.GetSemanticName();
            enum Type { Point, UnitVector, None } type = None;

                // todo -- semantic names are hard coded here. But we
                // could make this data-driven by using a configuration
                // file to select the transform type.
            if (semanticName == "POSITION") {
                type = Point;
            } else if (
                    semanticName == "NORMAL"
                ||  semanticName == "TEXTANGENT"
                ||  semanticName == "TEXBITANGENT"
                ||  semanticName == "TEXBINORMAL"
                ||  semanticName == "TANGENT"
                ||  semanticName == "BITANGENT"
                ||  semanticName == "BINORMAL") {
                type = UnitVector;
            }
            if (type == None) continue;

            const auto& src = stream.GetSourceData();
            auto componentCount = Metal::GetComponentCount(Metal::GetComponents(src.GetFormat()));
            if (type == Point) {
                    // We can support both 3d and 2d pretty easily here. Collada generalizes to 2d well,
                    // so we might as well support it (though maybe the 3d case is by far the most common
                    // case)
                if (componentCount==3) {
                    TransformStream<Float3>(
                        mesh, s,
                        [&transform](Float3* begin, Float3* end)
                            { for (auto i=begin; i!=end; ++i) *i = TransformPoint(transform, *i); });
                } else if (componentCount==4) {
                    TransformStream<Float4>(
                        mesh, s,
                        [&transform](Float4* begin, Float4* end)
                            { for (auto i=begin; i!=end; ++i) *i = transform * (*i); });
                } else if (componentCount==2) {
                    TransformStream<Float2>(
                        mesh, s,
                        [&transform](Float2* begin, Float2* end)
                            { for (auto i=begin; i!=end; ++i) *i = Truncate(TransformPoint(transform, Expand(*i, 0.f))); });
                } else if (componentCount==1) {
                    TransformStream<float>(
                        mesh, s,
                        [&transform](float* begin, float* end)
                            { for (auto i=begin; i!=end; ++i) *i = TransformPoint(transform, Float3(*i, 0.f, 0.f))[0]; });
                }
            } else if (type == UnitVector) {
                // We can do this in two ways... We can create a version of the matrix that
                // has the scale removed. This would be fine for uniform scale.
                // But in the nonuniform scale, the normal should get deformed.
                // Alternatively, we can transform with the scale part there, and just renormalize
                // afterwards.
                auto truncated = Truncate3x3(transform);
                if (componentCount==3) {
                    TransformStream<Float3>(
                        mesh, s,
                        [&truncated](Float3* begin, Float3* end)
                            { for (auto i=begin; i!=end; ++i) *i = Normalize(truncated * (*i)); });
                } else if (componentCount==4) {
                    // note that the "tangent" stream can be 4D if the "handiness" flag is already attached.
                    Throw(::Exceptions::BasicLabel("Attempting to apply 3D transform to 4D vector. Perhaps the final component is the tangent handiness flag?"));
                } else if (componentCount==2) {
                    TransformStream<Float2>(
                        mesh, s,
                        [&truncated](Float2* begin, Float2* end)
                            { for (auto i=begin; i!=end; ++i) *i = Truncate(Normalize(truncated * Expand(*i, 0.f))); });
                }
            }
        }
    }

    void RemoveRedundantBitangents(MeshDatabase& mesh)
    {
            // remove bitangents for every stream that has both normals and tangents
        auto normAndTan = mesh.HasElement("NORMAL") & mesh.HasElement("TEXTANGENT");
        if (normAndTan!=0) {
            for (unsigned b=0; b<(32-xl_ctz4(normAndTan)); ++b) {
                auto bitan = mesh.FindElement("TEXBITANGENT", b);
                if (bitan != ~0u)
                    mesh.RemoveStream(bitan);
            }
        }
    }

///////////////////////////////////////////////////////////////////////////////////////////////////

    void CopyVertexElements(
        void* destinationBuffer,            size_t destinationVertexStride,
        const void* sourceBuffer,           size_t sourceVertexStride,
        const Assets::VertexElement* destinationLayoutBegin,  const Assets::VertexElement* destinationLayoutEnd,
        const Assets::VertexElement* sourceLayoutBegin,       const Assets::VertexElement* sourceLayoutEnd,
        const uint32* reorderingBegin,      const uint32* reorderingEnd )
    {
        uint32      elementReordering[32];
        signed      maxSourceLayout = -1;
        for (auto source=sourceLayoutBegin; source!=sourceLayoutEnd; ++source) {
                //      look for the same element in the destination layout (or put ~uint32(0x0) if it's not there)
            elementReordering[source-sourceLayoutBegin] = ~uint32(0x0);
            for (auto destination=destinationLayoutBegin; destination!=destinationLayoutEnd; ++destination) {
                if (    !XlCompareString(destination->_semanticName, source->_semanticName)
                    &&  destination->_semanticIndex  == source->_semanticIndex
                    &&  destination->_nativeFormat   == source->_nativeFormat) {

                    elementReordering[source-sourceLayoutBegin] = uint32(destination-destinationLayoutBegin);
                    maxSourceLayout = std::max(maxSourceLayout, signed(source-sourceLayoutBegin));
                    break;
                }
            }
        }

        if (maxSourceLayout<0) return;

        size_t vertexCount = reorderingEnd - reorderingBegin; (void)vertexCount;

        #if defined(_DEBUG)
                    //  fill in some dummy values
            std::fill((uint8*)destinationBuffer, (uint8*)PtrAdd(destinationBuffer, vertexCount*destinationVertexStride), 0xaf);
        #endif

            ////////////////     copy each vertex (slowly) piece by piece       ////////////////
        for (auto reordering = reorderingBegin; reordering!=reorderingEnd; ++reordering) {
            size_t sourceIndex               = reordering-reorderingBegin, destinationIndex = *reordering;
            void* destinationVertexStart     = PtrAdd(destinationBuffer, destinationIndex*destinationVertexStride);
            const void* sourceVertexStart    = PtrAdd(sourceBuffer, sourceIndex*sourceVertexStride);
            for (unsigned c=0; c<=(unsigned)maxSourceLayout; ++c) {
                if (elementReordering[c] != ~uint32(0x0)) {
                    const auto& destinationElement = destinationLayoutBegin[elementReordering[c]]; assert(&destinationElement < destinationLayoutEnd);
                    const auto& sourceElement = sourceLayoutBegin[c]; assert(&sourceElement < sourceLayoutEnd);
                    size_t elementSize = Metal::BitsPerPixel(Metal::NativeFormat::Enum(destinationElement._nativeFormat))/8;
                    assert(elementSize == Metal::BitsPerPixel(Metal::NativeFormat::Enum(sourceElement._nativeFormat))/8);
                    assert(destinationElement._alignedByteOffset + elementSize <= destinationVertexStride);
                    assert(sourceElement._alignedByteOffset + elementSize <= sourceVertexStride);
                    assert(PtrAdd(destinationVertexStart, destinationElement._alignedByteOffset+elementSize) <= PtrAdd(destinationVertexStart, vertexCount*destinationVertexStride));
                    assert(PtrAdd(sourceVertexStart, sourceElement._alignedByteOffset+elementSize) <= PtrAdd(sourceVertexStart, vertexCount*sourceVertexStride));

                    XlCopyMemory(
                        PtrAdd(destinationVertexStart, destinationElement._alignedByteOffset),
                        PtrAdd(sourceVertexStart, sourceElement._alignedByteOffset),
                        elementSize);
                }
            }
        }
    }

    unsigned CalculateVertexSize(
        const Assets::VertexElement* layoutBegin,
        const Assets::VertexElement* layoutEnd)
    {
        unsigned result = 0;
        for (auto l=layoutBegin; l!=layoutEnd; ++l)
            result += Metal::BitsPerPixel(Metal::NativeFormat::Enum(l->_nativeFormat));
        return result/8;
    }

    unsigned CalculateVertexSize(
        const Metal::InputElementDesc* layoutBegin,
        const Metal::InputElementDesc* layoutEnd)
    {
        unsigned result = 0;
        for (auto l=layoutBegin; l!=layoutEnd; ++l)
            result += Metal::BitsPerPixel(Metal::NativeFormat::Enum(l->_nativeFormat));
        return result/8;
    }

}}


text:
package selection_test

import (
	"errors"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/sclevine/agouti/core/internal/mocks"
	. "github.com/sclevine/agouti/core/internal/selection"
	"github.com/sclevine/agouti/core/internal/types"
)

var _ = Describe("Actions", func() {
	var (
		selection     *MultiSelection
		client        *mocks.Client
		firstElement  *mocks.Element
		secondElement *mocks.Element
	)

	BeforeEach(func() {
		client = &mocks.Client{}
		firstElement = &mocks.Element{}
		secondElement = &mocks.Element{}
		emptySelection := &Selection{Client: client}
		selection = emptySelection.All("#selector")
	})

	ItShouldEnsureAtLeastOneElement := func(matcher func() error) {
		Context("when zero elements are returned", func() {
			It("should return an error with the number of elements", func() {
				client.GetElementsCall.ReturnElements = []types.Element{}
				Expect(matcher()).To(MatchError("failed to select 'CSS: #selector': no elements found"))
			})
		})
	}

	Describe("#Click", func() {
		BeforeEach(func() {
			client.GetElementsCall.ReturnElements = []types.Element{firstElement, secondElement}
		})

		ItShouldEnsureAtLeastOneElement(func() error {
			return selection.Click()
		})

		It("should successfully click on all selected elements", func() {
			Expect(selection.Click()).To(Succeed())
			Expect(firstElement.ClickCall.Called).To(BeTrue())
			Expect(secondElement.ClickCall.Called).To(BeTrue())
		})

		Context("when any click fails", func() {
			It("should return an error", func() {
				secondElement.ClickCall.Err = errors.New("some error")
				Expect(selection.Click()).To(MatchError("failed to click on 'CSS: #selector': some error"))
			})
		})
	})

	// TODO: extend mock to test multiple calls
	Describe("#DoubleClick", func() {
		BeforeEach(func() {
			client.GetElementsCall.ReturnElements = []types.Element{firstElement, secondElement}
		})

		ItShouldEnsureAtLeastOneElement(func() error {
			return selection.DoubleClick()
		})

		It("should successfully move the mouse to the middle of each selected element", func() {
			Expect(selection.DoubleClick()).To(Succeed())
			Expect(client.MoveToCall.Element).To(Equal(secondElement))
			Expect(client.MoveToCall.Point).To(BeNil())
		})

		Context("when moving over any element fails", func() {
			It("should retun an error", func() {
				client.MoveToCall.Err = errors.New("some error")
				Expect(selection.DoubleClick()).To(MatchError("failed to move mouse to 'CSS: #selector': some error"))
			})
		})

		It("should successfully double-click on each element", func() {
			Expect(selection.DoubleClick()).To(Succeed())
			Expect(client.DoubleClickCall.Called).To(BeTrue())
		})

		Context("when the double-clicking any element fails", func() {
			It("should return an error", func() {
				client.DoubleClickCall.Err = errors.New("some error")
				Expect(selection.DoubleClick()).To(MatchError("failed to double-click on 'CSS: #selector': some error"))
			})
		})
	})

	Describe("#Fill", func() {
		BeforeEach(func() {
			client.GetElementsCall.ReturnElements = []types.Element{firstElement, secondElement}
		})

		ItShouldEnsureAtLeastOneElement(func() error {
			return selection.Fill("some text")
		})

		It("should successfully clear each element", func() {
			Expect(selection.Fill("some text")).To(Succeed())
			Expect(firstElement.ClearCall.Called).To(BeTrue())
			Expect(secondElement.ClearCall.Called).To(BeTrue())
		})

		Context("when clearing any element fails", func() {
			It("should return an error", func() {
				secondElement.ClearCall.Err = errors.New("some error")
				Expect(selection.Fill("some text")).To(MatchError("failed to clear 'CSS: #selector': some error"))
			})
		})

		It("should successfully fill each element with the provided text", func() {
			Expect(selection.Fill("some text")).To(Succeed())
			Expect(firstElement.ValueCall.Text).To(Equal("some text"))
			Expect(secondElement.ValueCall.Text).To(Equal("some text"))
		})

		Context("when entering text into any element fails", func() {
			It("should return an error", func() {
				secondElement.ValueCall.Err = errors.New("some error")
				Expect(selection.Fill("some text")).To(MatchError("failed to enter text into 'CSS: #selector': some error"))
			})
		})
	})

	Describe("#Check", func() {
		BeforeEach(func() {
			client.GetElementsCall.ReturnElements = []types.Element{firstElement, secondElement}
		})

		ItShouldEnsureAtLeastOneElement(func() error {
			return selection.Check()
		})

		It("should successfully check the type of each checkbox", func() {
			firstElement.GetAttributeCall.ReturnValue = "checkbox"
			secondElement.GetAttributeCall.ReturnValue = "checkbox"
			Expect(selection.Check()).To(Succeed())
			Expect(firstElement.GetAttributeCall.Attribute).To(Equal("type"))
			Expect(secondElement.GetAttributeCall.Attribute).To(Equal("type"))
		})

		Context("when any element fails to retrieve the 'type' attribute", func() {
			It("should return an error", func() {
				firstElement.GetAttributeCall.ReturnValue = "checkbox"
				secondElement.GetAttributeCall.Err = errors.New("some error")
				Expect(selection.Check()).To(MatchError("failed to retrieve type of 'CSS: #selector': some error"))
			})
		})

		Context("when any element is not a checkbox", func() {
			It("should return an error", func() {
				firstElement.GetAttributeCall.ReturnValue = "checkbox"
				secondElement.GetAttributeCall.ReturnValue = "banana"
				Expect(selection.Check()).To(MatchError("'CSS: #selector' does not refer to a checkbox"))
			})
		})

		Context("when all elements are checkboxes", func() {
			BeforeEach(func() {
				firstElement.GetAttributeCall.ReturnValue = "checkbox"
				secondElement.GetAttributeCall.ReturnValue = "checkbox"
			})

			It("should not click on the checked checkbox successfully", func() {
				firstElement.IsSelectedCall.ReturnSelected = true
				Expect(selection.Check()).To(Succeed())
				Expect(firstElement.ClickCall.Called).To(BeFalse())
			})

			It("should click on the unchecked checkboxes successfully", func() {
				secondElement.IsSelectedCall.ReturnSelected = false
				Expect(selection.Check()).To(Succeed())
				Expect(secondElement.ClickCall.Called).To(BeTrue())
			})

			Context("when the determining the selected status of any element fails", func() {
				It("should return an error", func() {
					secondElement.IsSelectedCall.Err = errors.New("some error")
					Expect(selection.Check()).To(MatchError("failed to retrieve state of 'CSS: #selector': some error"))
				})
			})

			Context("when clicking on the checkbox fails", func() {
				It("should return an error", func() {
					secondElement.ClickCall.Err = errors.New("some error")
					Expect(selection.Check()).To(MatchError("failed to click on 'CSS: #selector': some error"))
				})
			})
		})
	})

	Describe("#Uncheck", func() {
		It("should successfully click on a checked checkbox", func() {
			client.GetElementsCall.ReturnElements = []types.Element{firstElement, secondElement}
			firstElement.GetAttributeCall.ReturnValue = "checkbox"
			secondElement.GetAttributeCall.ReturnValue = "checkbox"
			secondElement.IsSelectedCall.ReturnSelected = true
			Expect(selection.Uncheck()).To(Succeed())
			Expect(firstElement.ClickCall.Called).To(BeFalse())
			Expect(secondElement.ClickCall.Called).To(BeTrue())
		})
	})

	Describe("#Select", func() {
		var (
			firstOptions  []*mocks.Element
			secondOptions []*mocks.Element
		)

		BeforeEach(func() {
			firstOptions = []*mocks.Element{&mocks.Element{}, &mocks.Element{}}
			secondOptions = []*mocks.Element{&mocks.Element{}, &mocks.Element{}}
			firstElement.GetElementsCall.ReturnElements = []types.Element{firstOptions[0], firstOptions[1]}
			secondElement.GetElementsCall.ReturnElements = []types.Element{secondOptions[0], secondOptions[1]}
			client.GetElementsCall.ReturnElements = []types.Element{firstElement, secondElement}
		})

		ItShouldEnsureAtLeastOneElement(func() error {
			return selection.Select("some text")
		})

		It("should successfully retrieve the options with matching text for each selected element", func() {
			Expect(selection.Select("some text")).To(Succeed())
			Expect(firstElement.GetElementsCall.Selector.Using).To(Equal("xpath"))
			Expect(firstElement.GetElementsCall.Selector.Value).To(Equal(`./option[normalize-space(text())="some text"]`))
			Expect(secondElement.GetElementsCall.Selector.Using).To(Equal("xpath"))
			Expect(secondElement.GetElementsCall.Selector.Value).To(Equal(`./option[normalize-space(text())="some text"]`))
		})

		Context("when we fail to retrieve any option", func() {
			It("should return an error", func() {
				secondElement.GetElementsCall.Err = errors.New("some error")
				Expect(selection.Select("some text")).To(MatchError("failed to select specified option for some 'CSS: #selector': some error"))
			})
		})

		Context("when any of the elements has no options with matching text", func() {
			It("should return an error", func() {
				secondElement.GetElementsCall.ReturnElements = []types.Element{}
				Expect(selection.Select("some text")).To(MatchError(`no options with text "some text" found for some 'CSS: #selector'`))
			})
		})

		It("should successfully click on all options with matching text", func() {
			Expect(selection.Select("some text")).To(Succeed())
			Expect(firstOptions[0].ClickCall.Called).To(BeTrue())
			Expect(firstOptions[1].ClickCall.Called).To(BeTrue())
			Expect(secondOptions[0].ClickCall.Called).To(BeTrue())
			Expect(secondOptions[1].ClickCall.Called).To(BeTrue())
		})

		Context("when the click fails for any of the options", func() {
			It("should return an error", func() {
				secondOptions[1].ClickCall.Err = errors.New("some error")
				Expect(selection.Select("some text")).To(MatchError(`failed to click on option with text "some text" for some 'CSS: #selector': some error`))
			})
		})
	})

	Describe("#Submit", func() {
		BeforeEach(func() {
			client.GetElementsCall.ReturnElements = []types.Element{firstElement, secondElement}
		})

		ItShouldEnsureAtLeastOneElement(func() error {
			return selection.Submit()
		})

		It("should successfully submit all selected elements", func() {
			Expect(selection.Submit()).To(Succeed())
			Expect(firstElement.SubmitCall.Called).To(BeTrue())
			Expect(secondElement.SubmitCall.Called).To(BeTrue())
		})

		Context("when any submit fails", func() {
			It("should return an error", func() {
				secondElement.SubmitCall.Err = errors.New("some error")
				Expect(selection.Submit()).To(MatchError("failed to submit 'CSS: #selector': some error"))
			})
		})
	})
})


text:
var gulp = require("gulp");

var SRC = "./src/**/*.js*"

var defaultTasks = ["build-examples", "test"];

gulp.task("build-examples", require("./gulp/tasks/build-examples"));
gulp.task("test", require("./gulp/tasks/test"));

gulp.task("default", defaultTasks);

/* WATCH */
gulp.task("watch", defaultTasks, function () {
  gulp.watch(SRC, defaultTasks);
});


text:
using Cake.Core.IO;
using Cake.Core.Tooling;

namespace Cake.VsCode
{
    /// <summary>
    /// Contains settings used by <see cref="VscePackager"/>.
    /// </summary>
    public sealed class VscePackageSettings : ToolSettings
    {
        /// <summary>
        /// Gets or sets a value indicating the Output FilePath that should be used when packaging is complete.
        /// </summary>
        public FilePath OutputFilePath { get; set; }

        /// <summary>
        /// Gets or sets a value indicating the Url which will be prepended to all relative links in README.md.
        /// </summary>
        public string BaseContentUrl { get; set; }

        /// <summary>
        /// Gets or sets a value indicating the Url which will be prepended to all relative image links in README.md.
        /// </summary>
        public string BaseImagesUrl { get; set; }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="@dimen/dp0" android:left="@dimen/dp0" android:drawable="@drawable/sell_category_male_focus">
    </item>
    <item>
        <bitmap android:src="@drawable/ic_gallery_pic_select" android:gravity="center"/>
    </item>
</layer-list>