text:
<?php
class Wxjssdk {

    private $appId;
    private $appSecret;
    private $wxjssdk_config_file_path;

    public function __construct(){
        $this->appId = 'wx1a060a56132dfff4';
        $this->appSecret = '38eefbff5e21a833292d49c18ee68935';
        $this->wxjssdk_config_file_path = '/alidata/www/api_llx';
    }

    public function wxgetSignPackage($appid='wx1a060a56132dfff4',$appsecret='38eefbff5e21a833292d49c18ee68935',$path='/alidata/www/api_llx') {
        $this->appId = $appid;
        $this->appSecret = $appsecret;
        $this->wxjssdk_config_file_path = $path;
        $jsapiTicket = $this->wxgetJsApiTicket();

        // 注意 URL 一定要动态获取,不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $url = $_SERVER['HTTP_REFERER'];
//        $url = "http://llx.51loveshow.com/home";
        $timestamp = time();
        $nonceStr = $this->wxcreateNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "appId"     => $this->appId,
            "nonceStr"  => $nonceStr,
            "timestamp" => (string)$timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }

    public function wxgetAccessToken() {
        // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
        $data = json_decode(file_get_contents($this->wxjssdk_config_file_path."/access_token.json"));
        if ($data->expire_time < time()) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";

            //测试
            //return $this->wxhttpGet($url);
            //测试

            $res = json_decode($this->wxhttpGet($url));
           /* $open=fopen('/var/wx.txt',"a" );
       fwrite($open,var_export($res,true));
       fclose($open);*/
            $access_token = $res->access_token;
            if ($access_token) {
                $data->expire_time = time() + 7000;
                $data->access_token = $access_token;
                $fp = fopen($this->wxjssdk_config_file_path."/access_token.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        } else {
            $access_token = $data->access_token;
        }
        return $access_token;
    }

    private function wxgetJsApiTicket() {
        // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
        $data = json_decode(file_get_contents($this->wxjssdk_config_file_path."/jsapi_ticket.json"));
        if ($data->expire_time < time()) {
            $accessToken = $this->wxgetAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($this->wxhttpGet($url));
            $ticket = $res->ticket;
            if ($ticket) {
                $data->expire_time = time() + 7000;
                $data->jsapi_ticket = $ticket;
                $fp = fopen($this->wxjssdk_config_file_path."/jsapi_ticket.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        } else {
            $ticket = $data->jsapi_ticket;
        }
        return $ticket;
    }

    private function wxcreateNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    private function wxhttpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }
}


text:
namespace FootballLeague.Tests.Data
{
    using FootballLeague.Models;

    public class TeamBuilder
    {
        private int? _id;

        private User _member1;

        private User _member2;

        private TeamBuilder() {}

        public static TeamBuilder Create()
        {
            return new TeamBuilder();
        }

        public TeamBuilder WithId(int id)
        {
            _id = id;
            return this;
        }

        public TeamBuilder WithMember(User member)
        {
            if (_member1 == null)
                _member1 = member;
            else
                _member2 = member;

            return this;
        }

        public Team Build()
        {
            var team = new Team();
            if (_id.HasValue) team.Id = _id.Value;

            if (_member1 != null) team.SetMember(_member1);

            if (_member2 != null) team.SetMember(_member2);

            return team;
        }
    }

    public static class TeamData
    {
        public static Team TeamWithFerko
        {
            get
            {
                var team = TeamBuilder.Create().WithId(1).WithMember(Users.Ferko).Build();

                return team;
            }
        }

        public static Team TeamWithFerkoJurko
        {
            get
            {
                var team = TeamBuilder.Create().WithId(2).WithMember(Users.Ferko).WithMember(Users.Jurko).Build();

                return team;
            }
        }

        public static Team TeamWithDanoPeto
        {
            get
            {
                var team = TeamBuilder.Create().WithId(3).WithMember(Users.Dano).WithMember(Users.Peto).Build();

                return team;
            }
        }

        public static Team EmptyTeam
        {
            get
            {
                return TeamBuilder.Create().WithId(4).Build();
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * This file is part of Beads. See http://www.beadsproject.net for all information.
 */
package net.beadsproject.beads.ugens;

import net.beadsproject.beads.core.AudioContext;
import net.beadsproject.beads.core.UGenChain;
import net.beadsproject.beads.data.DataBead;
import net.beadsproject.beads.data.DataBeadReceiver;

/**
 * A basic reverb unit with adjustable room size, high-frequency damping, and
 * early reflections and late reverb levels. If specified, creates a
 * de-correlated multi-channel effect.
 *
 * @beads.category effect
 * @author Benito Crawford
 * @version 0.9.5
 */
public class Reverb extends UGenChain implements DataBeadReceiver {
	private float size, damping, earlyLevel, lateLevel;
	private Gain earlyGain, lateGain;
	private AllpassFilter eAPF1, eAPF2, eAPF3, lAPF1, lAPF2, lAPF3, lAPF4;
	private AllpassFilter[] apfOuts;
	private float[] outDelayScale;
	private OnePoleFilter lpf, src;
	private RandomPWM delayModulator;
	private float lateDelay1, lateDelay2, lateDelay3, lateDelay4;
	private float sampsPerMS;
	private TapIn earlyTapIn;
	private TapOut earlyTapOut;

	/**
	 * Constructor for a reverb unit with one output channel.
	 *
	 * @param context
	 *            The audio context.
	 */
	public Reverb(AudioContext context) {
		this(context, 1);
	}

	/**
	 * Constructor for a reverb unit with the specified number of output
	 * channels.
	 *
	 * @param context
	 *            The audio context.
	 * @param outChannels
	 *            The number of output channels.
	 */
	public Reverb(AudioContext context, int outChannels) {
		super(context, 1, outChannels);

		sampsPerMS = (float) context.msToSamples(1);

		// start with a minor low-pass filter.
		src = new OnePoleFilter(context, 4000);

		// Early reflections unit: start with a delay, then 3 allpass filters in
		// series. Takes input from the source filter src.
		earlyTapIn = new TapIn(context, 125);
		earlyTapOut = new TapOut(context, earlyTapIn, 10);
		eAPF1 = new AllpassFilter(context, (int) (12.812 * sampsPerMS), 113,
				.3f);
		eAPF2 = new AllpassFilter(context, (int) (12.812 * sampsPerMS * 3),
				337, .4f);
		eAPF3 = new AllpassFilter(context, (int) (12.812 * sampsPerMS * 9.4),
				1051, .5f);
		Gain earlyGainEcho = new Gain(context, 1, -.3f);
		// The early reflections output gets fed back in at the top...

		// Late reverb unit: 4 allpass filters in series.
		// Takes input from the source filter src, the early reflections output
		// earlyGainEcho, and an echo of itself
		lAPF1 = new AllpassFilter(context, (int) (140f * sampsPerMS), 19, .72f);
		lAPF2 = new AllpassFilter(context, (int) (140f * sampsPerMS), 23, .7f);
		lAPF3 = new AllpassFilter(context, (int) (140f * sampsPerMS), 29, .65f);
		lAPF4 = new AllpassFilter(context, (int) (140f * sampsPerMS), 37, .6f);
		lpf = new OnePoleFilter(context, 1000);
		TapIn lateTapIn = new TapIn(context, 1000);
		TapOut lateTapOut1 = new TapOut(context, lateTapIn, 10);
		TapOut lateTapOut2 = new TapOut(context, lateTapIn, 31.17f);
		Gain lateGainEcho = new Gain(context, 1, -.25f);
		// double tap - this gets put back in at the top of the filter series.

		// Collect the early reflections and the late reverb here
		earlyGain = new Gain(context, 1, 1);
		lateGain = new Gain(context, 1, 1);
		Gain collectedGain = new Gain(context, 1, 1);

		// used to modulate the delay times, to help reduce ringing.
		delayModulator = new RandomPWM(context, RandomPWM.RAMPED_NOISE, 4000,
				15000, 1);

		drawFromChainInput(src);
		earlyTapIn.addInput(src);
		earlyTapIn.addInput(earlyGain);
		eAPF1.addInput(earlyTapOut);
		eAPF2.addInput(eAPF1);
		eAPF3.addInput(eAPF2);
		earlyGainEcho.addInput(eAPF3);
		earlyGain.addInput(earlyGainEcho);
		lAPF1.addInput(earlyGainEcho);
		lAPF1.addInput(lateGainEcho);
		lAPF1.addInput(src);
		lAPF2.addInput(lAPF1);
		lAPF3.addInput(lAPF2);
		lAPF4.addInput(lAPF3);
		lpf.addInput(lAPF4);
		lateTapIn.addInput(lpf);
		lateGainEcho.addInput(lateTapOut1);
		lateGainEcho.addInput(lateTapOut2);
		lateGain.addInput(lateGainEcho);
		collectedGain.addInput(earlyGain);
		collectedGain.addInput(lateGain);

		apfOuts = new AllpassFilter[outChannels];
		outDelayScale = new float[outChannels];
		for (int i = 0; i < outChannels; i++) {
			float g = .3f + ((float) i / (i + 1)) * .1f + (float) Math.sin(i)
					* .05f;
			outDelayScale[i] = (3f * i + 5) / (5f * i + 5);
			apfOuts[i] = new AllpassFilter(context, (int) (60f * sampsPerMS),
					20, g);
			apfOuts[i].addInput(collectedGain);
			addToChainOutput(i, apfOuts[i]);
		}

		setSize(.5f).setDamping(.7f).setEarlyReflectionsLevel(1)
				.setLateReverbLevel(1);
	}

	@Override
	protected void preFrame() {
		delayModulator.update();
		int m = (int) (delayModulator.getValue() * .3f * sampsPerMS);
		lAPF1.setDelay((int) lateDelay1 - m);
		lAPF2.setDelay((int) lateDelay2 + m);
		lAPF3.setDelay((int) lateDelay3 - m);
		lAPF4.setDelay((int) lateDelay4 + m);
	}

	/**
	 * Gets the "room size".
	 *
	 * @return The "room size", between 0 and 1.
	 */
	public float getSize() {
		return size;
	}

	/**
	 * Sets the "room size". Valid value range from 0 to 1 (.5 is the default).
	 * The larger the value, the longer the decay time.
	 *
	 * @param size
	 *            The "room size".
	 * @return This reverb instance.
	 */
	public Reverb setSize(float size) {
		if (size > 1)
			size = 1;
		else if (size < 0.01)
			size = .01f;
		this.size = size;
		lateDelay1 = 86.0f * size * sampsPerMS;
		lateDelay2 = lateDelay1 * 1.16f;
		lateDelay3 = lateDelay2 * 1.16f;
		lateDelay4 = lateDelay3 * 1.16f;
		earlyTapOut.setDelay(60f * size);

		float d = 12.812f * sampsPerMS * size;
		eAPF1.setDelay((int) d);
		eAPF2.setDelay((int) (d * 3 - 2));
		eAPF3.setDelay((int) (d * 9.3 + 1));

		d = 60f * sampsPerMS * size;
		for (int i = 0; i < this.outs; i++) {
			apfOuts[i].setDelay((int) (d * outDelayScale[i]));
		}
		return this;
	}

	/**
	 * Gets the damping factor.
	 *
	 * @return The damping factor, between 0 and 1.
	 */
	public float getDamping() {
		return damping;
	}

	/**
	 * Sets the damping factor. Valid values range from 0 to 1 (.7 is the
	 * default). Higher values filter out higher frequencies faster.
	 *
	 * @param damping
	 *            The damping factor.
	 * @return This reverb instance.
	 */
	public Reverb setDamping(float damping) {
		if (damping < 0)
			damping = 0;
		else if (damping > 1)
			damping = 1;
		this.damping = damping;

		float f = 1f - (float) Math.sqrt(damping);

		src.setFrequency(f * 10000 + 250);
		lpf.setFrequency(f * 8000 + 200);

		return this;
	}

	/**
	 * Gets the early reflections level.
	 *
	 * @return The early reflections level.
	 */
	public float getEarlyReflectionsLevel() {
		return earlyLevel;
	}

	/**
	 * Sets the early reflections level (the amount of early reflections heard
	 * in the output). The default value is 1.
	 *
	 * @param earlyLevel
	 *            The early reflections level.
	 * @return This reverb instance.
	 */
	public Reverb setEarlyReflectionsLevel(float earlyLevel) {
		this.earlyLevel = earlyLevel;
		earlyGain.setGain(earlyLevel);
		return this;
	}

	/**
	 * Gets the late reverb level.
	 *
	 * @return The late reverb level.
	 */
	public float getLateReverbLevel() {
		return lateLevel;
	}

	/**
	 * Sets the late reverb level (the amount of late reverb heard in the
	 * output). The default value is 1.
	 *
	 * @param lateLevel
	 *            The late reverb level.
	 * @return This reverb instance.
	 */
	public Reverb setLateReverbLevel(float lateLevel) {
		this.lateLevel = lateLevel;
		lateGain.setGain(lateLevel);
		return this;
	}

	/**
	 * Sets the reverb parameters with a DataBead, using values stored in the
	 * keys "damping", "roomSize", "earlyReflectionsLevel", and
	 * "lateReverbLevel".
	 *
	 * @param db
	 *            The parameter DataBead.
	 */
	public DataBeadReceiver sendData(DataBead db) {
		if (db != null) {
			setDamping(db.getFloat("damping", damping));
			setSize(db.getFloat("roomSize", size));
			setEarlyReflectionsLevel(db.getFloat("earlyReflectionsLevel",
					earlyLevel));
			setLateReverbLevel(db.getFloat("lateReverbLevel", lateLevel));

		}
		return this;
	}

	/**
	 * Gets a new DataBead filled with parameter values stored in the keys
	 * "damping", "roomSize", "earlyReflectionsLevel", and "lateReverbLevel".
	 *
	 * @return The parameter DataBead.
	 */
	public DataBead getParams() {
		DataBead db = new DataBead();
		db.put("damping", damping);
		db.put("roomSize", size);
		db.put("earlyReflectionsLevel", earlyLevel);
		db.put("lateReverbLevel", lateLevel);
		return db;
	}

}


text:
export LD_LIBRARY_PATH=`pwd`/build/install/ospray/lib:$LD_LIBRARY_PATH
export DYLD_LIBRARY_PATH=`pwd`/build/install/ospray/lib:$DYLD_LIBRARY_PATH
export PATH=`pwd`/build/install/ospray/bin:$PATH

echo -e "\n\nRunning 'ospTutorial'..."
ospTutorial || exit 2

echo -e "\n\nRunning 'ospTutorialCpp'..."
ospTutorialCpp || exit 2

echo -e "\n\nRunning 'ospTutorialAsync'..."
ospTutorialAsync || exit 2

if [[ -x `pwd`/build/install/ospray/bin/ospTutorialGLM ]] ; then
  echo -e "\n\nRunning 'ospTutorialGLM'..."
  ospTutorialGLM || exit 2
fi


text:
<style>
  .pad {
    width: 95%;
    height: 45%;
    margin: 10px;
    padding: 10px;
    font-size: 20px;
    font-family: monaco;
    background-repeat: no-repeat;
    border-radius: 10px;
  }
  body {
    background-color: #ccc;
  }
</style>
<textarea id='pad1' class="pad" autofocus>...</textarea>

<textarea id='pad2' class="pad">...</textarea>
<script src="channel/bcsocket.js"></script>
<script src="text.js"></script>
<script src="share.uncompressed.js"></script>
<script>

var s = new BCSocket(null, {reconnect: true});

var sjs = new window.sharejs.Connection(s);

var doc = sjs.get('users', 'seph');
console.log(doc);
doc.subscribe();

doc.whenReady(function () {
  if (!doc.type) doc.create('text');

  if (doc.type && doc.type.name === 'text')
    doc.attachTextarea(pad1);
    doc.attachTextarea(pad2);
});

</script>


text:
package com.communote.server.core.user.note;

import com.communote.server.core.common.caching.AbstractCacheElementProvider;
import com.communote.server.core.vo.user.note.UserNoteEntityTO;

/**
 * Element provider for getting {@link UserNoteEntityTO}
 *
 * @author Communote GmbH - http://www.communote.com/
 *
 */
public class UserNoteTOElementProvider extends
        AbstractCacheElementProvider<UserNoteTOCacheKey, UserNoteEntityTO> {

    private UserNoteEntityManagement userNoteEntityManagement;

    /**
     *
     * @param userNoteEntityManagement
     *            the management is used for loading the entity.
     */
    public UserNoteTOElementProvider(UserNoteEntityManagement userNoteEntityManagement) {
        super("Object", 3600);
        if (userNoteEntityManagement == null) {
            throw new IllegalArgumentException("userNoteEntityDao cannot be null.");
        }
        this.userNoteEntityManagement = userNoteEntityManagement;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UserNoteEntityTO load(UserNoteTOCacheKey key) {
        return this.userNoteEntityManagement.findByUserIdNoteId(key.getUserId(),
                key.getNoteId());
    }
}


text:
package io.hekate.spring.boot.coordination;

import io.hekate.coordinate.CoordinationContext;
import io.hekate.coordinate.CoordinationHandler;
import io.hekate.coordinate.CoordinationProcessConfig;
import io.hekate.coordinate.CoordinationRequest;
import io.hekate.coordinate.CoordinationService;
import io.hekate.coordinate.CoordinatorContext;
import io.hekate.spring.boot.HekateAutoConfigurerTestBase;
import io.hekate.spring.boot.HekateTestConfigBase;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;

import static org.junit.Assert.assertNotNull;

public class HekateCoordinationServiceConfigurerTest extends HekateAutoConfigurerTestBase {
    @EnableAutoConfiguration
    public static class CoordinationTestConfig extends HekateTestConfigBase {
        @Autowired
        private CoordinationService coordinationService;

        @Bean
        public CoordinationProcessConfig process1() {
            return new CoordinationProcessConfig().withName("test.process").withHandler(new CoordinationHandler() {
                @Override
                public void prepare(CoordinationContext ctx) {
                    // No-op.
                }

                @Override
                public void coordinate(CoordinatorContext ctx) {
                    ctx.complete();
                }

                @Override
                public void process(CoordinationRequest request, CoordinationContext ctx) {
                    // No-op.
                }
            });
        }
    }

    @Test
    public void testProcesses() throws Exception {
        registerAndRefresh(CoordinationTestConfig.class);

        assertNotNull(get("coordinationService", CoordinationService.class));
        assertNotNull(get(CoordinationTestConfig.class).coordinationService);
        assertNotNull(getNode().coordination().process("test.process").future().get());
    }
}


text:
define(['./_baseClone', './_baseMatchesProperty'], function(baseClone, baseMatchesProperty) {

  /**
   * Creates a function that performs a partial deep comparison between the
   * value at `path` of a given object to `srcValue`, returning `true` if the
   * object value is equivalent, else `false`.
   *
   * **Note:** Partial comparisons will match empty array and empty object
   * `srcValue` values against any array or object value, respectively. See
   * `_.isEqual` for a list of supported value comparisons.
   *
   * @static
   * @memberOf _
   * @since 3.2.0
   * @category Util
   * @param {Array|string} path The path of the property to get.
   * @param {*} srcValue The value to match.
   * @returns {Function} Returns the new spec function.
   * @example
   *
   * var objects = [
   *   { 'a': 1, 'b': 2, 'c': 3 },
   *   { 'a': 4, 'b': 5, 'c': 6 }
   * ];
   *
   * _.find(objects, _.matchesProperty('a', 4));
   * // => { 'a': 4, 'b': 5, 'c': 6 }
   */
  function matchesProperty(path, srcValue) {
    return baseMatchesProperty(path, baseClone(srcValue, true));
  }

  return matchesProperty;
});


text:
<?php

namespace Oro\Bundle\WorkflowBundle\Tests\Unit\Configuration;

use Oro\Bundle\ActionBundle\Model\Attribute;
use Oro\Bundle\ActionBundle\Model\AttributeManager;
use Oro\Bundle\ActionBundle\Provider\CurrentApplicationProviderInterface;
use Oro\Bundle\WorkflowBundle\Configuration\WorkflowConfiguration;
use Oro\Bundle\WorkflowBundle\Configuration\WorkflowDefinitionBuilderExtensionInterface;
use Oro\Bundle\WorkflowBundle\Configuration\WorkflowDefinitionConfigurationBuilder;
use Oro\Bundle\WorkflowBundle\Entity\WorkflowDefinition;
use Oro\Bundle\WorkflowBundle\Entity\WorkflowEntityAcl;
use Oro\Bundle\WorkflowBundle\Model\Step;
use Oro\Bundle\WorkflowBundle\Model\StepManager;
use Oro\Bundle\WorkflowBundle\Model\Transition;
use Oro\Bundle\WorkflowBundle\Model\TransitionManager;
use Oro\Bundle\WorkflowBundle\Model\Workflow;
use Oro\Bundle\WorkflowBundle\Model\WorkflowAssembler;
use Oro\Bundle\WorkflowBundle\Resolver\TransitionOptionsResolver;

class WorkflowDefinitionConfigurationBuilderTest extends \PHPUnit\Framework\TestCase
{
    /** @var WorkflowAssembler|\PHPUnit\Framework\MockObject\MockObject */
    private $workflowAssembler;

    protected function setUp()
    {
        $this->workflowAssembler = $this->createMock(WorkflowAssembler::class);
    }

    /**
     * @param WorkflowDefinitionBuilderExtensionInterface[] $extensions
     *
     * @return WorkflowDefinitionConfigurationBuilder
     */
    private function getWorkflowDefinitionConfigurationBuilder(array $extensions = [])
    {
        return new WorkflowDefinitionConfigurationBuilder($this->workflowAssembler, $extensions);
    }

    /**
     * @param WorkflowDefinition $definition
     * @return array
     */
    private function getDataAsArray(WorkflowDefinition $definition)
    {
        $data = [
            'name' => $definition->getName(),
            'label' => $definition->getLabel(),
            'entity' => $definition->getRelatedEntity(),
            'defaults' => ['active' => $definition->isActive()],
            'priority' => $definition->getPriority(),
            'configuration' => $definition->getConfiguration(),
        ];

        if ($definition->getStartStep()) {
            $data['start_step'] = $definition->getStartStep()->getName();
        }

        return $data;
    }

    /**
     * @param array $inputData
     * @param array $expectedData
     * @param array $expectedAcls
     * @dataProvider buildFromConfigurationDataProvider
     */
    public function testBuildFromConfiguration(array $inputData, array $expectedData, array $expectedAcls = [])
    {
        $workflowConfiguration = current($inputData);
        $definition = new WorkflowDefinition();
        $definition->setConfiguration($workflowConfiguration);

        $stepManager = new StepManager($this->getSteps($workflowConfiguration));
        $attributeManager = new AttributeManager($this->getAttributes($workflowConfiguration));
        $transitionManager = new TransitionManager($this->getTransitions($workflowConfiguration));

        $activeGroups = [];
        $recordGroups = [];
        $applications = [CurrentApplicationProviderInterface::DEFAULT_APPLICATION];
        if (!empty($workflowConfiguration[WorkflowConfiguration::NODE_EXCLUSIVE_ACTIVE_GROUPS])) {
            $activeGroups = array_map(
                'strtolower',
                $workflowConfiguration[WorkflowConfiguration::NODE_EXCLUSIVE_ACTIVE_GROUPS]
            );
        }
        if (!empty($workflowConfiguration[WorkflowConfiguration::NODE_EXCLUSIVE_RECORD_GROUPS])) {
            $recordGroups = array_map(
                'strtolower',
                $workflowConfiguration[WorkflowConfiguration::NODE_EXCLUSIVE_RECORD_GROUPS]
            );
        }
        if (!empty($workflowConfiguration[WorkflowConfiguration::NODE_APPLICATIONS])) {
            $applications = array_map(
                'strtolower',
                $workflowConfiguration[WorkflowConfiguration::NODE_APPLICATIONS]
            );
        }

        /** @var Workflow|\PHPUnit\Framework\MockObject\MockObject $workflow */
        $workflow = $this->getMockBuilder(Workflow::class)
            ->disableOriginalConstructor()
            ->setMethods(['getStepManager', 'getAttributeManager', 'getRestrictions', 'getTransitionManager'])
            ->getMock();
        $workflow->expects($this->any())
            ->method('getStepManager')
            ->will($this->returnValue($stepManager));
        $workflow->expects($this->any())
            ->method('getAttributeManager')
            ->will($this->returnValue($attributeManager));
        $workflow->expects($this->once())
            ->method('getTransitionManager')
            ->willReturn($transitionManager);
        $workflow->expects($this->any())
            ->method('getRestrictions')
            ->will($this->returnValue([]));
        $workflow->setDefinition($definition);

        $this->workflowAssembler->expects($this->once())
            ->method('assemble')
            ->with($this->isInstanceOf('Oro\Bundle\WorkflowBundle\Entity\WorkflowDefinition'), false)
            ->willReturn($workflow);

        $builder = $this->getWorkflowDefinitionConfigurationBuilder();
        $workflowDefinitions = $builder->buildFromConfiguration($inputData);
        $this->assertCount(1, $workflowDefinitions);

        /** @var WorkflowDefinition $workflowDefinition */
        $workflowDefinition = current($workflowDefinitions);
        $this->assertEquals($expectedData, $this->getDataAsArray($workflowDefinition));
        $this->assertEquals($workflowDefinition->getExclusiveActiveGroups(), $activeGroups);
        $this->assertEquals($workflowDefinition->getExclusiveRecordGroups(), $recordGroups);
        $this->assertEquals($workflowDefinition->getApplications(), $applications);

        $actualAcls = $workflowDefinition->getEntityAcls()->toArray();
        $this->assertSameSize($expectedAcls, $actualAcls);
        foreach ($expectedAcls as $expectedAcl) {
            /** @var WorkflowEntityAcl $actualAcl */
            $actualAcl = array_shift($actualAcls);
            $this->assertEquals($expectedAcl['step'], $actualAcl->getStep()->getName());
            $this->assertEquals($expectedAcl['attribute'], $actualAcl->getAttribute());
            $this->assertEquals($expectedAcl['permissions']['UPDATE'], $actualAcl->isUpdatable());
            $this->assertEquals($expectedAcl['permissions']['DELETE'], $actualAcl->isDeletable());
        }
    }

    /**
     * @return array
     *
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function buildFromConfigurationDataProvider()
    {
        $minimumConfiguration = [
            'label' => 'Test Workflow',
            'entity' => 'My\Entity',
            'defaults' => ['active' => false],
            'priority' => 0,
        ];

        $maximumConfiguration = [
            'label' => 'Test Workflow',
            'is_system' => true,
            'entity' => 'My\Entity',
            'defaults' => ['active' => false],
            'priority' => 1,
            'start_step' => 'test_step',
            'entity_attribute' => 'my_entity',
            'steps_display_ordered' => true,
            'scopes' => [
                ['scope1' => 'value1'],
            ],
            WorkflowConfiguration::NODE_APPLICATIONS => [
                CurrentApplicationProviderInterface::DEFAULT_APPLICATION,
                'Some Extra Application'
            ],
            WorkflowConfiguration::NODE_EXCLUSIVE_ACTIVE_GROUPS => [
                'active_group1',
                'active_group2',
            ],
            WorkflowConfiguration::NODE_EXCLUSIVE_RECORD_GROUPS => [
                'record_group1',
                'record_group2',
            ],
            WorkflowConfiguration::NODE_STEPS => [
                [
                    'name' => 'first',
                    'entity_acl' => [
                        'entity_attribute' => [
                            'update' => false,
                        ]
                    ],
                    'is_final' => true,
                ],
            ],
            WorkflowConfiguration::NODE_ATTRIBUTES => [
                [
                    'name' => 'string_attribute',
                    'type' => 'string',
                ],
                [
                    'name' => 'entity_attribute',
                    'type' => 'entity',
                    'entity_acl' => ['delete' => false],
                    'options' => ['class' => 'TestClass']
                ],
            ],
            WorkflowConfiguration::NODE_TRANSITIONS => [
                [
                    'name' => 'transit1',
                    WorkflowConfiguration::NODE_INIT_ENTITIES => ['entity1', 'entity2'],
                    WorkflowConfiguration::NODE_INIT_ROUTES => ['route1', 'route2'],
                    WorkflowConfiguration::NODE_INIT_DATAGRIDS => ['datagrid1', 'datagrid2'],
                    'is_start' => true,
                ],
            ],
        ];

        return [
            'minimum configuration' => [
                'inputData' => [
                    'test_workflow' => $minimumConfiguration,
                ],
                'expectedData' => [
                    'name' => 'test_workflow',
                    'label' => 'Test Workflow',
                    'entity' => 'My\Entity',
                    'defaults' => ['active' => false],
                    'priority' => 0,
                    'configuration' => $this->filterConfiguration($minimumConfiguration),
                ],
            ],
            'maximum configuration' => [
                'inputData' => [
                    'test_workflow' => $maximumConfiguration,
                ],
                'expectedData' => [
                    'name' => 'test_workflow',
                    'label' => 'Test Workflow',
                    'start_step' => 'test_step',
                    'entity' => 'My\Entity',
                    'defaults' => ['active' => false],
                    'priority' => 1,
                    'configuration' => $this->filterConfiguration(
                        array_merge(
                            $maximumConfiguration,
                            [
                                WorkflowConfiguration::NODE_INIT_ENTITIES => [
                                    'entity1' => ['transit1'],
                                    'entity2' => ['transit1'],
                                ],
                                WorkflowConfiguration::NODE_INIT_ROUTES => [
                                    'route1' => ['transit1'],
                                    'route2' => ['transit1'],
                                ],
                                WorkflowConfiguration::NODE_INIT_DATAGRIDS => [
                                    'datagrid1' => ['transit1'],
                                    'datagrid2' => ['transit1'],
                                ],
                            ]
                        )
                    ),
                ],
                'expected_acls' => [
                    [
                        'step' => 'first',
                        'attribute' => 'entity_attribute',
                        'permissions' => ['UPDATE' => false, 'DELETE' => false],
                    ],
                    [
                        'step' => 'test_step',
                        'attribute' => 'entity_attribute',
                        'permissions' => ['UPDATE' => true, 'DELETE' => false],
                    ],
                ],
            ],
        ];
    }

    /**
     * @param array $configuration
     * @return array
     */
    private function filterConfiguration(array $configuration)
    {
        $configurationKeys = [
            WorkflowDefinition::CONFIG_SCOPES,
            WorkflowConfiguration::NODE_STEPS,
            WorkflowConfiguration::NODE_ATTRIBUTES,
            WorkflowConfiguration::NODE_TRANSITIONS,
            WorkflowConfiguration::NODE_TRANSITION_DEFINITIONS,
            WorkflowConfiguration::NODE_INIT_ENTITIES,
            WorkflowConfiguration::NODE_INIT_ROUTES,
            WorkflowConfiguration::NODE_INIT_DATAGRIDS,
        ];

        return array_intersect_key($configuration, array_flip($configurationKeys));
    }

    /**
     * @expectedException \Oro\Bundle\WorkflowBundle\Exception\MissedRequiredOptionException
     * @expectedExceptionMessage The "entity" configuration option is required.
     */
    public function testBuildFromConfigurationWhenNoEntityInConfiguration()
    {
        $builder = $this->getWorkflowDefinitionConfigurationBuilder();
        $builder->buildFromConfiguration(['test_workflow' => ['label' => 'My Entity']]);
    }

    public function testWithExtensions()
    {
        $firstExtension = $this->createMock(WorkflowDefinitionBuilderExtensionInterface::class);
        $interruptionExtension = $this->createMock(WorkflowDefinitionBuilderExtensionInterface::class);

        $builder = $this->getWorkflowDefinitionConfigurationBuilder([
            $firstExtension,
            $interruptionExtension
        ]);

        $name = 'workflow_name';
        $configuration = ['label' => 'Label'];

        $modifiedConfiguration = ['label' => 'Label Modified'];

        $firstExtension->expects($this->once())
            ->method('prepare')
            ->with($name, $configuration)
            ->willReturn($modifiedConfiguration);

        $interruptionExtension->expects($this->once())
            ->method('prepare')
            ->with($name, $modifiedConfiguration)
            ->willThrowException(new \Exception('interrupted by extension'));

        $this->expectException(\Exception::class);
        $this->expectExceptionMessage('interrupted by extension');
        $builder->buildOneFromConfiguration($name, $configuration);
    }

    /**
     * @param array $configuration
     *
     * @return Step[]
     */
    private function getSteps(array $configuration)
    {
        $steps = [];
        if (!empty($configuration[WorkflowConfiguration::NODE_STEPS])) {
            foreach ($configuration[WorkflowConfiguration::NODE_STEPS] as $stepData) {
                $step = new Step();
                $step->setName($stepData['name']);
                if (!empty($stepData['entity_acl'])) {
                    $step->setEntityAcls($stepData['entity_acl']);
                }
                if (array_key_exists('is_final', $stepData)) {
                    $step->setFinal($stepData['is_final']);
                }
                $steps[] = $step;
            }
        }
        if (!empty($configuration['start_step'])) {
            $step = new Step();
            $step->setName($configuration['start_step']);
            $steps[] = $step;
        }

        return $steps;
    }

    /**
     * @param array $configuration
     *
     * @return Attribute[]
     */
    private function getAttributes(array $configuration)
    {
        $attributes = [];
        if (!empty($configuration[WorkflowConfiguration::NODE_ATTRIBUTES])) {
            foreach ($configuration[WorkflowConfiguration::NODE_ATTRIBUTES] as $attributeData) {
                $attribute = new Attribute();
                $attribute->setName($attributeData['name'])
                    ->setType($attributeData['type']);
                if (!empty($attributeData['entity_acl'])) {
                    $attribute->setEntityAcl($attributeData['entity_acl']);
                }
                $attributes[] = $attribute;
            }
        }

        return $attributes;
    }

    /**
     * @param array $configuration
     *
     * @return Transition[]
     */
    private function getTransitions(array $configuration)
    {
        $transitions = [];
        if (!empty($configuration[WorkflowConfiguration::NODE_TRANSITIONS])) {
            foreach ($configuration[WorkflowConfiguration::NODE_TRANSITIONS] as $transitionData) {
                $transition = new Transition($this->createMock(TransitionOptionsResolver::class));
                $transition
                    ->setStart($this->getOption($transitionData, 'is_start', false))
                    ->setName($transitionData['name'])
                    ->setInitEntities($this->getOption($transitionData, WorkflowConfiguration::NODE_INIT_ENTITIES, []))
                    ->setInitRoutes($this->getOption($transitionData, WorkflowConfiguration::NODE_INIT_ROUTES, []))
                    ->setInitDatagrids(
                        $this->getOption($transitionData, WorkflowConfiguration::NODE_INIT_DATAGRIDS, [])
                    )
                    ->setInitContextAttribute(
                        $this->getOption($transitionData, WorkflowConfiguration::NODE_INIT_CONTEXT_ATTRIBUTE, '')
                    );
                $transitions[] = $transition;
            }
        }

        return $transitions;
    }

    /**
     * @param array $data
     * @param string $option
     * @param mixed $default
     *
     * @return mixed
     */
    private function getOption(array $data, $option, $default = null)
    {
        return isset($data[$option]) ? $data[$option] : $default;
    }
}


text:
package org.gradle.test.performance.mediummonolithicjavaproject.p54;

public class Production1087 {

    private Production1084 property0;

    public Production1084 getProperty0() {
        return property0;
    }

    public void setProperty0(Production1084 value) {
        property0 = value;
    }

    private Production1085 property1;

    public Production1085 getProperty1() {
        return property1;
    }

    public void setProperty1(Production1085 value) {
        property1 = value;
    }

    private Production1086 property2;

    public Production1086 getProperty2() {
        return property2;
    }

    public void setProperty2(Production1086 value) {
        property2 = value;
    }

    private String property3;

    public String getProperty3() {
        return property3;
    }

    public void setProperty3(String value) {
        property3 = value;
    }

    private String property4;

    public String getProperty4() {
        return property4;
    }

    public void setProperty4(String value) {
        property4 = value;
    }

    private String property5;

    public String getProperty5() {
        return property5;
    }

    public void setProperty5(String value) {
        property5 = value;
    }

    private String property6;

    public String getProperty6() {
        return property6;
    }

    public void setProperty6(String value) {
        property6 = value;
    }

    private String property7;

    public String getProperty7() {
        return property7;
    }

    public void setProperty7(String value) {
        property7 = value;
    }

    private String property8;

    public String getProperty8() {
        return property8;
    }

    public void setProperty8(String value) {
        property8 = value;
    }

    private String property9;

    public String getProperty9() {
        return property9;
    }

    public void setProperty9(String value) {
        property9 = value;
    }

}


text:
// The MIT License (MIT)

// Copyright (c) 2012-2014 Danny Y., Rapptz

// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#ifndef GEARS_MATH_HPP
#define GEARS_MATH_HPP

#include <gears/math/uintx.hpp>
#include <gears/math/generator.hpp>
#include <gears/math/constants.hpp>

/**
 * @defgroup math Math module
 * @brief Provides utilities to help with mathematics
 * @details This module provides an implementation of common
 * mathematical algorithms and an infinite precision integer.
 *
 * Example usage:
 *
 * @code
 * #include <gears/math.hpp>
 * #include <iostream>
 *
 * namespace math = gears::math;
 *
 * // needed to use _x user defined literal
 * using namespace gears::math::operators;
 *
 * int main() {
 *     auto lhs = 9384721983748274812387232191827321_x;
 *     auto rhs = 2937189237182973865769137697362736_x;
 *     std::cout << (lhs * rhs) << '\n';
 *     std::cout << math::factorial(10) << '\n';
 * }
 * @endcode
 *
 * Output
 * <pre>
 * 27564704404619880556797005156529364384954680388538087951954412110256
 * 3628800
 * </pre>
 *
 */

#endif // GEARS_MATH_HPP


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Guitar32.Exceptions
{
    /// <summary>
    /// Exception thrown when a failure occured while a data is being updated to a data source
    /// </summary>
    public class DataUpdateException : Exception
    {
        public DataUpdateException()
            : base("A data cannot be updated to a data source") { }
    }
}


text:
\section{Run and event level cut member functions}
\label{App:ObjectCuts}
\subsection{Run level member functions}
{\ttfamily \noindent
\begin{verbatim}
  void SetRunId(Int_t Pid);
  void SetMagneticField(Float_t Pmag);
  void SetRunStartTimeRange(Int_t t0, Int_t t1);
  void SetRunStopTimeRange(Int_t t0, Int_t t1);
  void SetAlirootVersion(TString v);
  void SetRootVersion(TString v);
  void SetGeant3Version(TString v);
  void SetRunQuality(Int_t Pn);
  void SetBeamEnergy(Float_t PE);
  void SetBeamType(TString Ptype);
  void SetCalibVersion(Int_t Pn);
  void SetDataType(Int_t i);
\end{verbatim}
}
\subsection{Event level member functions}
{\ttfamily \noindent
\begin{verbatim}
  void SetNParticipantsRange(Int_t low, Int_t high);
  void SetImpactParamRange(Float_t low, Float_t high);

  void SetPrimaryVertexXRange(Float_t low, Float_t high);
  void SetPrimaryVertexYRange(Float_t low, Float_t high);
  void SetPrimaryVertexZRange(Float_t low, Float_t high);
  void SetPrimaryVertexFlag(Int_t flag);
  void SetPrimaryVertexZErrorRange(Float_t low, Float_t high);

  void SetTriggerMask(ULong64_t trmask);
  void SetTriggerCluster(UChar_t trcluster);

  void SetZDCNeutron1Range(Float_t low, Float_t high);
  void SetZDCProton1Range(Float_t low, Float_t high);
  void SetZDCEMRange(Float_t low, Float_t high);
  void SetZDCNeutron2Range(Float_t low, Float_t high);
  void SetZDCProton2Range(Float_t low, Float_t high);
  void SetT0VertexZRange(Float_t low, Float_t high);

  void SetMultiplicityRange(Int_t low, Int_t high);
  void SetPosMultiplicityRange(Int_t low, Int_t high);
  void SetNegMultiplicityRange(Int_t low, Int_t high);
  void SetNeutrMultiplicityRange(Int_t low, Int_t high);
  void SetNV0sRange(Int_t low, Int_t high);
  void SetNCascadesRange(Int_t low, Int_t high);
  void SetNKinksRange(Int_t low, Int_t high);

  void SetNPMDTracksRange(Int_t low, Int_t high);
  void SetNFMDTracksRange(Int_t low, Int_t high);
  void SetNPHOSClustersRange(Int_t low, Int_t high);
  void SetNEMCALClustersRange(Int_t low, Int_t high);
  void SetNJetCandidatesRange(Int_t low, Int_t high);

  void SetTopJetEnergyMin(Float_t low);
  void SetTopNeutralEnergyMin(Float_t low);
  void SetNHardPhotonsRange(Int_t low, Int_t high);
  void SetNChargedAbove1GeVRange(Int_t low, Int_t high);
  void SetNChargedAbove3GeVRange(Int_t low, Int_t high);
  void SetNChargedAbove10GeVRange(Int_t low, Int_t high);
  void SetNMuonsAbove1GeVRange(Int_t low, Int_t high);
  void SetNMuonsAbove3GeVRange(Int_t low, Int_t high);
  void SetNMuonsAbove10GeVRange(Int_t low, Int_t high);
  void SetNElectronsAbove1GeVRange(Int_t low, Int_t high);
  void SetNElectronsAbove3GeVRange(Int_t low, Int_t high);
  void SetNElectronsAbove10GeVRange(Int_t low, Int_t high);
  void SetNElectronRange(Int_t low, Int_t high);
  void SetNMuonRange(Int_t low, Int_t high);
  void SetNPionRange(Int_t low, Int_t high);
  void SetNKaonRange(Int_t low, Int_t high);
  void SetNProtonRange(Int_t low, Int_t high);
  void SetNLambdaRange(Int_t low, Int_t high);
  void SetNPhotonRange(Int_t low, Int_t high);
  void SetNPi0Range(Int_t low, Int_t high);
  void SetNNeutronRange(Int_t low, Int_t high);
  void SetNKaon0Range(Int_t low, Int_t high);
  void SetTotalPRange(Float_t low, Float_t high);
  void SetMeanPtRange(Float_t low, Float_t high);
  void SetTopPtMin(Float_t low);
  void SetTotalNeutralPRange(Float_t low, Float_t high);
  void SetMeanNeutralPtPRange(Float_t low, Float_t high);
  void SetTopNeutralPtMin(Float_t low);
  void SetEventPlaneAngleRange(Float_t low, Float_t high);
  void SetHBTRadiiRange(Float_t low, Float_t high);
\end{verbatim}
}


text:
<?php

if ($_POST["submit"]) {

	 	 if (!$_POST['name']) {

			 $error="
Please enter your name";

	 	 }

	 	 if (!$_POST['email']) {

			 $error.="
Please
	 	 if ($_POST['email']!="" AND !filter_var($_POST['email'],
FILTER_VALIDATE_EMAIL)) {

 	 	 $error.="
Please enter a valid email address";

	 	 }

	 	 if ($error) {

 $result='
There were error(s)
in your form:'.$error.'
';

	 	 } else {

 if (mail("test@greenhost.org.uk", "Comment from website!", "Name: ".
$_POST['name']."

 Email: ".$_POST['email']."

 Comment: ".$_POST['comment'])) {

 $result='
Thank
you! I\'ll be in touch.
';

 } else {

 $result='
"Sorry, there was
an error sending your message. Please try again later."
';

 }

 }

 }

 ?>
<!doctype html>

<title>My First Webpage</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/htm
.emailForm {
border:1px solid grey;
 border-radius:10px;
 margin-top:20px;
}
form {
 padding-bottom:20px;

}
</style>

My email form

<?php echo $result; ?>

"Please get in touch - I'll get back to you as soon as I can."

<form method="post">

Your Name:
<input type="text" name="name" class="form-control" placeholder="Your Name"
value="<?php echo $_POST['name']; ?>" />

Your Email:
<input type="email" name="email" class="form-control" placeholder="Your Email"
value="<?php echo $_POST['email']; ?>" />

Your Comment:
<textarea class="form-control" name="comment"><?php echo $_POST['comment']; ?></
textarea>

<input type="submit" name="submit" class="btn btn-success btn-lg" value="Submit"
/>
</form>


text:
require 'spec_helper'

module Rubocop
  module Cop
    module Style
      describe DefWithParentheses do
        let(:def_par) { DefWithParentheses.new }

        it 'reports an offence for def with empty parens' do
          src = ['def func()',
                 'end']
          inspect_source(def_par, src)
          expect(def_par.offences.size).to eq(1)
        end

        it 'reports an offence for class def with empty parens' do
          src = ['def Test.func()',
                 'end']
          inspect_source(def_par, src)
          expect(def_par.offences.size).to eq(1)
        end

        it 'accepts def with arg and parens' do
          src = ['def func(a)',
                 'end']
          inspect_source(def_par, src)
          expect(def_par.offences).to be_empty
        end

        it 'accepts empty parentheses in one liners' do
          src = ["def to_s() join '/' end"]
          inspect_source(def_par, src)
          expect(def_par.offences).to be_empty
        end
      end
    end
  end
end


text:
%November 11th 2015
clear

baseFolder = '../CVs/CV1/'; %Train_Grid_%s.wav

% Check to make sure that folder actually exists.  Warn user if it doesn't.
if ~isdir(baseFolder)
    errorMessage = sprintf('Error: The following folder does not exist:\n%s', baseFolder);
    uiwait(warndlg(errorMessage));
    return;
end

dirinfo = dir(baseFolder);
dirinfo(~[dirinfo.isdir]) = [];  %remove non-directories
tf = ismember( {dirinfo.name}, {'.', '..'});
dirinfo(tf) = [];  %remove current and parent directory.
recordings_counter = 0; %Keep track of number of processed recordings
features = zeros(length(dir(fullfile(baseFolder,dirinfo(1).name, '*.wav'))), 14);
% output = zeros(length(dir(fullfile(baseFolder,dirinfo(1).name, '*.wav'))),7)

for s = 1 : length(dirinfo)
    theFiles = dir(fullfile(baseFolder,dirinfo(s).name, '*.wav'));
    % Get a list of all files in the folder with the desired file name pattern.
    %filePattern = fullfile(myFolder, '*.wav'); % Change to whatever pattern you need.
    %theFiles = dir(myFolder);

    for k = 1 : length(theFiles)
        clearvars -except k fullFileName baseFileName theFiles baseFolder s dirinfo grid_name features;

        baseFileName = theFiles(k).name;
        fullFileName = fullfile(baseFolder,dirinfo(s).name, baseFileName);
        fprintf(1, 'Now reading %s\n', fullFileName);
        [combined, grid_number] = preprocessing(fullFileName);
        features(k, :) = extract_features(combined, grid_number);

        imageName = strcat(baseFileName, '.jpg');
        figure
        plot(combined.time,combined.values,'linewidth',1)
        xlabel('Time (s)')
        ylabel('Frequency (Hz)')
        title(sprintf('Curve Combination for %s', baseFileName))
%         hgexport(gcf, imageName, hgexport('factorystyle'), 'Format', 'jpeg');
        close
    end
%     dlmwrite('cv2_15_03_16_completefeatures.csv',features,'-append');
end


text:
//----------------------------------------------------------------------------------
#ifndef GUIGENERICTEXT_H
#define GUIGENERICTEXT_H
//----------------------------------------------------------------------------------
class CGUIGenericText : public CGUIText
{
public:
    //!Индекс текста
    uint TextID = 0;

    //!Максимальная ширина (для CroppedText)
    int MaxWidth = 0;

    CGUIGenericText(int index, ushort color, int x, int y, int maxWidth = 0);
    virtual ~CGUIGenericText();

    void CreateTexture(const wstring &str);
};
//----------------------------------------------------------------------------------
#endif
//----------------------------------------------------------------------------------


text:
module Views
  class View < Layout
    def view_request
      @view['request']
    end

    def view_header
      @view['header']
    end

    def view_body
      @view['body']
    end
  end
end


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="20dp"
    android:height="20dp"
    android:viewportWidth="20"
    android:viewportHeight="20"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M9,13.938H15.604V9H9ZM1.271,17.062V2.938H18.729V17.062ZM12.312,11.479Z"/>
</vector>


text:
haskell + electron experiments

Nothing to see here yet. Just an attempt to make haskell work with Electron.atom.io gracefully.


text:
exports.RESTfulCall = function (callType, url, callback, errorCallback)
{
	if (Titanium.Network.online == true)
	{
		// create HTTP client
	    var xhr = Ti.Network.createHTTPClient({
	        // function called when the response data is available
	        onload : function(e) {
	        	nursApp.system.updateSessionTime();
	            callback(this.responseText);
	        },
	        // function called when an error occurs, including a timeout
	        onerror : function(e) {
	        	errorCallback();
				Ti.API.debug("STATUS: " + this.status);
				Ti.API.debug("TEXT:   " + this.responseText);
				Ti.API.debug("ERROR:  " + e.error);
	        },
		    ondatastream: function(e) {
		        // function called as data is downloaded
		        Ti.API.info('ondatastream called, readyState = '+this.readyState);
		    },
		    onsendstream: function(e) {
		        // function called as data is uploaded
		        Ti.API.info('onsendstream called, readyState = '+this.readyState);
		    },
		    onreadystatechange: function(e) {
		        switch(this.readyState) {
		            case 0:
		                // after HTTPClient declared, prior to open()
		                // though Ti won't actually report on this readyState
		                Ti.API.info('case 0, readyState = '+this.readyState);
		            break;
		            case 1:
		                // open() has been called, now is the time to set headers
		                Ti.API.info('case 1, readyState = '+this.readyState);
		            break;
		            case 2:
		                // headers received, xhr.status should be available now
		                Ti.API.info('case 2, readyState = '+this.readyState);
		            break;
		            case 3:
		                // data is being received, onsendstream/ondatastream being called now
		                Ti.API.info('case 3, readyState = '+this.readyState);
		            break;
		            case 4:
		                // done, onload or onerror should be called now
		                Ti.API.info('case 4, readyState = '+this.readyState);
		            break;
		        }
		    },
	        timeout : 8000,  // in milliseconds
	        enableKeepAlive : true
	    });

	    //prepare the connection
	    xhr.open(callType, url);
	    xhr.setRequestHeader("Content-Type","application/json");

		//send request
		xhr.send();

	}	else   {
		alert('You are not online');
	}
}

exports.newLaulimaSession = function (callback)
{
	if (Titanium.Network.online == true)
	{
		Ti.API.info('About to request a new session');
		var url = 'https://laulima.hawaii.edu/direct/session/new/?_username=' + nursApp.userData.username + '&_password=' + nursApp.userData.password;
		var callType = 'POST';
		Ti.API.info('Sending url: ' + url);

		// create HTTP client
	    var xhr = Ti.Network.createHTTPClient({
	        // function called when the response data is available
	        onload : function(e) {
	        	Ti.API.info('newLaulimaSession successful');
	        	nursApp.system.updateSessionTime();
	        	nursApp.userData.sessionID = this.responseText;
	        	Ti.API.info('Executing callback');
	            callback();
	        },
	        // function called when an error occurs, including a timeout
	        onerror : function(e) {
				Ti.API.debug("STATUS: " + this.status);
				Ti.API.debug("TEXT:   " + this.responseText);
				Ti.API.debug("ERROR:  " + e.error);
	        },

	        timeout : 8000,  // in milliseconds
	        enableKeepAlive : true
	    });

	    //prepare the connection
	    xhr.open(callType, url);
	    xhr.setRequestHeader("Content-Type","application/json");

		//send request
		xhr.send();

	}	else   {
		alert('You are not online');
	}
}


text:
YouTubeDemo Repo
===========

Test Repo for YouTube series - simplest possible example of working with Github

Series includes using GUI tools and also Codenvy integration

=======


text:
package fromjava.schema_inline.server;

import jakarta.jws.WebService;

/**
 * Tests in-lining of generated schema in WSDL
 *
 * @author Jitendra Kotamraju
 */
@WebService(name = "Echo", serviceName = "echoService",
        targetNamespace = "http://echo.org/")
public class EchoImpl {

    public Bar echoBarList(Bar bar) throws WSDLBarException, Fault1 {
        return bar;
    }

}


text:
docker run -d -p 5000:5000 --name yoapp training/webapp python app.py

# Go into the image and make changes
docker exec -it yoapp bash

#vi app.py
#import datetime
#    return 'Hello '+provider+'! '+datetime.date.today().isoformat()

# commit image
docker commit -a "Yogi" -m "Added date to welcome message" yoapp yogendra/yoapp:latest

# show that docker image is created
docker images

# create a container with new image
docker run -d -p 6000:5000 --name yoappnew yogendra/yoapp:latest python app.py

# Goto http://dockerhost:6000
open http://dockerhost:6000

# Stop and Remove container
docker rm -f yoapp yoappnew


text:
import django.utils.timezone
import model_utils.fields
from django.conf import settings
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ("django_mailbox", "0003_auto_20150409_0316"),
        ("letters", "0003_remove_attachment_text"),
    ]

    operations = [
        migrations.AlterModelOptions(
            name="attachment",
            options={
                "verbose_name": "Attachment",
                "verbose_name_plural": "Attachments",
            },
        ),
        migrations.AlterModelOptions(
            name="letter",
            options={"verbose_name": "Letter", "verbose_name_plural": "Letters"},
        ),
        migrations.RemoveField(model_name="letter", name="send_by"),
        migrations.AddField(
            model_name="letter",
            name="message",
            field=models.ForeignKey(
                on_delete=models.CASCADE,
                blank=True,
                to="django_mailbox.Message",
                null=True,
            ),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name="letter",
            name="signature",
            field=models.TextField(null=True, verbose_name="Signature", blank=True),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name="letter",
            name="accept",
            field=model_utils.fields.MonitorField(
                default=django.utils.timezone.now,
                when={b"done"},
                verbose_name="Accepted on",
                monitor=b"status",
            ),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name="letter",
            name="created_by",
            field=models.ForeignKey(
                on_delete=models.CASCADE,
                related_name="letter_created_by",
                verbose_name="Created by",
                to=settings.AUTH_USER_MODEL,
            ),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name="letter",
            name="created_on",
            field=models.DateTimeField(auto_now_add=True, verbose_name="Created on"),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name="letter",
            name="genre",
            field=models.CharField(
                default=b"comment",
                max_length=20,
                choices=[(b"mail", b"mail"), (b"comment", b"comment")],
            ),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name="letter",
            name="modified_by",
            field=models.ForeignKey(
                on_delete=models.CASCADE,
                related_name="letter_modified_by",
                verbose_name="Modified by",
                to=settings.AUTH_USER_MODEL,
                null=True,
            ),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name="letter",
            name="modified_on",
            field=models.DateTimeField(
                auto_now=True, verbose_name="Modified on", null=True
            ),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name="letter",
            name="name",
            field=models.CharField(max_length=250, verbose_name="Subject"),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name="letter",
            name="text",
            field=models.TextField(verbose_name="Comment"),
            preserve_default=True,
        ),
    ]


text: bbb::Terminator bbb::send;


text:
: ${TIMEOUT:=50000}
: ${REPORTER:="spec"}
: ${BAIL:=1}
: ${TYPE:="integration"}

if [ $BAIL -eq 1 ]; then
    BAIL_OPT="--bail"
else
    BAIL_OPT=""
fi

if [ $TYPE = "integration" ]; then
    TESTS_PATH="tests/integration/test.*.js"
fi
if [ $TYPE = "fuzzy" ]; then
    TESTS_PATH="tests/fuzzy/test.*.js"
fi
if [ $TYPE = "mapreduce" ]; then
    TESTS_PATH="tests/mapreduce/test.*.js"
fi
if [ $COVERAGE ]; then
    # run all tests when testing for coverage
    TESTS_PATH="tests/{unit,integration,mapreduce}/test*.js"
fi

if [ $PERF ]; then
    node tests/performance/index.js
elif [ ! $COVERAGE ]; then
    ./node_modules/.bin/mocha \
        $BAIL_OPT \
        --timeout $TIMEOUT \
        --require=./tests/integration/node.setup.js \
        --reporter=$REPORTER \
        --grep=$GREP \
        $TESTS_PATH
else
    ./node_modules/.bin/istanbul cover ./node_modules/mocha/bin/_mocha -- \
        $BAIL_OPT \
        --timeout $TIMEOUT \
        --require=./tests/integration/node.setup.js \
        --reporter=$REPORTER \
        --grep=$GREP \
        $TESTS_PATH
fi


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Xml;
using ColossalFramework.UI;
using UnityEngine;

namespace Sapphire
{

    public class SkinMetadata
    {
        public string name;
        public string author;
        public string sapphirePath;
    }

    public class Skin
    {

        public enum ModuleClass
        {
            MainMenu = 0,
            InGame = 1,
            MapEditor = 2,
            AssetEditor = 3
        }

        public static Skin FromXmlFile(string skinXmlPath, bool autoReloadOnChange)
        {
            Skin skin = null;

            try
            {
                skin = new Skin(skinXmlPath, autoReloadOnChange);
            }
            catch (XmlNodeException ex)
            {
                Debug.LogErrorFormat("{0} while parsing xml \"{1}\" at node \"{2}\": {3}",
                    ex.GetType(), skinXmlPath, ex.Node == null ? "null" : ex.Node.Name, ex.ToString());
            }
            catch (XmlException ex)
            {
                Debug.LogErrorFormat("XmlException while parsing xml \"{0}\" at line {1}, col {2}: {3}",
                    skinXmlPath, ex.LineNumber, ex.LinePosition, ex.Message);
            }
            catch (Exception ex)
            {
                Debug.LogErrorFormat("{0} while parsing xml \"{1}\": {2}", ex.GetType(),
                    skinXmlPath, ex.ToString());
            }

            return skin;
        }

        public static SkinMetadata MetadataFromXmlFile(string skinXmlPath)
        {
            SkinMetadata metadata = null;

            try
            {
                var document = new XmlDocument();
                document.LoadXml(File.ReadAllText(skinXmlPath));

                var root = document.SelectSingleNode("/SapphireSkin");
                if (root == null)
                {
                    throw new ParseException("Skin missing root SapphireSkin node at " + skinXmlPath, null);
                }

                var name = XmlUtil.GetStringAttribute(root, "name");
                var author = XmlUtil.GetStringAttribute(root, "author");
                metadata = new SkinMetadata {name = name, author = author, sapphirePath = Path.GetDirectoryName(skinXmlPath)};
            }
            catch (XmlNodeException ex)
            {
                Debug.LogErrorFormat("{0} while parsing xml \"{1}\" at node \"{2}\": {3}",
                    ex.GetType(), skinXmlPath, ex.Node == null ? "null" : ex.Node.Name, ex.ToString());
            }
            catch (XmlException ex)
            {
                Debug.LogErrorFormat("XmlException while parsing xml \"{0}\" at line {1}, col {2}: {3}",
                    skinXmlPath, ex.LineNumber, ex.LinePosition, ex.Message);
            }
            catch (Exception ex)
            {
                Debug.LogErrorFormat("{0} while parsing xml \"{1}\": {2}", ex.GetType(),
                    skinXmlPath, ex.ToString());
            }

            return metadata;
        }

        private Dictionary<ModuleClass, List<SkinModule>> modules = new Dictionary<ModuleClass, List<SkinModule>>();

        private string name;

        public string Name
        {
            get { return name; }
        }

        private string author;

        public string Author
        {
            get { return author; }
        }

        private Dictionary<string, Color32> colorDefinitions = new Dictionary<string, Color32>();

        public Color32 GetNamedColor(string name)
        {
            if (!colorDefinitions.ContainsKey(name))
            {
                throw new ColorNotFoundException(name);
            }

            return colorDefinitions[name];
        }

        public Dictionary<string, UITextureAtlas> spriteAtlases = new Dictionary<string, UITextureAtlas>();

        private string sapphirePath;
        private string skinXmlPath;

        public string SapphirePath
        {
            get { return sapphirePath; }
        }

        private XmlDocument document;
        private XmlNode root;

        private FileWatcher fileWatcher;

        private Rect renderArea = new Rect(0.0f, 0.0f, 1.0f, 1.0f);

        public Rect RenderArea
        {
            get
            {
                return renderArea;
            }
        }

        public bool IsValid
        {
            get { return isValid; }
        }

        private bool isValid = true;

        private ModuleClass currentModuleClass;

        private SkinApplicator applicator;

        public Skin(string _skinXmlPath, bool autoReloadOnChange)
        {
            skinXmlPath = _skinXmlPath;
            sapphirePath = Path.GetDirectoryName(skinXmlPath);
            applicator = new SkinApplicator(this);

            Reload(autoReloadOnChange);
        }

        public void SafeReload(bool autoReloadOnChange)
        {
            try
            {
                Reload(autoReloadOnChange);
            }
            catch (XmlNodeException ex)
            {
                ErrorLogger.LogErrorFormat("{0} while parsing xml \"{1}\" at node \"{2}\": {3}",
                    ex.GetType(), skinXmlPath, ex.Node == null ? "null" : ex.Node.Name, ex.ToString());
                isValid = false;
            }
            catch (XmlException ex)
            {
                ErrorLogger.LogErrorFormat("XmlException while parsing xml \"{0}\" at line {1}, col {2}: {3}",
                    skinXmlPath, ex.LineNumber, ex.LinePosition, ex.Message);
                isValid = false;
            }
            catch (Exception ex)
            {
                ErrorLogger.LogErrorFormat("{0} while parsing xml \"{1}\": {2}", ex.GetType(),
                    skinXmlPath, ex.ToString());
                isValid = false;
            }
        }

        private void Reload(bool autoReloadOnChange)
        {
            isValid = true;

            Dispose();

            modules[ModuleClass.MainMenu] = new List<SkinModule>();
            modules[ModuleClass.InGame] = new List<SkinModule>();
            modules[ModuleClass.MapEditor] = new List<SkinModule>();
            modules[ModuleClass.AssetEditor] = new List<SkinModule>();

            document = new XmlDocument();
            document.LoadXml(File.ReadAllText(skinXmlPath));

            if (fileWatcher != null)
            {
                fileWatcher.Dispose();
                fileWatcher = null;
            }

            if (autoReloadOnChange)
            {
                fileWatcher = new FileWatcher(sapphirePath);
                fileWatcher.WatchFile("skin.xml");
            }

            root = document.SelectSingleNode("/SapphireSkin");
            if (root == null)
            {
                isValid = false;
                throw new ParseException("Skin missing root SapphireSkin node at " + sapphirePath, null);
            }

            name = XmlUtil.GetStringAttribute(root, "name");
            author = XmlUtil.GetStringAttribute(root, "author");

            LoadSkinSettings();
            LoadSprites();
            LoadColors();
            LoadModules();
        }

        public void Dispose()
        {
            Rollback();
            foreach (var atlas in spriteAtlases)
            {
                GameObject.Destroy(atlas.Value.material.mainTexture);
                GameObject.Destroy(atlas.Value);
            }

            colorDefinitions.Clear();

            spriteAtlases.Clear();

            renderArea = new Rect(0.0f, 0.0f, 1.0f, 1.0f);

            if (fileWatcher != null)
            {
                fileWatcher.Dispose();
                fileWatcher = null;
            }
        }

        private void LoadModules()
        {
            foreach (XmlNode childNode in root.ChildNodes)
            {
                if (childNode.Name == "Module")
                {
                    var modulePath = Path.Combine(sapphirePath, childNode.InnerText);
                    var moduleClass = XmlUtil.GetStringAttribute(childNode, "class");

                    if (moduleClass == "MainMenu")
                    {
                        AddModuleAtPath(ModuleClass.MainMenu, modulePath);
                    }
                    else if (moduleClass == "InGame")
                    {
                        AddModuleAtPath(ModuleClass.InGame, modulePath);
                    }
                    else if (moduleClass == "MapEditor")
                    {
                        AddModuleAtPath(ModuleClass.MapEditor, modulePath);
                    }
                    else if (moduleClass == "AssetEditor")
                    {
                        AddModuleAtPath(ModuleClass.AssetEditor, modulePath);
                    }
                    else
                    {
                        throw new ParseException(String.Format
                            ("Invalid module class \"{0}\"", moduleClass), childNode);
                    }
                }
            }

            CheckAndLoadOverride(ModuleClass.MainMenu);
            CheckAndLoadOverride(ModuleClass.AssetEditor);
            CheckAndLoadOverride(ModuleClass.MapEditor);
            CheckAndLoadOverride(ModuleClass.InGame);
        }

        private void CheckAndLoadOverride(ModuleClass moduleClass)
        {
            var overridePath = Path.Combine(Core.overrideDirectory, String.Format("{0}_{1}.xml", name, moduleClass.ToString()));
            if (File.Exists(overridePath))
            {
                Debug.LogWarningFormat("Found override for skin \"{0}\" at \"{1}\"", name, overridePath);
                AddModuleAtPath(moduleClass, overridePath);
            }
        }

        private void LoadSkinSettings()
        {
            try
            {
                LoadSkinSettingsInternal();
            }
            catch (XmlNodeException ex)
            {
                ErrorLogger.LogErrorFormat("{0} while loading skin settings for skin \"{1}\" at node \"{2}\": {3}",
                    ex.GetType(), name, ex.Node == null ? "null" : ex.Node.Name, ex.ToString());
                isValid = false;
            }
            catch (Exception ex)
            {
                ErrorLogger.LogErrorFormat("{0} while loading skin settings for skin \"{1}\": {2}", ex.GetType(), name, ex.Message);
                isValid = false;
            }
        }

        private void LoadSkinSettingsInternal()
        {
            Debug.LogWarning("Loading skin settings");

            var rootSettingsNode = document.SelectSingleNode("/SapphireSkin/SkinSettings");

            if (rootSettingsNode == null)
            {
                Debug.LogWarning("Skin defines no settings");
                return;
            }

            foreach (XmlNode childNode in rootSettingsNode)
            {
                var settingsKey = childNode.Name;
                var text = childNode.InnerText;

                if (text.Length == 0)
                {
                    throw new ParseException(String.Format("Empty value for settings key \"{0}\"", settingsKey), childNode);
                }

                if (settingsKey == "InGameRenderArea")
                {
                    var rect = (Rect)XmlUtil.GetValueForType(childNode, typeof (Rect), childNode.InnerText, null);
                    Debug.LogWarning(String.Format("Setting skin \"InGameRenderArea\" to {0}", rect));

                    rect.width /= 1920.0f;
                    rect.height /= 1080.0f;

                    rect.x /= 1920.0f;
                    rect.y /= 1080.0f;
                    rect.y = 1.0f - rect.y - rect.height;

                    renderArea = rect;
                }
            }
        }

        private void LoadColors()
        {
            try
            {
                LoadColorsInternal();
            }
            catch (XmlNodeException ex)
            {
                ErrorLogger.LogErrorFormat("{0} while loading colors for skin \"{1}\" at node \"{2}\": {3}",
                    ex.GetType(), name, ex.Node == null ? "null" : ex.Node.Name, ex.ToString());
                isValid = false;
            }
            catch (Exception ex)
            {
                ErrorLogger.LogErrorFormat("Exception while loading colors for skin \"{0}\": {1}", name, ex.Message);
                isValid = false;
            }
        }

        private void LoadColorsInternal()
        {
            Debug.LogWarning("Loading colors");

            var rootColorsNode = document.SelectSingleNode("/SapphireSkin/Colors");

            if (rootColorsNode == null)
            {
                Debug.LogWarning("Skin defines no colors");
                return;
            }

            foreach (XmlNode childNode in rootColorsNode)
            {
                if (childNode.Name != "Color")
                {
                    continue;
                }

                var colorName = XmlUtil.GetStringAttribute(childNode, "name");
                if (colorDefinitions.ContainsKey(colorName))
                {
                    Debug.LogWarningFormat("Duplicate color name \"{0}\", ignoring second definition..", colorName);
                    continue;
                }

                var text = childNode.InnerText;

                if (text.Length == 0)
                {
                    throw new ParseException(String.Format("Empty color value for color \"{0}\"", colorName), childNode);
                }

                Color32 color = Color.black;

                if (text[0] == '#')
                {
                    int colorHex = Int32.Parse(text.Replace("#", ""), NumberStyles.HexNumber);
                    byte r = (byte)((colorHex >> 16) & 0xFF);
                    byte g = (byte)((colorHex >> 8) & 0xFF);
                    byte b = (byte)((colorHex) & 0xFF);
                    color = new Color32(r, g, b, 255);
                }
                else
                {
                    var values = text.Split(',');
                    if (values.Length != 4)
                    {
                        throw new ParseException("Color32 definition must have four components", childNode);
                    }

                    color = new Color32(byte.Parse(values[0]), byte.Parse(values[1]), byte.Parse(values[2]), byte.Parse(values[3]));
                }

                colorDefinitions.Add(colorName, color);
                Debug.LogWarningFormat("Color \"{0}\" defined as \"{1}\"", colorName, color.ToString());
            }
        }

        private void LoadSprites()
        {
            try
            {
                LoadSpritesInternal();
            }
            catch (XmlNodeException ex)
            {
                ErrorLogger.LogErrorFormat("{0} while loading sprites for skin \"{1}\" at node \"{2}\": {3}",
                    ex.GetType(), name, ex.Node == null ? "null" : ex.Node.Name, ex.ToString());
                isValid = false;
            }
            catch (Exception ex)
            {
                ErrorLogger.LogErrorFormat("{0} while loading sprites for skin \"{1}\": {2}", ex.GetType(), name, ex.Message);
                isValid = false;
            }
        }

        private void LoadSpritesInternal()
        {
            Debug.LogWarning("Loading sprites");

            foreach (XmlNode childNode in root)
            {
                if (childNode.Name != "SpriteAtlas")
                {
                    continue;
                }

                var atlasName = XmlUtil.GetStringAttribute(childNode, "name");
                if (spriteAtlases.ContainsKey(atlasName))
                {
                    throw new ParseException(String.Format("Duplicate atlas name \"{0}\"", atlasName), childNode);
                }

                Debug.LogWarningFormat("Generating atlas \"{0}\"", atlasName);

                var atlasPacker = new AtlasPacker();

                int count = 0;
                foreach (XmlNode spriteNode in childNode.ChildNodes)
                {
                    var path = spriteNode.InnerText;
                    if (fileWatcher != null)
                    {
                        fileWatcher.WatchFile(path);
                    }

                    var name = XmlUtil.GetStringAttribute(spriteNode, "name");
                    Debug.LogWarningFormat("Found definition for sprite \"{0}\" in atlas \"{1}\"", name, atlasName);

                    var fullPath = Path.Combine(sapphirePath, path);

                    if (!File.Exists(fullPath))
                    {
                        throw new FileNotFoundException(String.Format("Sprite at path \"{0}\" not found!", fullPath), fullPath);
                    }

                    atlasPacker.AddSprite(name, fullPath);
                    count++;
                }

                Debug.LogWarningFormat("Added {0} sprites to atlas \"{1}\"", count, atlasName);

                try
                {
                    spriteAtlases[atlasName] = atlasPacker.GenerateAtlas(atlasName);
                }
                catch (AtlasPacker.TooManySprites)
                {
                    ErrorLogger.LogError("Too many sprites in atlas \"" + atlasName + "\", move some sprites to a new atlas!");
                    break;
                }

                Debug.LogWarningFormat("Atlas \"{0}\" generated", atlasName);
            }
        }

        private void AddModuleAtPath(ModuleClass moduleClass, string modulePath)
        {
            if (fileWatcher != null)
            {
                fileWatcher.WatchFile(modulePath);
            }

            var name = Path.GetFileNameWithoutExtension(modulePath);
            if (name == null)
            {
                throw new Exception(String.Format("Invalid skin module path \"{0}\"", modulePath));
            }

            var module = SkinModule.FromXmlFile(modulePath);
            if (module == null)
            {
                isValid = false;
                return;
            }

            modules[moduleClass].Add(module);
        }

        public void ApplyStickyProperties(ModuleClass moduleClass)
        {
            if (!isValid)
            {
                return;
            }

            applicator.ApplyStickyProperties();
        }

        public void Apply(ModuleClass moduleClass)
        {
            if (!isValid)
            {
                Debug.LogWarning("Trying to apply an invalid skin");
                return;
            }

            currentModuleClass = moduleClass;

            if (!applicator.Apply(modules[moduleClass]))
            {
                applicator.Rollback();
                Debug.LogWarning("Failed to apply skin module (look for an error in the messages above). All changes have been reverted.");
                isValid = false;
            }

            SetCameraRectHelper.CameraRect = renderArea;
        }

        public void Rollback()
        {
            if (!isValid)
            {
                Debug.LogWarning("Trying to roll-back an invalid skin");
                return;
            }

            applicator.Rollback();
            SetCameraRectHelper.ResetCameraRect();
        }

        public void ReloadIfChanged()
        {
            if (fileWatcher != null)
            {
                if (fileWatcher.CheckForAnyChanges())
                {
                    SafeReload(fileWatcher != null);
                    Apply(currentModuleClass);
                }
            }
        }

    }
}


text:
import React, { Component, PropTypes } from "react";
import { Motion, spring } from "react-motion";

import {
  SpringSettings,
  BLACKLIST_CURRENT_ELEMENT_DESELECT
} from "../../constants";
import Icon from "../icon";
import styles from "./element-item.css";

const addedPadding = 2;

class ElementItem extends Component {
  static propTypes = {
    elementType: PropTypes.string.isRequired,
    elementLeft: PropTypes.number.isRequired,
    elementTop: PropTypes.number.isRequired,
    elementWidth: PropTypes.number.isRequired,
    elementHeight: PropTypes.number.isRequired,
    onDragStart: PropTypes.func.isRequired,
    onDrag: PropTypes.func.isRequired,
    onDragStop: PropTypes.func.isRequired,
    onDrop: PropTypes.func.isRequired,
    scale: PropTypes.number
  };

  static contextTypes = {
    store: React.PropTypes.object
  };

  constructor(props, context) {
    super(props, context);

    this.state = {
      delta: [0, 0],
      mouseStart: [0, 0],
      mouseOffset: [0, 0],
      canvasOffset: [0, 0],
      isPressed: false,
      isUpdating: false
    };
  }

  handleTouchStart = (ev) => {
    ev.preventDefault();
    this.handleMouseDown(ev.touches[0]);
  }

  handleTouchMove = (ev) => {
    ev.preventDefault();
    this.handleMouseMove(ev.touches[0]);
  }

  handleMouseMove = ({ pageX, pageY, offsetX, offsetY, clientX, clientY, target: { id } }) => {
    const { mouseStart: [x, y], isOverCanvasPosition } = this.state;
    const newDelta = [pageX - x, pageY - y];

    let isUpdating = false;
    let newOverCanvasPosition = null;

    if (id === "canvas" || id === "slide") {
      newOverCanvasPosition = [offsetX, offsetY];

    // Switching from canvas element back to icon, do not animate icon
    } else if (isOverCanvasPosition !== null) {
      isUpdating = true;
    }

    const mousePosition = {
      clientX,
      clientY
    };

    if (!newOverCanvasPosition && this.state.isOverCanvasPosition) {
      this.props.onDragStop();
    } else if (newOverCanvasPosition && !this.state.isOverCanvasPosition) {
      this.props.onDragStart(mousePosition, this.props.elementType);
    }

    if (newOverCanvasPosition) {
      this.props.onDrag(mousePosition);
    }

    this.setState({
      delta: newDelta,
      // TODO: Clean up these two properties
      canvasOffset: [offsetX, offsetY],
      isOverCanvasPosition: newOverCanvasPosition,
      isUpdating
    }, () => {
      this.setState({
        isUpdating: false
      });
    });
  }

  handleMouseDown = (ev) => {
    ev.preventDefault();
    ev.persist();

    const { pageX, pageY } = ev;

    window.addEventListener("mouseup", this.handleMouseUp);
    window.addEventListener("touchend", this.handleMouseUp);

    // Only do drag if we hold the mouse down for a bit
    this.mouseClickTimeout = setTimeout(() => {
      this.mouseClickTimeout = null;

      this.context.store.updateElementDraggingState(true, true);

      // Make the cursor dragging everywhere
      document.body.style.cursor = "-webkit-grabbing";

      this.setState({
        mouseOffset: [(addedPadding / 2), (addedPadding / 2)],
        delta: [0, 0],
        mouseStart: [pageX, pageY],
        isPressed: true
      });

      window.addEventListener("touchmove", this.handleTouchMove);
      window.addEventListener("mousemove", this.handleMouseMove);
    }, 150);
  }

  handleMouseUp = () => {
    if (this.mouseClickTimeout || this.mouseClickTimeout === 0) {
      clearTimeout(this.mouseClickTimeout);
      window.removeEventListener("mouseup", this.handleMouseUp);
      window.removeEventListener("touchend", this.handleMouseUp);

      this.mouseClickTimeout = null;

      this.props.onDrop(this.props.elementType);
      this.props.onDragStop();

      return;
    }

    window.removeEventListener("touchmove", this.handleTouchMove);
    window.removeEventListener("touchend", this.handleMouseUp);
    window.removeEventListener("mousemove", this.handleMouseMove);
    window.removeEventListener("mouseup", this.handleMouseUp);

    // Reset the cursor dragging to auto
    document.body.style.cursor = "auto";

    const state = {
      delta: [0, 0],
      mouseOffset: [0, 0],
      mouseStart: [0, 0],
      canvasOffset: [0, 0],
      isOverCanvasPosition: null,
      isPressed: false
    };

    if (this.state.isOverCanvasPosition) {
      // Don't show return animation if dropping the element on the canvas
      state.isUpdating = true;

      this.props.onDrop(this.props.elementType, [
        this.state.canvasOffset[0],
        this.state.canvasOffset[1]
      ]);
      this.props.onDragStop();
    }

    this.context.store.updateElementDraggingState(false);

    this.setState(state, () => {
      setTimeout(() => {
        this.setState({
          isUpdating: false
        });
      }, 1);
    });
  }

  render() {
    const {
      elementType,
      elementLeft,
      elementTop,
      elementWidth,
      elementHeight
    } = this.props;

    const {
      isUpdating,
      isOverCanvasPosition,
      isPressed,
      delta: [x, y],
      mouseOffset: [offsetX, offsetY]
    } = this.state;

    const motionStyles = {
      translateX: spring(x - offsetX, SpringSettings.DRAG),
      translateY: spring(y - offsetY, SpringSettings.DRAG),
      opacity: spring(isPressed ? 0.9 : 0, SpringSettings.DRAG),
      padding: spring(isPressed ? 2 : 0, SpringSettings.DRAG)
    };

    if (isUpdating) {
      motionStyles.translateX = isPressed ? x - offsetX : 0;
      motionStyles.translateY = isPressed ? y - offsetY : 0;
      motionStyles.padding = isPressed ? addedPadding : 0;
      motionStyles.opacity = 0.9;
    }

    return (
      <div
        onMouseDown={this.handleMouseDown}
        onTouchStart={this.handleTouchStart}
        className={`${styles.wrapper} ${BLACKLIST_CURRENT_ELEMENT_DESELECT}`}
        style={{
          left: elementLeft,
          top: elementTop,
          width: elementWidth,
          height: elementHeight,
          cursor: isPressed ? "-webkit-grabbing" : "-webkit-grab"
        }}
      >
        {!isOverCanvasPosition &&
          <Motion
            defaultStyle={isUpdating ? motionStyles : {
              translateX: 0,
              translateY: 0,
              padding: 0,
              opacity: 0
            }}
            style={motionStyles}
          >
            {({ translateY, translateX, opacity, padding }) => (
              <Icon
                name={elementType}
                className={`${styles.icon} ${styles.dragIcon}`}
                style={{
                  transform: `
                    translate3d(${translateX}px,
                    ${translateY}px, 0)
                  `,
                  opacity,
                  padding
                }}
              />
            )}
          </Motion>
        }
        <div
          className={styles.item}
        >
          <Icon name={elementType} className={styles.icon} />
          <h4>
            {elementType.replace("Plotly", "Plotly & Dash")}
          </h4>
        </div>
      </div>
    );
  }
}

export default ElementItem;


text:
package isse.mbr.integration;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;

import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

import isse.mbr.parsing.CodeGenerator;
import isse.mbr.parsing.MiniBrassCompiler;
import isse.mbr.parsing.MiniBrassParseException;
import isse.mbr.tools.BasicTestListener;
import isse.mbr.tools.MiniZincLauncher;

@RunWith(Parameterized.class)
public class FuzzyTest {

	String minibrassModel = "test-models/fuzzy.mbr";
	String minibrassWorkaroundModel = "test-models/fuzzyWorkaround.mbr";
	String minibrassCompiled = "test-models/fuzzy_o.mzn";
	String minizincModel = "test-models/fuzzy.mzn";
	private MiniBrassCompiler compiler;
	private MiniZincLauncher launcher;

	// parameterized test stuff
	enum Type {TEST_DIRECT_TABLE, TEST_WORKAROUND};
	@Parameters
	public static Collection<Object[]> data(){
		return Arrays.asList(new Object[][] {
				{Type.TEST_DIRECT_TABLE, "jacop", "fzn-jacop", "0", "0", "0", "1.0"},
				{Type.TEST_DIRECT_TABLE, "gecode", "fzn-gecode", "0", "0", "0", "1.0"},
				{Type.TEST_DIRECT_TABLE, "chuffed", "fzn-chuffed", "0", "0", "0", "1.0"},
				{Type.TEST_WORKAROUND, "jacop", "fzn-jacop", "0", "0", "0", "1.0"},
				{Type.TEST_WORKAROUND, "gecode", "fzn-gecode", "0", "0", "0", "1.0"},
			//  Chuffed does not work with floats
			//	{Type.TEST_WORKAROUND, "chuffed", "fzn-chuffed", "0", "0", "0", "1.0"}
		});
	}

	private Type type;
	private String mznGlobals, fznExec, expectedMainCourse, expectedWine, expectedLunch, expectedObj;

	public FuzzyTest(Type type, String a, String b, String expected,String expected2,String expected3,
			String expected4){
		this.type = type;
		this.mznGlobals=a; this.fznExec=b; this.expectedMainCourse=expected;this.expectedWine=expected2;this.expectedLunch=expected3;
		this.expectedObj=expected4;
	}

	@Before
	public void setUp() throws Exception {
		compiler = new MiniBrassCompiler(true);
		launcher = new MiniZincLauncher();
		launcher.setMinizincGlobals(mznGlobals);
		launcher.setFlatzincExecutable(fznExec);
	}

	@Test
	public void testDirectTable() throws IOException, MiniBrassParseException {
		Assume.assumeTrue(type == Type.TEST_DIRECT_TABLE);
		// This one currently only works with JaCoP
		// cause other solvers do not properly support float_array_element
		launcher.setMinizincGlobals("jacop");
		launcher.setFlatzincExecutable("fzn-jacop");

		// 1. compile minibrass file
		File output = new File(minibrassCompiled);
		compiler.compile(new File(minibrassModel), output);
		Assert.assertTrue(output.exists());

		// 2. execute minisearch

		BasicTestListener listener = new BasicTestListener();
		launcher.addMiniZincResultListener(listener);
		launcher.runMiniSearchModel(new File(minizincModel), null, 60);

		// 3. check solution
		Assert.assertTrue(listener.isSolved());
		Assert.assertTrue(listener.isOptimal());

		Assert.assertEquals(expectedMainCourse, listener.getLastSolution().get("mainCourse"));
		Assert.assertEquals(expectedWine, listener.getLastSolution().get("wine"));
		Assert.assertEquals(expectedLunch, listener.getLastSolution().get("lunch"));

		// for the objective, we need to find out the variable name
		// instance was "cr1"
		String obj = CodeGenerator.encodeString("overall","fz1");
		Assert.assertEquals(expectedObj, listener.getObjectives().get(obj));
	}

	@Test
	public void testWorkaround() throws IOException, MiniBrassParseException {
		Assume.assumeTrue(type == Type.TEST_WORKAROUND);
		// 1. compile minibrass file
		File output = new File(minibrassCompiled);
		compiler.compile(new File(minibrassWorkaroundModel), output);
		Assert.assertTrue(output.exists());

		// 2. execute minisearch

		BasicTestListener listener = new BasicTestListener();
		launcher.addMiniZincResultListener(listener);
		launcher.runMiniSearchModel(new File(minizincModel), null, 60);

		// 3. check solution
		Assert.assertTrue(listener.isSolved());
		Assert.assertTrue(listener.isOptimal());

		Assert.assertEquals(expectedMainCourse, listener.getLastSolution().get("mainCourse"));
		Assert.assertEquals(expectedWine, listener.getLastSolution().get("wine"));
		Assert.assertEquals(expectedLunch, listener.getLastSolution().get("lunch"));

		// for the objective, we need to find out the variable name
		// instance was "cr1"
		String obj = CodeGenerator.encodeString("overall","fz1");
		Assert.assertEquals(expectedObj, listener.getObjectives().get(obj));
	}
}


text:
package com.firebearsstudio.arcaneindustry.items;

import net.minecraft.item.ItemPickaxe;

public class ItemArcanePickaxe extends ItemPickaxe {

	public ItemArcanePickaxe(String unlocalizedName, ToolMaterial material) {
		super(material);

		this.setUnlocalizedName(unlocalizedName);
	}
}


text:
var uuid = require('node-uuid');

// query:{id}/<topic>
// query/<topic>
function isQuery(topic) {
  var queryPrefix = 'query/';
  if (topic.slice(0, queryPrefix.length) === queryPrefix) {
    return true;
  }

  var queryPrefix = 'query:';
  if (topic.slice(0, queryPrefix.length) === queryPrefix) {
    return true;
  }

  return false;
}

module.exports.isQuery = isQuery;

module.exports.parse = function parseDeviceQuery(q) {
  if (!isQuery(q)) {
    return null;
  }

  var split = q.split('/');
  var ret = {
    id: (split.splice(0, 1)[0].split(':')[1] || uuid.v4() ),
    ql: split.join('/')
  };

  return ret;
};

module.exports.format = function formatDeviceQuery(obj) {
  if (!obj.id) {
    obj.id = uuid.v4();
  }
  return 'query:' + obj.id + '/' + obj.ql;
};