text:
module Spree
  module Admin
    class OrdersController < Spree::Admin::BaseController
      require 'spree/core/gateway_error'
      before_filter :initialize_order_events
      before_filter :load_order, :only => [:edit, :update, :fire, :resend, :open_adjustments, :close_adjustments]

      respond_to :html

      def index
        params[:q] ||= {}
        params[:q][:completed_at_not_null] ||= '1' if Spree::Config[:show_only_complete_orders_by_default]
        @show_only_completed = params[:q][:completed_at_not_null].present?
        params[:q][:s] ||= @show_only_completed ? 'completed_at desc' : 'created_at desc'

        # As date params are deleted if @show_only_completed, store
        # the original date so we can restore them into the params
        # after the search
        created_at_gt = params[:q][:created_at_gt]
        created_at_lt = params[:q][:created_at_lt]

        params[:q].delete(:inventory_units_shipment_id_null) if params[:q][:inventory_units_shipment_id_null] == "0"

        if !params[:q][:created_at_gt].blank?
          params[:q][:created_at_gt] = Time.zone.parse(params[:q][:created_at_gt]).beginning_of_day rescue ""
        end

        if !params[:q][:created_at_lt].blank?
          params[:q][:created_at_lt] = Time.zone.parse(params[:q][:created_at_lt]).end_of_day rescue ""
        end

        if @show_only_completed
          params[:q][:completed_at_gt] = params[:q].delete(:created_at_gt)
          params[:q][:completed_at_lt] = params[:q].delete(:created_at_lt)
        end

        @search = Order.accessible_by(current_ability, :index).ransack(params[:q])
        @orders = @search.result.includes([:user, :shipments, :payments]).
          page(params[:page]).
          per(params[:per_page] || Spree::Config[:orders_per_page])

        # Restore dates
        params[:q][:created_at_gt] = created_at_gt
        params[:q][:created_at_lt] = created_at_lt
      end

      def new
        @order = Order.create
        redirect_to edit_admin_order_url(@order)
      end

      def edit
        @order.shipments.map &:refresh_rates
        # Transition as far as we can go
        while @order.next; end
        # The payment step shows an error of 'No pending payments'
        # Clearing the errors from the order object will stop this error
        # appearing on the edit page where we don't want it to.
        @order.errors.clear
      end

      def update
        return_path = nil
        if @order.update_attributes(params[:order]) && @order.line_items.present?
          @order.update!
          unless @order.complete?
            # Jump to next step if order is not complete.
            return_path = admin_order_customer_path(@order)
          else
            # Otherwise, go back to first page since all necessary information has been filled out.
            return_path = admin_order_path(@order)
          end
        else
          @order.errors.add(:line_items, Spree.t('errors.messages.blank')) if @order.line_items.empty?
        end

        if return_path
          redirect_to return_path
        else
          render :action => :edit
        end
      end

      def fire
        # TODO - possible security check here but right now any admin can before any transition (and the state machine
        # itself will make sure transitions are not applied in the wrong state)
        event = params[:e]
        if @order.send("#{event}")
          flash[:success] = Spree.t(:order_updated)
        else
          flash[:error] = Spree.t(:cannot_perform_operation)
        end
      rescue Spree::Core::GatewayError => ge
        flash[:error] = "#{ge.message}"
      ensure
        redirect_to :back
      end

      def resend
        OrderMailer.confirm_email(@order.id, true).deliver
        flash[:success] = Spree.t(:order_email_resent)

        redirect_to :back
      end

      def open_adjustments
        adjustments = @order.adjustments.where(:state => 'closed')
        adjustments.update_all(:state => 'open')
        flash[:success] = Spree.t(:all_adjustments_opened)

        respond_with(@order) { |format| format.html { redirect_to :back } }
      end

      def close_adjustments
        adjustments = @order.adjustments.where(:state => 'open')
        adjustments.update_all(:state => 'closed')
        flash[:success] = Spree.t(:all_adjustments_closed)

        respond_with(@order) { |format| format.html { redirect_to :back } }
      end

      private

        def load_order
          @order = Order.find_by_number!(params[:id], :include => :adjustments) if params[:id]
          authorize! action, @order
        end

        # Used for extensions which need to provide their own custom event links on the order details view.
        def initialize_order_events
          @order_events = %w{cancel resume}
        end

        def model_class
          Spree::Order
        end
    end
  end
end


text:
package com.twu.inputOutput;

/**
 * Interface to read input from different sources
 */
public interface InputReader {

    String read();
}

redpajama_set_name: RedPajamaGithub


text:
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using System.Collections.Generic;

namespace RecordConstructorGenerator
{
    public static class SyntaxExtensions
    {
        public const string RecordComment = "Record Constructor";
        public const string CopyComment = "Copy Constructor";

        public static ConstructorDeclarationSyntax GetRecordConstructor(this TypeDeclarationSyntax typeDecl)
            => (ConstructorDeclarationSyntax)typeDecl.Members
                .FirstOrDefault(m => m.IsKind(SyntaxKind.ConstructorDeclaration) && m.IsGenerated());

        private static bool IsGenerated(this MemberDeclarationSyntax m)
            => m.HasLeadingTrivia
                && m.GetLeadingTrivia().Any(trivia =>
                    trivia.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia) && trivia.ToString().Contains(RecordComment));

        public static bool IsAutoProperty(this PropertyDeclarationSyntax p)
        {
            if (p.AccessorList == null) return false;

            return p.AccessorList.Accessors.All(a => a != null && a.Body == null)
                && p.Initializer == null
                && !p.Modifiers.Any(m => m.IsKind(SyntaxKind.AbstractKeyword));
        }

        public static bool IsGetOnlyAuto(this PropertyDeclarationSyntax p)
        {
            if (p.AccessorList == null) return false;
            if (p.AccessorList.Accessors.Count != 1) return false;

            var accessor = p.AccessorList.Accessors[0];

            return accessor != null
                && accessor.Keyword.IsKind(SyntaxKind.GetKeyword)
                && accessor.Body == null
                && p.Initializer == null
                && !p.Modifiers.Any(m => m.IsKind(SyntaxKind.AbstractKeyword));
        }

        /// <summary>
        /// Creates <see cref="TypeDeclarationSyntax"/> with the same identifier as <paramref name="typeDecl"/>, a partial modifier and an empty body.
        /// </summary>
        /// <param name="typeDecl"></param>
        /// <returns></returns>
        public static TypeDeclarationSyntax CreatePartialTypeDelaration(this TypeDeclarationSyntax typeDecl)
        {
            var name = typeDecl.Identifier.Text;

            if (typeDecl.IsKind(SyntaxKind.ClassDeclaration))
            {
                return CSharpSyntaxTree.ParseText($@"
partial class {name}
{{
}}
").GetRoot().ChildNodes().OfType<ClassDeclarationSyntax>().First();
            }
            else
            {
                return CSharpSyntaxTree.ParseText($@"
partial struct {name}
{{
}}
").GetRoot().ChildNodes().OfType<StructDeclarationSyntax>().First();
            }
        }

        /// <summary>
        /// Finds all <see cref="TypeDeclarationSyntax"/>s which have the same identifier as <paramref name="typeDecl"/> from <paramref name="compilation"/>.
        /// </summary>
        /// <param name="typeDecl"></param>
        /// <param name="compilation"></param>
        /// <returns></returns>
        public static IEnumerable<TypeDeclarationSyntax> FindPartialTypeDelarations(this TypeDeclarationSyntax typeDecl, Compilation compilation)
        {
            foreach (var tree in compilation.SyntaxTrees)
            {
                var root = tree.GetRoot();
                var types = root.DescendantNodes(n => !(n is TypeDeclarationSyntax))
                    .OfType<TypeDeclarationSyntax>()
                    .Where(n => n.Identifier.Text == typeDecl.Identifier.Text);

                foreach (var t in types)
                {
                    yield return t;
                }
            }
        }

        public static TypeDeclarationSyntax AddMembers(this TypeDeclarationSyntax typeDecl, params MemberDeclarationSyntax[] members)
        {
            if (typeDecl.IsKind(SyntaxKind.ClassDeclaration))
                return ((ClassDeclarationSyntax)typeDecl).AddMembers(members);
            else
                return ((StructDeclarationSyntax)typeDecl).AddMembers(members);
        }

        private static readonly SyntaxToken PartialToken = SyntaxFactory.Token(SyntaxKind.PartialKeyword);

        public static TypeDeclarationSyntax AddPartialModifier(this TypeDeclarationSyntax typeDecl)
        {
            if (typeDecl.IsKind(SyntaxKind.ClassDeclaration))
            {
                var d = ((ClassDeclarationSyntax)typeDecl);
                if (d.Modifiers.Any(m => m.IsKind(SyntaxKind.PartialKeyword))) return d;
                return d.AddModifiers(new[] { PartialToken });
            }
            else
            {
                var d = ((StructDeclarationSyntax)typeDecl);
                if (d.Modifiers.Any(m => m.IsKind(SyntaxKind.PartialKeyword))) return d;
                return d.AddModifiers(new[] { PartialToken });
            }
        }
    }

    public class Property
    {
        public IdentifierName Name { get; }

        private PropertyDeclarationSyntax _p;

        public TypeSyntax Type => _p.Type;

        public Property(PropertyDeclarationSyntax p)
        {
            Name = IdentifierName.FromUpper(p.Identifier.Text);
            _p = p;
        }

        public ParameterSyntax ToParameter(bool isOptional)
            => isOptional ?
                Parameter(
                    default(SyntaxList<AttributeListSyntax>),
                    default(SyntaxTokenList),
                    Type,
                    Identifier(GenerateLowercaseIdentifierName(Name.Lower)),
                    EqualsValueClause(DefaultExpression(Type)))
            :
                Parameter(
                    default(SyntaxList<AttributeListSyntax>),
                    default(SyntaxTokenList),
                    Type,
                    Identifier(GenerateLowercaseIdentifierName(Name.Lower)),
                    null)
            ;

        public ExpressionStatementSyntax ToAssignment(string instanceName) => ExpressionStatement(
            AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
                IdentifierName(Name.Upper),
                MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
                    IdentifierName(instanceName),
                    IdentifierName(Name.Original))));

        public ExpressionStatementSyntax ToAssignment() => ExpressionStatement(
            AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
                IdentifierName(Name.Upper),
                IdentifierName(GenerateLowercaseIdentifierName(Name.Lower))));

        private string GenerateLowercaseIdentifierName(string name) =>
            SyntaxFacts.GetKeywordKind(name) == SyntaxKind.None ? name : "@" + name;
    }

    public struct IdentifierName
    {
        public string Original { get; }
        public string Lower { get; }
        public string Upper { get; }

        private IdentifierName(string original, string lower, string upper) { Original = original; Lower = lower; Upper = upper; }

        public static IdentifierName FromUpper(string upper) => new IdentifierName(upper, char.ToLower(upper[0]) + upper.Substring(1, upper.Length - 1), upper);
        public static IdentifierName FromLower(string lower) => new IdentifierName(lower, lower, char.ToUpper(lower[0]) + lower.Substring(1, lower.Length - 1));
    }
}


text: import cycles.d


text:
use super::*;

#[derive(Clone)]
pub struct Runtime {
    pub process_fn: Function,
    pub process_join_fn: Function,
}

impl Runtime {
    pub fn new() -> Runtime {
        Runtime {
            process_fn: Function::new(
                Symbol::new("__libruntime__process"),
                vec![
                    Variable::new(Symbol::new("f"), LambdaType::new(Types::new(), PrimitiveType::Void))
                ],
                PtrType::new(PrimitiveType::I8),
                None
            ),
            process_join_fn: Function::new(
                Symbol::new("__libruntime__process_join"),
                vec![
                    Variable::new(Symbol::new("process"), PtrType::new(PrimitiveType::I8))
                ],
                PrimitiveType::Void,
                None
            ),
        }
    }

    pub fn functions(&self) -> Functions {
        vec![self.process_fn.clone(),
             self.process_join_fn.clone()]
    }
}


text:
package tests

import (
	"github.com/kalcok/jc"
)

// Test Fixtures
type (
	ImplicitID struct {
		jc.Collection `bson:"-"json:"-"`
		Data string   `bson:"data"json:"data"`
	}

	ExplicitID struct {
		jc.Collection `bson:"-"json:"-"`
		MyID int      `bson:"_id"json:"myID"`
		Data string   `bson:"data"json:"data"`
	}
	ExplicitCollection struct {
		jc.Collection `bson:"-"json:"-"jc:"my_collection"`
		Data string   `bson:"data"json:"data"`
	}
	ImplicitCollection struct {
		jc.Collection `bson:"-"json:"-"`
		Data string   `bson:"data"json:"data"`
	}
)

// Benchmark Fixtures
type (
	simpleUserMGO struct {
		name    string
		surname string
		address string
		age     int
	}

	simpleUserJC struct {
		jc.Collection
		name    string
		surname string
		address string
		age     int
	}
)


text:
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;

/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \common\models\LoginForm */

$this->title = '网站登录';

$fieldOptions1 = [
    'options' => ['class' => 'form-group has-feedback'],
    'inputTemplate' => "{input}"
];

$fieldOptions2 = [
    'options' => ['class' => 'form-group has-feedback'],
    'inputTemplate' => "{input}"
];
?>
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0,user-scalable=no"/>
    <meta http-equiv="Cache-Control" content="no-siteapp"/>
    <LINK rel="Bookmark" href="/favicon.ico">
    <LINK rel="Shortcut Icon" href="/favicon.ico"/>
    <title>系统管理</title>

    <link href="../css/H-ui.min.css" rel="stylesheet">
    <link href="../css/login.css" rel="stylesheet">

                    <?php $form = ActiveForm::begin(['id' => 'login-form', 'enableClientValidation' => false]); ?>

                        <?= $form
                            ->field($model, 'username', $fieldOptions1)
                            ->label(false)
                            ->textInput(['placeholder' => $model->getAttributeLabel('username')]) ?>

                        <?= $form
                            ->field($model, 'password', $fieldOptions2)
                            ->label(false)
                            ->passwordInput(['placeholder' => $model->getAttributeLabel('password')]) ?>

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

                        <?= Html::submitButton(Yii::t('app', 'Sign in'), ['class' => 'btn btn-primary btn-block btn-flat', 'name' => 'login-button']) ?>

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


text:
[ -d .liquidprompt ] || {
	git clone https://github.com/nojhan/liquidprompt.git .liquidprompt
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="@dimen/resume_item_spacing">

    <TextView
        android:id="@+id/work_textview_name"
        style="@style/Header"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:text="Avalon English School" />

    <TextView
        android:id="@+id/work_textview_location"
        style="@style/TextAppearance.AppCompat.Subhead"
        android:layout_width="wrap_content"

        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_below="@id/work_textview_name"
        tools:text="Bupyeong, KR" />

    <TextView
        android:id="@+id/work_textview_position"
        style="@style/TextAppearance.AppCompat.Subhead"
        android:layout_width="wrap_content"

        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@id/work_textview_name"
        android:textIsSelectable="true"
        android:textStyle="bold"
        tools:text="English Teacher" />

    <TextView
        android:id="@+id/work_textview_years"
        style="@style/TextAppearance.AppCompat.Body1"
        android:layout_width="wrap_content"

        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@id/work_textview_position"
        android:paddingTop="8dp"
        android:textIsSelectable="true"
        tools:text="March 2014 - March 2015" />

</RelativeLayout>


text:
        {{ site.author.name }}

    maintains
    {{ site.project.name }}


text:
#include "polycode/ide/EntityEditorTreeView.h"

EntityEditorTreeSheet::EntityEditorTreeSheet(Core *core, ResourcePool *pool) : PropSheet(core, pool, "LIST VIEW", "list_view"){
	treeContainer = new UITreeContainer(core, pool, "folder.png", "Root", 10, 10);
	contents->addChild(treeContainer);
	treeContainer->getRootNode()->addEventListener(this, UITreeEvent::SELECTED_EVENT);
	treeContainer->setPosition(-20, -5);
	treeContainer->getRootNode()->toggleCollapsed();

	selectedEntity = NULL;
	dontSendSelectionEvent = false;
}

EntityEditorTreeView::EntityEditorTreeView(Core *core, ResourcePool *pool) : UIElement(core) {

	entityProps = new PropList(core, pool, "HIERARCHY");
	addChild(entityProps);

	layerSheet = new LayerSheet(core, pool);
	entityProps->addPropSheet(layerSheet);
	layerSheet->addEventListener(this, PropEvent::EVENT_PROP_CHANGE);

	treeSheet = new EntityEditorTreeSheet(core, pool);
	entityProps->addPropSheet(treeSheet);

}

void EntityEditorTreeSheet::setRootEntity(Entity *entity) {
	rootEntity = entity;
	treeContainer->getRootNode()->setUserData((void*) entity);
	refreshTree();
}

void EntityEditorTreeSheet::syncNodeToEntity(UITree *node, Entity *entity) {
	// remove non existing and set proper ids,

	std::vector<UITree*> nodesToRemove;

	for(int i=0; i < node->getNumTreeChildren(); i++) {
		UITree *child = node->getTreeChild(i);

		bool hasChild = false;
		for(int j=0; j < entity->getNumChildren(); j++) {
			if(!entity->getChildAtIndex(j)->editorOnly) {
				if(((Entity*)child->getUserData()) == entity->getChildAtIndex(j)) {
					hasChild = true;

					String entityName = entity->getChildAtIndex(j)->id;
					if(entityName == "") {
						entityName = "<unnamed entity>";
					}

					if(child->getLabelText() != entityName) {
						child->setLabelText(entityName);
					}

					if(entity->getChildAtIndex(j) == selectedEntity) {
						dontSendSelectionEvent = true;
						child->setSelected();
					}

				}
			}
		}

		if(!hasChild) {
			nodesToRemove.push_back(child);
		}
	}

	for(int i=0; i < nodesToRemove.size(); i++) {
		node->removeTreeChild(nodesToRemove[i]);
	}

	std::vector<Entity*> entitiesToAdd;

	for(int j=0; j < entity->getNumChildren(); j++) {
		if(!entity->getChildAtIndex(j)->editorOnly) {
			bool hasEntity = false;
			for(int i=0; i < node->getNumTreeChildren(); i++) {
				UITree *child = node->getTreeChild(i);
				if(((Entity*)child->getUserData()) == entity->getChildAtIndex(j)) {
					hasEntity = true;
				}
			}

			if(!hasEntity) {
				entitiesToAdd.push_back(entity->getChildAtIndex(j));
			}
		}
	}

	for(int i=0; i < entitiesToAdd.size(); i++) {

		String entityName = entitiesToAdd[i]->id;
		if(entityName == "") {
			entityName = "<unnamed entity>";
		}

		UITree *newNode = node->addTreeChild("file.png", entityName);
		newNode->setUserData((void*)entitiesToAdd[i]);

		if(entitiesToAdd[i] == selectedEntity) {
			dontSendSelectionEvent = true;
			newNode->setSelected();
		}
	}

	for(int i=0; i < node->getNumTreeChildren(); i++) {
		UITree *child = node->getTreeChild(i);
		syncNodeToEntity(child, ((Entity*)child->getUserData()));
	}
}

Entity *EntityEditorTreeSheet::getSelectedEntity() {
	return selectedEntity;
}

void EntityEditorTreeSheet::setSelectedEntity(Entity *entity) {
	selectedEntity = entity;
	refreshTree();
}

void EntityEditorTreeSheet::handleEvent(Event *event) {

	if(event->getDispatcher() == treeContainer->getRootNode()) {
		if(event->getEventCode() == UITreeEvent::SELECTED_EVENT){
			if(!dontSendSelectionEvent) {
//				  if(treeContainer->getRootNode()->getSelectedNode() != treeContainer->getRootNode()) {
					selectedEntity = (Entity*)treeContainer->getRootNode()->getSelectedNode()->getUserData();
					dispatchEvent(new Event(), Event::CHANGE_EVENT);
//				  }
			}
			dontSendSelectionEvent = false;
		}
	}
	PropSheet::handleEvent(event);
}

void EntityEditorTreeView::setEntityInstance(SceneEntityInstance *instance) {
	treeSheet->setRootEntity(instance);
	layerSheet->setEntityInstance(instance);
}

void EntityEditorTreeSheet::refreshTree() {
	if(selectedEntity == rootEntity) {
		dontSendSelectionEvent = true;
		treeContainer->getRootNode()->setSelected();
	} else {
		syncNodeToEntity(treeContainer->getRootNode(), rootEntity);
	}
}

EntityEditorTreeSheet::~EntityEditorTreeSheet() {

}

EntityEditorTreeSheet *EntityEditorTreeView::getTreeSheet() {
	return treeSheet;
}

void EntityEditorTreeSheet::Resize(Number width, Number height) {
	treeContainer->Resize(width, height-60);
	PropSheet::Resize(width, height);
}

void EntityEditorTreeView::Resize(Number width, Number height) {
	entityProps->Resize(width, height);
}


text:
from __future__ import unicode_literals

from django_evolution.mutations import ChangeMeta

MUTATIONS = [
    ChangeMeta('HostingServiceAccount', 'unique_together', []),
]


text:
package com.java110.vo.api.complaint;

import com.java110.vo.MorePageVo;

import java.io.Serializable;
import java.util.List;

public class ApiComplaintVo extends MorePageVo implements Serializable {
    List<ApiComplaintDataVo> complaints;

    public List<ApiComplaintDataVo> getComplaints() {
        return complaints;
    }

    public void setComplaints(List<ApiComplaintDataVo> complaints) {
        this.complaints = complaints;
    }
}


text:
"""
Copy pykit IR.
"""

from __future__ import print_function, division, absolute_import
from functools import partial
from pykit.ir import (Module, Value, Function, Block, Constant, Op,
                      GlobalValue, Undef, FuncArg)
from pykit.utils import nestedmap, make_temper

def _lookup(module, function, valuemap, arg):
    """Helper to reconstruct Operations"""
    if isinstance(arg, (Block, Op)):
        result = valuemap[arg]
    elif isinstance(arg, FuncArg):
        result = function.get_arg(arg.result)
    elif isinstance(arg, Function) and module is not None:
        result = module.get_function(arg.name)
    elif isinstance(arg, GlobalValue) and module is not None:
        result = module.get_global(arg.name)
    else:
        assert isinstance(arg, (Constant, FuncArg, Undef))
        result = arg # immutable

    assert result is not None, arg
    assert isinstance(result, Value)
    return result

# ______________________________________________________________________

def copy_module(module, temper=None):
    raise NotImplementedError("not finished, needs to insert all functions"
                              "in valuemap first")

    new_module = Module(temper=temper)
    valuemap = {}

    ### Copy Globals
    for name, gv in module.globals.iteritems():
        name = new_module.temp(name)
        new_global = GlobalValue(name, gv.type, gv.external, gv.address, gv.value)
        new_module.add_global(new_global)

        valuemap[gv] = new_global

    ### Copy Functions
    for name, func in module.functions.iteritems():
        new_func = copy_function(func, module=new_module)
        new_func.name = new_module.temp(name)
        new_module.add_function(new_func)

        valuemap[func] = new_func

    return new_module

def copy_function(func, temper=None, module=None):
    """Copy a Function. `temper` may be given to"""
    temper = temper or make_temper()
    f = Function(func.name, list(func.argnames), func.type, temper=temper)
    valuemap = {}
    lookup = partial(_lookup, module or func.module, f, valuemap)

    ### Construct new Blocks
    for block in func.blocks:
        new_block = Block(temper(block.name), f)
        valuemap[block] = new_block
        f.add_block(new_block)

    ### Construct new Operations
    for block in func.blocks:
        new_block = valuemap[block]
        for op in block.ops:
            new_op = Op(op.opcode, op.type, nestedmap(lookup, op.args),
                        result=temper(op.result), parent=new_block)
            # assert new_op.result != op.result

            valuemap[op] = new_op
            new_block.append(new_op)

    return f


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/clear"
        android:icon="@drawable/ic_broom"
        android:title="Supprimer les transferts inactifs"
        app:showAsAction="always" />
</menu>


text:
import { TestBed, inject } from '@angular/core/testing';

import { FilterByService } from './filter-by.service';

describe('FilterByService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [FilterByService]
    });
  });

  it('should be created', inject([FilterByService], (service: FilterByService) => {
    expect(service).toBeTruthy();
  }));
});


text:
/**
 * Created by vadimsky on 17/06/16.
 */
var User = require("./user");

/**
 * @param userName
 * @param password
 *
 * @return user or undefined
 */
function authen(userName, password) {
    return undefined;
}

module.exports.register = () => {
    let user  = new User();
    user.save((err) => {

    });

}


text:
//
// Segrey Software 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.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace KettleModel
{
    public class TransformationStep : KettleEntry
    {
         public Transformation Transformation { get; private set; }

         public TransformationStep(Transformation transformation, XElement element)
             : base(transformation, element)
         {
             Transformation = transformation;
         }

    }
}


text:
class AddProjects < ActiveRecord::Migration
  def change
    create_table :projects do |t|
      t.string  :title
      t.integer :owner_id

      t.timestamps
    end
  end
end


text:
#
# Author:: Adam Jacob (<adam@chef.io>)
# Copyright:: Copyright (c) Chef Software Inc.
# License:: Apache License, Version 2.0
#
# 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.

# If you need to add anything in here, don't.
# Add it to one of the files in spec/support

# Abuse ruby's constant lookup to avoid undefined constant errors
module Shell
  JUST_TESTING_MOVE_ALONG = true unless defined? JUST_TESTING_MOVE_ALONG
  IRB = nil unless defined? IRB
end

$LOAD_PATH.unshift File.expand_path("..", __dir__)

$LOAD_PATH.unshift File.expand_path("../chef-config/lib", __dir__)
$LOAD_PATH.unshift File.expand_path("../chef-utils/lib", __dir__)

require "rubygems"
require "rspec/mocks"

require "webmock/rspec"

require "chef"
require "chef/knife"

Dir["lib/chef/knife/**/*.rb"]
  .map { |f| f.gsub("lib/", "") }
  .map { |f| f.gsub(/\.rb$/, "") }
  .each { |f| require f }

require "chef/resource_resolver"
require "chef/provider_resolver"

require "chef/mixins"
require "chef/dsl"
require "chef/application"
require "chef/applications"

require "chef/shell"
require "chef/util/file_edit"

require "chef/config"

require "chef/chef_fs/file_system_cache"

require "chef/api_client_v1"

require "chef/mixin/versioned_api"
require "chef/server_api_versions"

if ENV["CHEF_FIPS"] == "1"
  Chef::Config.init_openssl
end

# If you want to load anything into the testing environment
# without versioning it, add it to spec/support/local_gems.rb
require "spec/support/local_gems" if File.exist?(File.join(File.dirname(__FILE__), "support", "local_gems.rb"))

# Explicitly require spec helpers that need to load first
require "spec/support/platform_helpers"
require "spec/support/shared/unit/mock_shellout"

require "spec/support/recipe_dsl_helper"

# Autoloads support files
# Excludes support/platforms by default
# Do not change the gsub.
Dir["spec/support/**/*.rb"]
  .reject { |f| f =~ %r{^spec/support/platforms} }
  .reject { |f| f =~ %r{^spec/support/pedant} }
  .map { |f| f.gsub(/.rb$/, "") }
  .map { |f| f.gsub(%r{spec/}, "") }
  .each { |f| require f }

OHAI_SYSTEM = Ohai::System.new
OHAI_SYSTEM.all_plugins(["platform", "hostname", "languages/powershell"])

test_node = Chef::Node.new
test_node.automatic["os"] = (OHAI_SYSTEM["os"] || "unknown_os").dup.freeze
test_node.automatic["platform_family"] = (OHAI_SYSTEM["platform_family"] || "unknown_platform_family").dup.freeze
test_node.automatic["platform"] = (OHAI_SYSTEM["platform"] || "unknown_platform").dup.freeze
test_node.automatic["platform_version"] = (OHAI_SYSTEM["platform_version"] || "unknown_platform_version").dup.freeze
TEST_NODE = test_node.freeze
TEST_OS = TEST_NODE["os"]
TEST_PLATFORM = TEST_NODE["platform"]
TEST_PLATFORM_VERSION = TEST_NODE["platform_version"]
TEST_PLATFORM_FAMILY = TEST_NODE["platform_family"]

provider_priority_map ||= nil
resource_priority_map ||= nil
provider_handler_map ||= nil
resource_handler_map ||= nil

class UnexpectedSystemExit < RuntimeError
  def self.from(system_exit)
    new(system_exit.message).tap { |e| e.set_backtrace(system_exit.backtrace) }
  end
end

RSpec.configure do |config|
  config.include(Matchers)
  config.include(MockShellout::RSpec)
  config.filter_run focus: true
  config.filter_run_excluding external: true
  config.raise_on_warning = true

  # Explicitly disable :should syntax
  # And set max_formatted_output_length to nil to prevent RSpec from doing truncation.
  config.expect_with :rspec do |c|
    c.syntax = :expect
    c.max_formatted_output_length = nil
  end
  config.mock_with :rspec do |c|
    c.syntax = :expect
    c.allow_message_expectations_on_nil = false
  end

  # Only run these tests on platforms that are also chef workstations
  config.filter_run_excluding :workstation if solaris? || aix?

  # Tests that randomly fail, but may have value.
  config.filter_run_excluding volatile: true
  config.filter_run_excluding volatile_on_solaris: true if solaris?
  config.filter_run_excluding volatile_from_verify: false

  config.filter_run_excluding skip_buildkite: true if ENV["BUILDKITE"]

  config.filter_run_excluding windows_only: true unless windows?
  config.filter_run_excluding not_supported_on_windows: true if windows?
  config.filter_run_excluding not_supported_on_macos: true if macos?
  config.filter_run_excluding macos_only: true unless macos?
  config.filter_run_excluding macos_1013: true unless macos_1013?
  config.filter_run_excluding macos_gte_1014: true unless macos_gte_1014?
  config.filter_run_excluding not_supported_on_aix: true if aix?
  config.filter_run_excluding not_supported_on_solaris: true if solaris?
  config.filter_run_excluding not_supported_on_gce: true if gce?
  config.filter_run_excluding win2012r2_only: true unless windows_2012r2?
  config.filter_run_excluding windows64_only: true unless windows64?
  config.filter_run_excluding windows32_only: true unless windows32?
  config.filter_run_excluding windows_gte_10: true unless windows_gte_10?
  config.filter_run_excluding windows_lt_10: true if windows_gte_10?
  config.filter_run_excluding ruby64_only: true unless ruby_64bit?
  config.filter_run_excluding ruby32_only: true unless ruby_32bit?
  config.filter_run_excluding windows_powershell_dsc_only: true unless windows_powershell_dsc?
  config.filter_run_excluding windows_powershell_no_dsc_only: true if windows_powershell_dsc?
  config.filter_run_excluding windows_domain_joined_only: true unless windows_domain_joined?
  config.filter_run_excluding windows_not_domain_joined_only: true if windows_domain_joined?
  # We think this line was causing rspec tests to not run on the Jenkins windows
  # testers. If we ever fix it we should restore it.
  # config.filter_run_excluding :windows_service_requires_assign_token => true if !STDOUT.isatty && !windows_user_right?("SeAssignPrimaryTokenPrivilege")
  config.filter_run_excluding windows_service_requires_assign_token: true
  config.filter_run_excluding solaris_only: true unless solaris?
  config.filter_run_excluding system_windows_service_gem_only: true unless system_windows_service_gem?
  config.filter_run_excluding unix_only: true unless unix?
  config.filter_run_excluding linux_only: true unless linux?
  config.filter_run_excluding aix_only: true unless aix?
  config.filter_run_excluding suse_only: true unless suse?
  config.filter_run_excluding opensuse: true unless opensuse?
  config.filter_run_excluding debian_family_only: true unless debian_family?
  config.filter_run_excluding supports_cloexec: true unless supports_cloexec?
  config.filter_run_excluding selinux_only: true unless selinux_enabled?
  config.filter_run_excluding requires_root: true unless root?
  config.filter_run_excluding requires_root_or_running_windows: true unless root? || windows?
  config.filter_run_excluding requires_unprivileged_user: true if root?
  config.filter_run_excluding openssl_gte_101: true unless openssl_gte_101?
  config.filter_run_excluding openssl_lt_101: true unless openssl_lt_101?
  config.filter_run_excluding aes_256_gcm_only: true unless aes_256_gcm?
  config.filter_run_excluding broken: true
  config.filter_run_excluding not_wpar: true unless wpar?
  config.filter_run_excluding not_supported_under_fips: true if fips?
  config.filter_run_excluding rhel: true unless rhel?
  config.filter_run_excluding rhel6: true unless rhel6?
  config.filter_run_excluding rhel7: true unless rhel7?
  config.filter_run_excluding rhel8: true unless rhel8?
  config.filter_run_excluding rhel_gte_8: true unless rhel_gte_8?
  config.filter_run_excluding intel_64bit: true unless intel_64bit?
  config.filter_run_excluding not_rhel: true if rhel?
  config.filter_run_excluding not_rhel6: true if rhel6?
  config.filter_run_excluding not_rhel7: true if rhel7?
  config.filter_run_excluding not_intel_64bit: true if intel_64bit?

  # these let us use chef: ">= 13" or ruby: "~> 2.0.0" or any other Gem::Dependency-style constraint
  config.filter_run_excluding chef: DependencyProc.with(Chef::VERSION)
  config.filter_run_excluding ruby: DependencyProc.with(RUBY_VERSION)

  # check for particular binaries we need
  config.filter_run_excluding choco_installed: true unless choco_installed?
  config.filter_run_excluding requires_ifconfig: true unless ifconfig?
  config.filter_run_excluding pwsh_installed: true unless pwsh_installed?

  running_platform_arch = `uname -m`.strip unless windows?

  config.filter_run_excluding arch: lambda { |target_arch|
    running_platform_arch != target_arch
  }

  # Functional Resource tests that are provider-specific:
  # context "on platforms that use useradd", :provider => {:user => Chef::Provider::User::Useradd}} do #...
  config.filter_run_excluding provider: lambda { |criteria|
    type, target_provider = criteria.first

    node = TEST_NODE.dup
    resource_class = Chef::ResourceResolver.resolve(type, node: node)
    if resource_class
      resource = resource_class.new("test", Chef::RunContext.new(node, nil, nil))
      begin
        provider = resource.provider_for_action(Array(resource_class.default_action).first)
        provider.class != target_provider
      rescue Chef::Exceptions::ProviderNotFound # no provider for platform
        true
      end
    else
      true
    end
  }

  config.run_all_when_everything_filtered = true

  config.before(:each) do
    # it'd be nice to run this with connections blocked or only to localhost, but we do make lots
    # of real connections, so cannot.  we reset it to allow connections every time to avoid
    # tests setting connections to be disabled and that state leaking into other tests.
    WebMock.allow_net_connect!

    Chef.reset!

    Chef::ChefFS::FileSystemCache.instance.reset!

    Chef::Config.reset

    Chef::Log.setup!

    Chef::ServerAPIVersions.instance.reset!

    Chef::Config[:log_level] = :fatal
    Chef::Log.level(Chef::Config[:log_level])

    # By default, treat deprecation warnings as errors in tests.
    Chef::Config.treat_deprecation_warnings_as_errors(true)

    # Set environment variable so the setting persists in child processes
    ENV["CHEF_TREAT_DEPRECATION_WARNINGS_AS_ERRORS"] = "1"

    # we don't perfectly reset the priority/handler maps here, but by dup'ing the top level hash we
    # throw away all the garbage resources and providers that we setup.  if we mutate something like
    # :package then that'll carry over from test-to-test, but the solution would be to deep-dup on every
    # single test we run which is much more expensive.  by throwing away the garbage top level keys we
    # significantly speed up test runs.
    provider_handler_map ||= Chef.provider_handler_map.send(:map).dup
    resource_handler_map ||= Chef.resource_handler_map.send(:map).dup
    provider_priority_map ||= Chef.provider_priority_map.send(:map).dup
    resource_priority_map ||= Chef.resource_priority_map.send(:map).dup
    Chef.provider_handler_map.instance_variable_set(:@map, provider_handler_map.dup)
    Chef.resource_handler_map.instance_variable_set(:@map, resource_handler_map.dup)
    Chef.provider_priority_map.instance_variable_set(:@map, provider_priority_map.dup)
    Chef.resource_priority_map.instance_variable_set(:@map, resource_priority_map.dup)
  end

  # This bit of jankiness guards against specs which accidentally drop privs when running as
  # root -- which are nearly impossible to debug and so we bail out very hard if this
  # condition ever happens.  If a spec stubs Process.[e]uid this can throw a false positive
  # which the spec must work around by unmocking Process.[e]uid to and_call_original in its
  # after block.
  if Process.euid == 0 && Process.uid == 0
    config.after(:each) do
      if Process.uid != 0
        RSpec.configure { |c| c.fail_fast = true }
        raise "rspec was invoked as root, but the last test dropped real uid to #{Process.uid}"
      end
      if Process.euid != 0
        RSpec.configure { |c| c.fail_fast = true }
        raise "rspec was invoked as root, but the last test dropped effective uid to #{Process.euid}"
      end
    end
  end

  # raise if anyone commits any test to CI with :focus set on it
  if ENV["CI"]
    config.before(:example, :focus) do
      raise "This example was committed with `:focus` and should not have been"
    end
  end

  config.before(:suite) do
    ARGV.clear
  end

  # Protect Rspec from accidental exit(0) causing rspec to terminate without error
  config.around(:example) do |ex|

    ex.run
  rescue SystemExit => e
    raise UnexpectedSystemExit.from(e)

  end
end

require "webrick/utils"
#    Webrick uses a centralized/synchronized timeout manager. It works by
#    starting a thread to check for timeouts on an interval. The timeout
#    checker thread cannot be stopped or canceled in any easy way, and it
#    makes calls to Time.new, which fail when rspec is in the process of
#    creating a method stub for that method. Since our tests don't rely on
#    any timeout behavior enforced by webrick, disable the timeout manager
#    via a monkey patch.
#
#    Hopefully this fails loudly if the webrick code should change. As of this
#    writing, the relevant code is in webrick/utils, which can be located on
#    your system with:
#
#    $ gem which webrick/utils
module WEBrick
  module Utils
    class TimeoutHandler
      def initialize; end

      def register(*args); end

      def cancel(*args); end
    end
  end
end

# Enough stuff needs json serialization that I'm just adding it here for equality asserts
require "chef/json_compat"


text:
from optparse import make_option

from django.core.management.base import BaseCommand, CommandError
from django.db import DatabaseError

from mkt.carriers import CARRIER_CHOICE_DICT, CARRIER_MAP
from mkt.operators.models import OperatorPermission
from mkt.regions import REGIONS_CHOICES_ID_DICT, REGIONS_DICT
from mkt.users.models import UserProfile

all_opt = make_option('--all', action='store_true', dest='remove_all',
                      default=False,
                      help='Remove all operator permissions for the user')

class Command(BaseCommand):
    args = '[command] [command_options]'
    option_list = BaseCommand.option_list + (all_opt,)
    help = ('Add, remove, or list operator permissions for a user:\n\n'
            'manage.py operator_user add <email> <carrier> <region>\n'
            'manage.py operator_user remove <email> <carrier> <region>\n'
            'manage.py operator_user remove --all <email>\n'
            'manage.py operator_user list <email>')

    def get_user(self, email):
        try:
            return UserProfile.objects.get(email=email)
        except UserProfile.DoesNotExist:
            raise CommandError('No user account for: %s' % email)

    def get_region_id(self, slug):
        try:
            return REGIONS_DICT[slug].id
        except KeyError:
            raise CommandError('Invalid region: %r' % slug)

    def get_carrier_id(self, slug):
        try:
            return CARRIER_MAP[slug].id
        except KeyError:
            raise CommandError('Invalid carrier: %r' % slug)

    def get_region_slug(self, id):
        try:
            return REGIONS_CHOICES_ID_DICT[id].slug
        except KeyError:
            raise CommandError('Invalid region: %r' % id)

    def get_carrier_slug(self, id):
        try:
            return CARRIER_CHOICE_DICT[id].slug
        except KeyError:
            raise CommandError('Invalid carrier: %r' % id)

    def get_ecr(self, args):
        sliced = args[1:]
        if not len(sliced) == 3:
            raise CommandError('Did not pass <email> <carrier> <region>')
        return sliced

    def handle(self, *args, **options):
        try:
            cmd = args[0]
        except IndexError:
            raise CommandError('No command passed.')

        if cmd == 'add':
            email, carrier, region = self.get_ecr(args)
            try:
                OperatorPermission.objects.create(
                    user=self.get_user(email),
                    region=self.get_region_id(region),
                    carrier=self.get_carrier_id(carrier))
                self.stdout.write('Created %s/%s permission for %s' % (
                    region, carrier, email))
            except DatabaseError, e:
                exception = CommandError('Unable to grant permission.')
                exception.args = e.args
                raise exception

        elif cmd == 'remove':

            if options['remove_all']:
                user = self.get_user(args[1])
                qs = OperatorPermission.objects.filter(user=user)
                if len(qs):
                    qs.delete()
                    self.stdout.write('Removed all permissions for %s' % args[1])
                else:
                    raise CommandError('No permissions for %s' % args[1])

            else:
                email, carrier, region = self.get_ecr(args)
                qs = OperatorPermission.objects.filter(
                    user=self.get_user(email),
                    region=self.get_region_id(region),
                    carrier=self.get_carrier_id(carrier))
                if len(qs):
                    qs.delete()
                    self.stdout.write('Removed %s/%s permission for %s' % (
                        region, carrier, email))
                else:
                    raise CommandError('No %s/%s permission for %s' % (
                        region, carrier, email))

        elif cmd == 'list':
            user = self.get_user(args[1])
            qs = OperatorPermission.objects.filter(user=user)
            if len(qs):
                msg = ['Permissions for %s:' % args[1]]
                for item in qs:
                    msg.append('- %s/%s' % (
                        self.get_region_slug(item.region),
                        self.get_carrier_slug(item.carrier),
                    ))
                self.stdout.write('\n'.join(msg))
            else:
                self.stdout.write('No permissions for %s' % args[1])

        else:
            raise CommandError('Invalid command: %s' % cmd)


text:
module Radiant
  class Exporter
    def self.export
      hash = {}
      [Radiant::Config, User, Page, PagePart, Snippet, Layout].each do |klass|
        hash[klass.name.pluralize] = klass.find(:all).inject({}) { |h, record| h[record.id.to_i] = record.attributes; h }
      end
      hash.to_yaml
    end
  end
end


text:
<?xml version="1.0"?>
<Document>

	<Sentence>
		<value>You will need to wear a sling for the first 6 weeks after surgery.</value>
		<pattern_crowdsource> You will need to wear a [[sling|C0441637]] for the first 6 weeks after [[surgery|C0543467]].		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>sling</surface-form>
				<RDF-ID>C0441637</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>first</surface-form>
				<RDF-ID>C1279901</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>weeks</surface-form>
				<RDF-ID>C0439230</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>surgery</surface-form>
				<RDF-ID>C0543467</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0543467 PRECEDES C0441637</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Your surgeon or physical therapist will also teach you safe ways to move your arm and shoulder:  - DO NOT try to lift or move your shoulder without supporting it with your good arm or having someone else support it.</value>
		<pattern_crowdsource> Your surgeon or physical therapist will also teach you safe ways to move your arm and shoulder:  - DO NOT try to lift or move your [[shoulder|C0037004]] without supporting it with your good [[arm|C1140618]] or having someone else support it.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>surgeon</surface-form>
				<RDF-ID>C0582175</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>physical</surface-form>
				<RDF-ID>C0205485</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>therapist</surface-form>
				<RDF-ID>C0871525</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>arm</surface-form>
				<RDF-ID>C1140618</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>shoulder</surface-form>
				<RDF-ID>C0037004</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>NOT</surface-form>
				<RDF-ID>C1518422</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>lift</surface-form>
				<RDF-ID>C0181620</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>shoulder</surface-form>
				<RDF-ID>C0037004</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>supporting</surface-form>
				<RDF-ID>C0183683</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>good</surface-form>
				<RDF-ID>C0205170</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>arm</surface-form>
				<RDF-ID>C1140618</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C1140618 PART_OF C0037004</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Activities and movements you should try to avoid are:  - Reaching or using your shoulder a lot  - Lifting objects heavier than a cup of coffee  - Supporting your body weight with your hand on the side you had surgery  - Making sudden jerking movements    Wear the sling all the time unless your surgeon says you do not have to.</value>
		<pattern_crowdsource> Activities and movements you should try to avoid are:  - Reaching or using your shoulder a lot  - Lifting objects heavier than a [[cup|C0220647]] of coffee  - Supporting your body weight with your [[hand|C0018563]] on the side you had surgery  - Making sudden jerking movements    Wear the sling all the time unless your surgeon says you do not have to.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Activities</surface-form>
				<RDF-ID>C0441655</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>movements</surface-form>
				<RDF-ID>C0026649</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>shoulder</surface-form>
				<RDF-ID>C0037004</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>lot</surface-form>
				<RDF-ID>C1518000</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Lifting</surface-form>
				<RDF-ID>C0206244</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>cup</surface-form>
				<RDF-ID>C0220647</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>coffee</surface-form>
				<RDF-ID>C0009237</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>body weight</surface-form>
				<RDF-ID>C1305866</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>hand</surface-form>
				<RDF-ID>C0018563</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>side</surface-form>
				<RDF-ID>C0441987</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>surgery</surface-form>
				<RDF-ID>C0543467</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>jerking</surface-form>
				<RDF-ID>C0231530</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>movements</surface-form>
				<RDF-ID>C0026649</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>sling</surface-form>
				<RDF-ID>C0183346</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>time</surface-form>
				<RDF-ID>C0040223</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>surgeon</surface-form>
				<RDF-ID>C0582175</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>not</surface-form>
				<RDF-ID>C1518422</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0018563 PART_OF C0220647</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Returning to sports and other activities  Ask your surgeon which sports and other activities are ok for you after you recover.</value>
		<pattern_crowdsource> Returning to sports and other [[activities|C0441655]]  Ask your surgeon which [[sports|C0038039]] and other [[activities|C0441655]] are ok for you after you recover.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>sports</surface-form>
				<RDF-ID>C0038039</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>activities</surface-form>
				<RDF-ID>C0441655</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>surgeon</surface-form>
				<RDF-ID>C0582175</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>sports</surface-form>
				<RDF-ID>C0038039</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>activities</surface-form>
				<RDF-ID>C0441655</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0038039 ISA C0441655</triple>
			<triple>C0038039 ISA C0441655</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>To protect your new shoulder avoid:  - Activities that require doing the same movement over and over again with your shoulder, such as weight lifting.</value>
		<pattern_crowdsource> To protect your new [[shoulder|C0037004]] avoid:  - Activities that require doing the same movement over and over again with your [[shoulder|C0037004]], such as weight lifting.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>new</surface-form>
				<RDF-ID>C0205314</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>shoulder</surface-form>
				<RDF-ID>C0037004</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Activities</surface-form>
				<RDF-ID>C0441655</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>same</surface-form>
				<RDF-ID>C0445247</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>movement</surface-form>
				<RDF-ID>C0026649</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>over</surface-form>
				<RDF-ID>C0205136</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>over</surface-form>
				<RDF-ID>C0205136</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>shoulder</surface-form>
				<RDF-ID>C0037004</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>weight lifting</surface-form>
				<RDF-ID>C0043095</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0037004 PART_OF C0037004</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>- "Impact-loading" sports, such as boxing.</value>
		<pattern_crowdsource> - "Impact-loading" [[sports|C0038039]], such as [[boxing|C0006080]].		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>sports</surface-form>
				<RDF-ID>C0038039</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>boxing</surface-form>
				<RDF-ID>C0006080</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0006080 ISA C0038039</triple>
		</triples>
	</Sentence>

</Document>


text:
PolycodeTextEditor::PolycodeTextEditor() : PolycodeEditor(true){

}

PolycodeTextEditor::~PolycodeTextEditor() {

}

bool PolycodeTextEditor::openFile(String filePath) {

	textInput = new UITextInput(true, 100, 100);
	addChild(textInput);

	Data *data = new Data();
	data->loadFromFile(filePath);
	textInput->insertText(data->getAsString(String::ENCODING_UTF8));
	delete data;

	PolycodeEditor::openFile(filePath);
	return true;
}

void PolycodeTextEditor::saveFile() {
	Data *data = new Data();
	data->setFromString(textInput->getText(), String::ENCODING_UTF8);
	data->saveToFile(filePath);
	delete data;
}

void PolycodeTextEditor::Resize(int x, int y) {
	textInput->Resize(x,y);
}


text:
package com.igormaznitsa.meta.common.utils;

import com.igormaznitsa.meta.common.exceptions.MetaErrorListeners;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.After;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.Before;

public class DeferrersTest {

  @Before
  public void before () {
    MetaErrorListeners.clear();
    TimeGuard.cancelAll();
  }

  @After
  public void after () {
    MetaErrorListeners.clear();
    TimeGuard.cancelAll();
  }

  private static class TestDeferrer extends Deferrers.Deferred {

    private static final long serialVersionUID = -4502902205113537851L;
    private final AtomicInteger value;
    private final int id;
    private final List<Integer> order;

    public TestDeferrer(final AtomicInteger value, final List<Integer> order, final int id){
      super();
      this.value = value;
      this.order = order;
      this.id = id;
    }

    @Override
    public void executeDeferred () throws Exception {
      this.value.decrementAndGet();
      this.order.add(id);
    }
  }

  private static int [] toArray(final List<Integer> value){
    final int [] result = new int[value.size()];
    for(int i=0;i<value.size();i++){
      result[i] = value.get(i);
    }
    return result;
  }

  @Test
  public void testEnd_OneMethod () {
    final AtomicInteger value = new AtomicInteger(1);
    final List<Integer> order = new ArrayList<Integer>();

    Deferrers.defer(new TestDeferrer(value,order,1));
    Deferrers.processDeferredActions();

    assertArrayEquals(new int[]{1}, toArray(order));
    assertEquals(0, value.get());
  }

  @Test
  public void testProcessDeferredActions_TwoMethods () {
    final AtomicInteger value = new AtomicInteger(2);
    final List<Integer> order = new ArrayList<Integer>();

    Deferrers.defer(new TestDeferrer(value,order,1));
    Deferrers.defer(new TestDeferrer(value,order,2));
    Deferrers.processDeferredActions();

    assertEquals(0, value.get());
    assertArrayEquals(new int[]{1,2}, toArray(order));
  }

  @Test
  public void testCancelDeferredActions () {
    final AtomicInteger value = new AtomicInteger(2);
    final List<Integer> order = new ArrayList<Integer>();

    Deferrers.defer(new TestDeferrer(value,order,1));
    Deferrers.defer(new TestDeferrer(value,order,2));
    Deferrers.cancelDeferredActions();
    Deferrers.processDeferredActions();

    assertEquals(2, value.get());
    assertTrue(order.isEmpty());
  }

  @Test
  public void testProcessDeferredActions_MultiLevel () {
    final AtomicInteger value = new AtomicInteger(5);
    final List<Integer> order = new ArrayList<Integer>();

    Deferrers.defer(new TestDeferrer(value,order,1));
    Deferrers.defer(new TestDeferrer(value,order,2));

    secondLevel(value,2,order);

    Deferrers.processDeferredActions();

    assertEquals(0, value.get());
    assertArrayEquals(new int[]{5,3,4,1,2}, toArray(order));
  }

  private void secondLevel(final AtomicInteger value, final int num, final List<Integer> order){
    Deferrers.defer(new TestDeferrer(value,order,3));
    Deferrers.defer(new TestDeferrer(value,order,4));
    thirdLevel(value, 4, order);
    Deferrers.processDeferredActions();
    assertEquals(num, value.get());
  }

  private void thirdLevel(final AtomicInteger value, final int num, final List<Integer> order){
    Deferrers.defer(new TestDeferrer(value,order,5));
    Deferrers.processDeferredActions();
    assertEquals(num, value.get());
  }

}


text:
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.

bigtop-toolchain
===============

##BigTop Toolchain Deployment through Puppet

Puppet module for configuring a host for building BigTop. It installs:

**Apache Ant 1.9**

**OpenJDK 1.8**

**Apache Maven 3.5**

**Gradle 2.4**

**Protobuf 2.5.0**

##Usage

These can be indivdually applied using:

	node "node1.example.com" {
	  include bigtop_toolchain::jdk
	  include bigtop_toolchain::maven
	  include bigtop_toolchain::ant
	  include bigtop_toolchain::gradle
	  include bigtop_toolchain::protobuf
	  include bigtop_toolchain::packages
	  include bigtop_toolchain::env
	  include bigtop_toolchain::user
	}

Or installed as a whole with:

	node "node2.example.com" {
	  include bigtop_toolchain::installer
	}

It will create a user jenkins with the required environment variables set for
building BigTop:
```
MAVEN_HOME=/usr/local/maven
JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk.x86_64
ANT_HOME=/usr/local/ant
GRADLE_HOME=/usr/local/gradle
PATH=$MAVEN_HOME/bin:$ANT_HOME/bin:$FORREST_HOME/bin:$GRADLE_HOME/bin:$PATH
```

If you do not want to use a puppet master this module can be applied
standalone with a command such as:

	puppet apply --modulepath=<path_to_bigtop> -e "include bigtop_toolchain::installer"

where <path_to_bigtop> is the cloned git repo.

## Installation of Tools for Bigtop Deployment

This is a separated set of manifests that helps to setup tools for Bigtop deployment.
The usage is as below:

	puppet apply --modulepath=<path_to_bigtop> -e "include bigtop_toolchain::deployment_tools"

By applying the snippet, Vagrant will be installed(the Docker installation will be added soon).

## Optional development tools

This isn't a part of fundamental toolchain recipes as we are trying to contain the size of CI and dev-
images of docker containers.
As Groovy isn't required (yet!) for creation of a Bigtop stack, this environment is separated for now
In case you system doesn't have already installed version of Bigtop recommended Groovy environment,
you should be able to so easily by running

	puppet apply --modulepath=<path_to_bigtop> -e "include bigtop_toolchain::development_tools"

Potentially, we'll be adding more development tools in this manifest.

## Requirements

The Ant/Maven/Forrest/Gradle sources will be downloaded automatically. If you already
have them and do not want to download them again please copy the source
.tar.gz files into /usr/src.

## Support

License: Apache License, Version 2.0


text:
'use strict';

const expect = require('chai').expect;
const sinon = require('sinon');
const injectr = require('injectr');

describe('cli : domain : init-template', () => {
  let error;
  const initialise = stubs => cb => {
    const initTemplate = injectr(
      '../../dist/cli/domain/init-template/index.js',
      {
        'fs-extra': {
          ensureDir: stubs.fsExtraStub
        },
        path: { join: (...args) => args.join('/') },
        './install-template': stubs.installTemplateStub,
        '../../../utils/npm-utils': {
          init: stubs.npmStub
        },
        './scaffold': stubs.scaffoldStub
      }
    ).default;

    const options = {
      compiler: 'oc-template-react-compiler',
      componentName: 'new-component',
      componentPath: 'path/to/new-component',
      logger: { log: () => {} },
      templateType: 'oc-template-react'
    };

    initTemplate(options)
      .catch(err => (error = err))
      .finally(cb);
  };

  describe('happy path', () => {
    const fsExtraStub = sinon.stub().resolves('ok');
    const npmStub = sinon.stub().resolves('ok');
    const installTemplateStub = sinon.stub().resolves('ok');
    const scaffoldStub = sinon.stub().resolves('ok');

    beforeEach(
      initialise({
        fsExtraStub,
        npmStub,
        installTemplateStub,
        scaffoldStub
      })
    );

    it('should return no error', () => {
      expect(error).to.be.undefined;
    });

    it('should call ensureDir with correct params', () => {
      expect(fsExtraStub.args[0][0]).to.equal('path/to/new-component');
    });

    it('should call npm init with correct parameters', () => {
      expect(npmStub.args[0][0]).to.deep.equal({
        initPath: 'path/to/new-component',
        silent: true
      });
    });

    it('should call installTemplate with correct parameters', () => {
      const o = installTemplateStub.args[0][0];
      expect(o.compiler).to.equal('oc-template-react-compiler');
      expect(o.componentPath).to.equal('path/to/new-component');
      expect(o.logger.log).to.be.a('function');
      expect(o.templateType).to.equal('oc-template-react');
    });

    it('should call scaffold with correct parameters', () => {
      const o = scaffoldStub.args[0][0];
      expect(o.compiler).to.equal('oc-template-react-compiler');
      expect(o.compilerPath).to.equal(
        'path/to/new-component/node_modules/oc-template-react-compiler'
      );
      expect(o.componentName).to.equal('new-component');
      expect(o.componentPath).to.equal('path/to/new-component');
      expect(o.templateType).to.equal('oc-template-react');
    });
  });

  describe('when component folder creation fails', () => {
    beforeEach(
      initialise({
        fsExtraStub: sinon.stub().rejects(new Error('folder creation error'))
      })
    );

    it('should return an error', () => {
      expect(error.message).to.equal('folder creation error');
    });
  });

  describe('when npm init fails', () => {
    beforeEach(
      initialise({
        fsExtraStub: sinon.stub().resolves('ok'),
        npmStub: sinon.stub().rejects(new Error('npm init failed'))
      })
    );

    it('should return an error', () => {
      expect(error.message).to.equal('npm init failed');
    });
  });

  describe('when template compiler installation fails', () => {
    beforeEach(
      initialise({
        fsExtraStub: sinon.stub().resolves('ok'),
        npmStub: sinon.stub().resolves('ok'),
        installTemplateStub: sinon
          .stub()
          .rejects(new Error('npm install failed'))
      })
    );

    it('should return an error', () => {
      expect(error.message).to.equal('npm install failed');
    });
  });

  describe('when template compiler installation fails', () => {
    beforeEach(
      initialise({
        fsExtraStub: sinon.stub().resolves('ok'),
        npmStub: sinon.stub().resolves('ok'),
        installTemplateStub: sinon.stub().resolves('ok'),
        scaffoldStub: sinon.stub().rejects(new Error('scaffolding failed'))
      })
    );

    it('should return an error', () => {
      expect(error.message).to.equal('scaffolding failed');
    });
  });
});


text:
# include "decompr/iDecompressor.hpp"
# ifdef RPC_PROTOCOLS

namespace sV {

iDecompressor::iDecompressor( events::CompressionMethod comprMethod) :
    _comprMethod(comprMethod) {
}

iDecompressor::~iDecompressor() {
}

size_t iDecompressor::decompress_series(uint8_t * uncomprBuf,
            size_t lenUncomprBuf, uint8_t * comprBuf,
            size_t lenComprBuf) const {
    return _V_decompress_series( uncomprBuf, lenUncomprBuf, comprBuf,
                    lenComprBuf);
}

}  // namespace sV
# endif  // RPC_PROTOCOLS


text:
'use strict';
module.exports = function(server) {

};


text:
@interface FirstViewController ()

@end

@class LoginScreen;
LoginScreen *viewController;

@implementation FirstViewController

@synthesize userName;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [_logoutButton.layer setBorderWidth:1.0];
    [_logoutButton.layer setBorderColor:[[UIColor whiteColor] CGColor]];
    _logoutButton.layer.cornerRadius = 5;
    _logoutButton.clipsToBounds = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UIStatusBarStyle) preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)addBlurToView:(UIView *)view {
    UIView *blurView = nil;

    if([UIBlurEffect class]) { // iOS 8
        UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight];
        blurView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
        blurView.frame = view.frame;

    } else { // workaround for iOS 7
        blurView = [[UIToolbar alloc] initWithFrame:view.bounds];
    }

    [blurView setTranslatesAutoresizingMaskIntoConstraints:NO];

    [view addSubview:blurView];
    [view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[blurView]|" options:0 metrics:0 views:NSDictionaryOfVariableBindings(blurView)]];
    [view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[blurView]|" options:0 metrics:0 views:NSDictionaryOfVariableBindings(blurView)]];
}

@end


text:
package cn.elvea.platform.server.config;

import cn.elvea.platform.commons.constants.GlobalConstants;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;

/**
 * Config
 *
 * @author elvea
 * @since 0.0.1
 */
@Slf4j
@Configuration
@ComponentScan(basePackages = {
        "cn.elvea.platform.core"
})
@MapperScan(basePackages = {
        "cn.elvea.platform.core.**.mapper"
})
public class ApplicationConfiguration {

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasenames(
                "classpath:cn/elvea/platform/commons/messages/label",
                "classpath:cn/elvea/platform/commons/messages/validation",
                "classpath:org/springframework/security/messages",
                "classpath:messages/messages"
        );
        messageSource.setDefaultEncoding(GlobalConstants.ENCODING);
        messageSource.setUseCodeAsDefaultMessage(true);
        return messageSource;
    }

}


text:
repo=https://github.com/IntelOpenDesign/MakerNodeProjectSkeleton.git
start_time=`date +%s`
project_name=${1:-my_project}
echo creating project $project_name
git clone -v --progress $repo ./$project_name
pushd $project_name
rm -rf .git*
# npm install
popd
# The next lines clones directly on the device, but I don't think we need this...
#project_path=/home/root/projects
# target="root@${2:-clanton.local}"
# ssh $target git clone -v --progress $repo $project_path/$project_name
echo Completed in $(expr `date +%s` - $start_time) seconds.
exit 0


text:
[?php

/**
 * <?php echo $this->getModuleName() ?> module configuration.
 *
 * @package    ##PROJECT_NAME##
 * @subpackage <?php echo $this->getModuleName()."\n" ?>
 * @author     ##AUTHOR_NAME##
 * @version    SVN: $Id: configuration.php 24171 2009-11-19 16:37:50Z Kris.Wallsmith $
 */
abstract class Base<?php echo ucfirst($this->getModuleName()) ?>GeneratorConfiguration extends sfDoctrineRestGeneratorConfiguration
{
  public function getAdditionalParams()
  {
    return <?php echo $this->asPhp(isset($this->config['get']['additional_params']) ? $this->config['get']['additional_params'] : array()) ?>;
<?php unset($this->config['get']['additional_params']) ?>
  }

  public function getDefaultFormat()
  {
    return <?php echo $this->asPhp(isset($this->config['get']['default_format']) ? $this->config['get']['default_format'] : 'json') ?>;
<?php unset($this->config['get']['default_format']) ?>
  }

  public function getDisplay()
  {
    return <?php echo $this->asPhp(isset($this->config['get']['display']) ? $this->config['get']['display'] : array()) ?>;
<?php unset($this->config['get']['display']) ?>
  }

  public function getEmbedRelations()
  {
    return <?php echo $this->asPhp(isset($this->config['get']['embed_relations']) ? $this->config['get']['embed_relations'] : array()) ?>;
<?php unset($this->config['get']['embed_relations']) ?>
  }

  public function getEmbeddedRelationsDisplay()
  {
    $embedded_relations_display = <?php echo $this->asPhp(isset($this->config['get']['embedded_relations_display']) ? $this->config['get']['embedded_relations_display'] : array()) ?>;

    foreach ($embedded_relations_display as $relation_name => $displayed_fields)
    {
      $embedded_relations_display[$relation_name] = array_flip($displayed_fields);
    }

    return $embedded_relations_display;
<?php unset($this->config['get']['embedded_relations_display']) ?>
  }

  public function getEmbeddedRelationsHide()
  {
    $embedded_relations_hide = <?php echo $this->asPhp(isset($this->config['get']['embedded_relations_hide']) ? $this->config['get']['embedded_relations_hide'] : array()) ?>;

    foreach ($embedded_relations_hide as $relation_name => $hidden_fields)
    {
      $embedded_relations_hide[$relation_name] = array_flip($hidden_fields);
    }

    return $embedded_relations_hide;
<?php unset($this->config['get']['embedded_relations_hide']) ?>
  }

  public function getFormatsEnabled()
  {
    return <?php echo $this->asPhp(isset($this->config['default']['formats_enabled']) ? $this->config['default']['formats_enabled'] : array('json', 'xml', 'yaml')) ?>;
<?php unset($this->config['default']['formats_enabled']) ?>
  }

  public function getFormatsStrict()
  {
    return <?php echo $this->asPhp(isset($this->config['default']['formats_strict']) ? $this->config['default']['formats_strict'] : true) ?>;
<?php unset($this->config['default']['formats_strict']) ?>
  }

<?php include dirname(__FILE__).'/fieldsConfiguration.php' ?>

  public function getGlobalAdditionalFields()
  {
    return <?php echo $this->asPhp(isset($this->config['get']['global_additional_fields']) ? $this->config['get']['global_additional_fields'] : array()) ?>;
<?php unset($this->config['get']['global_additional_fields']) ?>
  }

  public function getHide()
  {
    return <?php echo $this->asPhp(isset($this->config['get']['hide']) ? $this->config['get']['hide'] : array()) ?>;
<?php unset($this->config['get']['hide']) ?>
  }

  public function getMaxItems()
  {
    return <?php echo $this->asPhp(isset($this->config['get']['max_items']) ? $this->config['get']['max_items'] : 0) ?>;
<?php unset($this->config['get']['max_items']) ?>
  }

  public function getObjectAdditionalFields()
  {
    return <?php echo $this->asPhp(isset($this->config['get']['object_additional_fields']) ? $this->config['get']['object_additional_fields'] : array()) ?>;
<?php unset($this->config['get']['object_additional_fields']) ?>
  }

  public function getSeparator()
  {
    return <?php echo $this->asPhp(isset($this->config['default']['separator']) ? $this->config['default']['separator'] : ',') ?>;
<?php unset($this->config['default']['separator']) ?>
  }

<?php include dirname(__FILE__).'/paginationConfiguration.php' ?>

<?php include dirname(__FILE__).'/sortConfiguration.php' ?>
}


text:
package log

import (
	"testing"

	"github.com/stretchr/testify/require"

	"github.com/vmware-tanzu/octant/pkg/event"
)

func TestStreamer_Close(t *testing.T) {
	f := newStubMessageListenerFactory()
	s := NewStreamer(f)

	s.Close()
	require.True(t, f.isCanceled)
}

func TestStreamer_Stream(t *testing.T) {
	tests := []struct {
		name string
	}{
		{
			name: "in general",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			message := Message{
				ID: "1",
			}

			want := event.Event{
				Type: event.EventTypeAppLogs,
				Data: []Message{message},
				Err:  nil,
			}

			f := newStubMessageListenerFactory()
			s := NewStreamer(f)

			readyCh := make(chan struct{}, 1)
			close(readyCh)

			ch, cancel := s.Stream(readyCh)

			done := make(chan struct{}, 1)
			var e event.Event
			go func() {
				defer close(done)
				e = <-ch
			}()

			f.ch <- message

			<-done
			require.Equal(t, want, e)
			cancel()

		})
	}
}

type stubMessageListenerFactory struct {
	ch         chan Message
	cancel     func()
	isCanceled bool
}

func newStubMessageListenerFactory() *stubMessageListenerFactory {
	f := &stubMessageListenerFactory{
		ch: make(chan Message, 1),
	}

	f.cancel = func() {
		if f.isCanceled {
			panic("already canceled")
		}
		f.isCanceled = true
	}

	return f
}

func (f *stubMessageListenerFactory) Listen() (<-chan Message, ListenCancelFunc) {
	return f.ch, f.cancel
}

var _ MessageListenerFactory = &stubMessageListenerFactory{}


text:
package app.model;

import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;

/**
 * The persistent class for the evento database table.
 *
 */
@Entity
@Table(name="evento", schema="futurodb")
@NamedQueries({
@NamedQuery(name="Evento.findAll", query="SELECT e FROM Evento e"),
@NamedQuery(name="Evento.findEventsByPersonIdAndStatus", query="SELECT e FROM Evento e WHERE e.pessoa.id = :personId AND e.status = :status"),
@NamedQuery(name="Evento.findEventsByPersonIdAndDate", query="SELECT e FROM Evento e WHERE e.pessoa.id = :personId AND date_format(e.dataHoraEntrada, '%d/%m/%Y') = date_format(:date, '%d/%m/%Y')")})

public class Evento implements Serializable {
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Long id;

	@Temporal(TemporalType.TIMESTAMP)
	private Date dataHoraEntrada;

	@Temporal(TemporalType.TIMESTAMP)
	private Date dataHoraSaida;

	private String status;

	//bi-directional many-to-one association to Pessoa
	@ManyToOne
	private Pessoa pessoa;

	public Evento() {
	}

	public Long getId() {
		return this.id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Date getDataHoraEntrada() {
		return this.dataHoraEntrada;
	}

	public void setDataHoraEntrada(Date dataHoraEntrada) {
		this.dataHoraEntrada = dataHoraEntrada;
	}

	public Date getDataHoraSaida() {
		return this.dataHoraSaida;
	}

	public void setDataHoraSaida(Date dataHoraSaida) {
		this.dataHoraSaida = dataHoraSaida;
	}

	public String getStatus() {
		return this.status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public Pessoa getPessoa() {
		return this.pessoa;
	}

	public void setPessoa(Pessoa pessoa) {
		this.pessoa = pessoa;
	}

}


text:
import * as React from 'react';
import { connect } from 'react-redux';
import State from '../state';

interface InfomationProps {
    title: string;
    currentTime: number;
    duration: number;
}

const mapStateToProps = ({ player }: State) => ({
    title: player.video.snippet.title,
    duration: player.duration,
    currentTime: player.currentTime
});

const mapDispatchToProps = () => ({});

function format(seconds: number): string {
    const h = Math.floor(seconds / 60 / 60);
    const mm = `00${Math.floor((seconds % 3600) / 60)}`.slice(-2);
    const ss = `00${Math.floor(seconds % 60)}`.slice(-2);
    return h ? `${h}:${mm}:${ss}` : `${mm}:${ss}`;
}

const Infomation = (props: InfomationProps) => (

{props.title}

        <progress value={props.currentTime} max={props.duration} />
        <time>{format(props.currentTime)} / {format(props.duration)}</time>

);

export default connect(mapStateToProps, mapDispatchToProps)(Infomation) as any;


text:
#include "config.h"
#include "web/WebHelperPluginImpl.h"

#include "core/html/HTMLObjectElement.h"
#include "core/loader/FrameLoader.h"
#include "core/loader/FrameLoaderClient.h"
#include "public/web/WebPlugin.h"
#include "web/WebLocalFrameImpl.h"
#include "web/WebPluginContainerImpl.h"

namespace blink {

DEFINE_TYPE_CASTS(WebHelperPluginImpl, WebHelperPlugin, plugin, true, true);

WebHelperPlugin* WebHelperPlugin::create(const WebString& pluginType, WebLocalFrame* frame)
{
    OwnPtr<WebHelperPlugin> plugin = adoptPtr<WebHelperPlugin>(new WebHelperPluginImpl());
    if (!toWebHelperPluginImpl(plugin.get())->initialize(pluginType, toWebLocalFrameImpl(frame)))
        return 0;
    return plugin.leakPtr();
}

WebHelperPluginImpl::WebHelperPluginImpl()
    : m_destructionTimer(this, &WebHelperPluginImpl::reallyDestroy)
{
}

WebHelperPluginImpl::~WebHelperPluginImpl()
{
}

bool WebHelperPluginImpl::initialize(const String& pluginType, WebLocalFrameImpl* frame)
{
    ASSERT(!m_objectElement && !m_pluginContainer);
    if (!frame->frame()->loader().client())
        return false;

    m_objectElement = HTMLObjectElement::create(*frame->frame()->document(), 0, false);
    Vector<String> attributeNames;
    Vector<String> attributeValues;
    ASSERT(frame->frame()->document()->url().isValid());
    m_pluginContainer = adoptRef(toWebPluginContainerImpl(frame->frame()->loader().client()->createPlugin(
        m_objectElement.get(),
        frame->frame()->document()->url(),
        attributeNames,
        attributeValues,
        pluginType,
        false,
        FrameLoaderClient::AllowDetachedPlugin).leakRef()));

    if (!m_pluginContainer)
        return false;

    // Getting a placeholder plugin is also failure, since it's not the plugin the caller needed.
    return !getPlugin()->isPlaceholder();
}

void WebHelperPluginImpl::reallyDestroy(Timer<WebHelperPluginImpl>*)
{
    delete this;
}

void WebHelperPluginImpl::destroy()
{
    // Defer deletion so we don't do too much work when called via stopActiveDOMObjects().
    // FIXME: It's not clear why we still need this. The original code held a Page and a
    // WebFrame, and destroying it would cause JavaScript triggered by frame detach to run,
    // which isn't allowed inside stopActiveDOMObjects(). Removing this causes one Chrome test
    // to fail with a timeout.
    m_destructionTimer.startOneShot(0, FROM_HERE);
}

WebPlugin* WebHelperPluginImpl::getPlugin()
{
    ASSERT(m_pluginContainer);
    ASSERT(m_pluginContainer->plugin());
    return m_pluginContainer->plugin();
}

} // namespace blink


text:
/**
 * Interface that describes a model's input and output variables.
 */
package edu.colorado.csdms.bmi;

/**
 * Methods that get information about input and output variables. These BMI
 * functions obtain information about a particular input or output variable.
 * They must accommodate any variable that is returned by the BMI functions
 * {@link BmiInfo#getInputVarNames()} or {@link BmiInfo#getOutputVarNames()}.
 */
public interface BmiVars {

  /**
   * Get the data type of the given variable.
   *
   * @param varName an input or output variable name, a CSDMS Standard Name
   * @return the variable type; e.g., <tt>int</tt>, <tt>double</tt>,
   *         <tt>String</tt>.
   */
  public String getVarType(String varName);

  /**
   * Get units of the given variable. Standard unit names, in lower case, should
   * be used, such as <tt>meters</tt> or <tt>seconds</tt>. Standard
   * abbreviations, like <tt>m</tt> for meters, are also supported. For
   * variables with compound units, each unit name is separated by a single
   * space, with exponents other than 1 placed immediately after the name, as in
   * <tt>m s-1</tt> for velocity, <tt>W m-2</tt> for an energy flux, or
   * <tt>km2</tt> for an area.
   *
   * @param varName an input or output variable name, a CSDMS Standard Name
   * @return the variable units
   */
  public String getVarUnits(String varName);

  /**
   * Gets the memory use for each array element in bytes.
   *
   * @param varName an input or output variable name, a CSDMS Standard Name
   * @return item size in bytes
   */
  public int getVarItemsize(String varName);

  /**
   * Gets the total size, in bytes, of the given variable.
   *
   * @param varName an input or output variable name, a CSDMS Standard Name
   * @return the size of the variable, counted in bytes.
   */
  public int getVarNbytes(String varName);

  /**
   * Gets the grid identifier for the given variable.
   *

   * Get <tt>varName</tt> from {@link BmiInfo#getInputVarNames()} or
   * {@link BmiInfo#getOutputVarNames()}
   *
   * @param varName an input or output variable name, a CSDMS Standard Name
   * @return the grid id
   */
  public int getVarGrid(String varName);

}


text:
var webpack = require('webpack'),
    path = require('path'),
    yargs = require('yargs');

var libraryName = 'PrismicDOM',
    fileName = 'prismic-dom',
    plugins = [],
    outputFile;

if (yargs.argv.p) {
  plugins.push(new webpack.optimize.UglifyJsPlugin({ minimize: true }));
  outputFile = fileName + '.min.js';
} else {
  outputFile = fileName + '.js';
}

var config = {
  entry: [
    __dirname + '/src/index.js'
  ],
  output: {
    path: path.join(__dirname, '/dist'),
    filename: outputFile,
    library: libraryName,
    libraryTarget: 'umd',
    umdNamedDefine: true
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader'
        }
      },
      {
        test: /\.json$/,
        use: 'json-loader'
      }
    ]
  },
  resolve: {
    alias:{
      "@root": path.resolve( __dirname, './src' )
    },
    extensions: ['.js']
  },
  plugins: plugins
};

module.exports = config;


text:
package com.blackbear.flatworm.annotations.beans;

import com.blackbear.flatworm.annotations.DataIdentity;
import com.blackbear.flatworm.annotations.FieldIdentity;
import com.blackbear.flatworm.annotations.ForProperty;
import com.blackbear.flatworm.annotations.Line;
import com.blackbear.flatworm.annotations.Record;
import com.blackbear.flatworm.annotations.RecordElement;
import com.blackbear.flatworm.annotations.Scriptlet;
import com.blackbear.flatworm.annotations.SegmentElement;

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

import lombok.Data;

/**
 * A more complex bean used to test the DefaultAnnotationConfigurationReaderImpl instance.
 *
 * @author Alan Henson
 */
@Data
@Record(
        name = "RecordBeanOne",
        identity = @DataIdentity(fieldIdentity = @FieldIdentity(
                ignoreCase = true,
                enabled = true,
                matchIdentities = {"TEST"}
        )),
        lines = @Line(
                delimiter = "|"
        ),
        afterReadRecordScript = @Scriptlet(
                scriptEngine = "nashorn",
                scriptFile = "before_after_script_test.js",
                functionName = "modifyRecord",
                enabled = true
        )
)
public class RecordBeanOne {
    @RecordElement(order = 1)
    private String valueOne;

    @RecordElement(order = 2)
    private String valueTwo;

    public RecordBeanOne() {
        this.beanSevens = new ArrayList<>();
    }

    @SegmentElement(
            order = 3,
            fieldIdentity = @FieldIdentity(ignoreCase = true, enabled = true, matchIdentities = {"RB2"}))
    private List<RecordBeanTwoChildToOne> beanTwoList = new ArrayList<>();

    @Line(delimiter = ",", forProperty = @ForProperty(enabled = true))
    private RecordBeanFiveChildToOne beanFive;

    @Line(
            forProperty = @ForProperty(
                    enabled = true,
                    identity = @DataIdentity(
                            fieldIdentity = @FieldIdentity(matchIdentities = {"RB7"}, enabled = true)
                    ))
    )
    private List<RecordBeanSevenChildToOne> beanSevens;

    @Line(
            delimiter = "|",
            forProperty = @ForProperty(
                    enabled = true,
                    identity = @DataIdentity(
                            fieldIdentity = @FieldIdentity(matchIdentities = {"RB9"}, enabled = true)
                    ))
    )
    private RecordBeanNineChildToOne beanNine;
}


text:
package org.openkilda.messaging.info.stats;

import org.openkilda.messaging.info.InfoData;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

import java.util.List;

/**
 * This class contains the port stats replies for a given switch.
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
        "message_type",
        "switch_id",
        "stats"})
public class PortStatsData extends InfoData {

    private static final long serialVersionUID = 1L;

    @JsonProperty("switch_id")
    private String switchId;

    @JsonProperty
    private List<PortStatsReply> stats;

    public PortStatsData(@JsonProperty("switch_id") String switchId,
                         @JsonProperty("stats") List<PortStatsReply> switchStats) {
        this.switchId = switchId;
        this.stats = switchStats;
    }

    public String getSwitchId() {
        return switchId;
    }

    public List<PortStatsReply> getStats() {
        return stats;
    }
}


text:
"use strict";
import gulp from 'gulp';
import babel from 'gulp-babel';
import runSequence from 'run-sequence';

const SOURCES = 'src/**/*.es6';

gulp.task('prepublish', ['babel']);

gulp.task('babel', () => {
  return gulp.src(SOURCES)
    .pipe(babel({ presets: ['es2015'] }))
    .pipe(gulp.dest('lib'));
});

gulp.task('watch', () => gulp.watch(SOURCES, ["babel"]));

gulp.task('default', (cb) => {
  runSequence("babel", "watch", cb);
});


text:
class style
{
    paint color_;               // (used for paint_type::currentColor)
    paint fill_;
    paint stroke_;
    length strokeWidth_;
    font_family fontFamily_;
    font_size fontSize_;

public:
    style();

    void set(
        std::unique_ptr<paint> const& color,
        std::unique_ptr<paint> const& fill,
        std::unique_ptr<paint> const& stroke,
        std::unique_ptr<length> const& strokeWidth,
        std::unique_ptr<font_family> const& fontFamily,
        std::unique_ptr<font_size> const& fontSize);

    ICanvasBrush^ fillBrush(ICanvasResourceCreator^ resourceCreator);
    ICanvasBrush^ strokeBrush(ICanvasResourceCreator^ resourceCreator);
    float stroke_width();
    CanvasTextFormat^ text_format();

private:
    template<typename T>
    void set(std::unique_ptr<T> const& value, T* field);
};

class inherited_style
{
    std::stack<style> stack_;

public:
    inherited_style();

    void push();
    void pop();
    style* current() { return &stack_.top(); }
};


text:
package org.springframework.social.yammer.api.impl;

import java.util.List;

import org.springframework.social.yammer.api.Group;
import org.springframework.social.yammer.api.GroupOperations;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * @author Morten Andersen-Gott
 *
 */
public class GroupTemplate extends AbstractYammerOperations implements GroupOperations {

	private RestTemplate restTemplate;

	public GroupTemplate(RestTemplate restTemplate) {
		this.restTemplate = restTemplate;
	}

	public List<Group> getGroups(int page, Character letter, String sortBy, boolean reverse) {
		MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
		params.set("page", String.valueOf(page));
		if(sortBy!=null){
			params.set("sort_by", sortBy);
		}
		params.set("reverse", String.valueOf(reverse));
		if(letter!=null){
			params.set("letter", String.valueOf(letter));
		}
		return restTemplate.getForObject(buildUri("groups.json", params), GroupList.class);
	}

	public Group getGroup(long groupId) {
		return restTemplate.getForObject(buildUri("groups/"+String.valueOf(groupId)+".json"), Group.class);
	}

	/* (non-Javadoc)
	 * @see org.springframework.social.yammer.api.GroupOperations#createGroup(java.lang.String, boolean)
	 */
	public void createGroup(String name, boolean isPrivate) {
		LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
		params.set("name",name);
		params.set("private", String.valueOf(isPrivate));
		restTemplate.postForEntity(buildUri("groups"), params, String.class);
	}

	/**
	 * Method returns 401 from Yammer, so it isn't visible in GroupOperations yet
	 * @param groupId
	 * @param name
	 * @param isPrivate
	 */
	public void updateGroup(long groupId, String name, boolean isPrivate) {
		LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
		params.set("name",name);
		params.set("private", String.valueOf(isPrivate));
		restTemplate.put(buildUri("groups/"+groupId), params);
	}

	public void joinGroup(long groupId){
		restTemplate.postForObject(buildUri("group_memberships.json", "group_id", String.valueOf(groupId)), null, String.class);
	}

	public void leaveGroup(long groupId){
		restTemplate.delete(buildUri("group_memberships.json", "group_id", String.valueOf(groupId)));
	}

}