text:
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using XenAPI;
using XenAdmin.Core;

namespace XenAdmin.ConsoleView
{
    public partial class VNCView : UserControl
    {
        private readonly VM source;
        private readonly VNCTabView vncTabView;
        public Form undockedForm;

        /// <summary>
        /// Helper boolean to only trigger Resize_End when window is really resized by dragging edges
        /// Without this Resize_End is triggered even when window is moved around and not resized
        /// </summary>
        private bool undockedFormResized;

        public bool IsDocked => undockedForm == null || !undockedForm.Visible;

        public void Pause()
        {
            vncTabView?.Pause();
        }

        public void Unpause()
        {
            vncTabView?.Unpause();
        }

        public VNCView(VM source, string elevatedUsername, string elevatedPassword)
        {
            Program.AssertOnEventThread();

            this.source = source;
            this.vncTabView = new VNCTabView(this, source, elevatedUsername, elevatedPassword) {Dock = DockStyle.Fill};

            InitializeComponent();
            this.Controls.Add(this.vncTabView);
        }

        private void UnregisterEventListeners()
        {
            if(source != null)
                source.PropertyChanged -= new PropertyChangedEventHandler(Server_PropertyChanged);
        }

        private Size oldUndockedSize = Size.Empty;
        private Point oldUndockedLocation = Point.Empty;
        private bool oldScaledSetting = false;

        public void DockUnDock()
        {
            if (IsDocked)
            {
                if (this.undockedForm == null)
                {
                    undockedForm = new Form();
                    undockedForm.Text = UndockedWindowTitle(source);
                    source.PropertyChanged -= Server_PropertyChanged;
                    source.PropertyChanged += Server_PropertyChanged;
                    undockedForm.Icon = Program.MainWindow.Icon;
                    undockedForm.FormClosing += new FormClosingEventHandler(delegate(object sender, FormClosingEventArgs e)
                    {
                        this.DockUnDock();
                    });
                    undockedForm.StartPosition = FormStartPosition.CenterScreen;
                    FormWindowState lastState = undockedForm.WindowState;
                    undockedForm.Resize += new EventHandler(
                         delegate(Object o, EventArgs a)
                         {
                             undockedFormResized = true;
                             if (undockedForm.WindowState != lastState && undockedForm.WindowState != FormWindowState.Minimized)
                             {
                                 lastState = undockedForm.WindowState;
                                 UpdateRDPResolution();
                             }

                             if (undockedForm.WindowState == FormWindowState.Minimized)
                             {
                                 vncTabView.Pause();
                             }
                             else
                             {
                                 vncTabView.Unpause();
                             }
                         });

                    undockedForm.ResizeEnd += new EventHandler(
                         delegate(Object o, EventArgs a)
                         {
                             if (undockedFormResized)
                                 UpdateRDPResolution();
                             undockedFormResized = false;
                         });

                }

                this.Controls.Remove(vncTabView);
                undockedForm.Controls.Add(vncTabView);

                oldScaledSetting = vncTabView.IsScaled;

                vncTabView.showHeaderBar(!source.is_control_domain, true);

                undockedForm.ClientSize = vncTabView.GrowToFit();

                if (oldUndockedSize != Size.Empty
                    && oldUndockedLocation != Point.Empty
                    && HelpersGUI.WindowIsOnScreen(oldUndockedLocation, oldUndockedSize))
                {
                    undockedForm.Size = oldUndockedSize;
                    undockedForm.StartPosition = FormStartPosition.Manual;
                    undockedForm.Location = oldUndockedLocation;
                }

                undockedForm.HelpButton = true;
                undockedForm.HelpButtonClicked += undockedForm_HelpButtonClicked;
                undockedForm.HelpRequested += undockedForm_HelpRequested;

                undockedForm.Show();

                if(Properties.Settings.Default.PreserveScaleWhenUndocked)
                    vncTabView.IsScaled = oldScaledSetting;

                this.reattachConsoleButton.Show();
                this.findConsoleButton.Show();
            }
            else
            {
                //save location of undock vnc control
                this.oldUndockedLocation = undockedForm.Location;
                this.oldUndockedSize = undockedForm.Size;

                if (!Properties.Settings.Default.PreserveScaleWhenUndocked)
                    vncTabView.IsScaled = oldScaledSetting;

                this.reattachConsoleButton.Hide();
                this.findConsoleButton.Hide();

                undockedForm.Hide();
                vncTabView.showHeaderBar(true, false);
                undockedForm.Controls.Remove(vncTabView);
                this.Controls.Add(vncTabView);

                undockedForm.Dispose();
                undockedForm = null;
            }

            vncTabView.UpdateDockButton();

            vncTabView.UpdateParentMinimumSize();

            //Every time we dock / undock I'm going to force an unpause to make sure we don't ever pause a visible one.
            vncTabView.Unpause();
            vncTabView.focus_vnc();

            //reconnect RDP with docked/undocked window dimensions
            UpdateRDPResolution();
        }

        private string UndockedWindowTitle(VM vm)
        {
            if (vm.IsControlDomainZero(out Host host))
                return string.Format(Messages.CONSOLE_HOST, host.Name());

            if (vm.IsSrDriverDomain(out SR sr))
                return string.Format(Messages.CONSOLE_SR_DRIVER_DOMAIN, sr.Name());

            return vm.Name();
        }

        private void undockedForm_HelpButtonClicked(object sender, CancelEventArgs e)
        {
            Help.HelpManager.Launch("TabPageConsole");
            e.Cancel = true;
        }

        private void undockedForm_HelpRequested(object sender, HelpEventArgs hlpevent)
        {
            Help.HelpManager.Launch("TabPageConsole");
            hlpevent.Handled = true;
        }

        void Server_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "name_label" && undockedForm != null)
            {
                undockedForm.Text = UndockedWindowTitle(source);
            }
        }

        private void findConsoleButton_Click(object sender, EventArgs e)
        {
            if (!IsDocked)
                undockedForm.BringToFront();
            if (undockedForm.WindowState == FormWindowState.Minimized)
                undockedForm.WindowState = FormWindowState.Normal;
        }

        private void reattachConsoleButton_Click(object sender, EventArgs e)
        {
            DockUnDock();
        }

        internal void SendCAD()
        {
            if (this.vncTabView != null)
                this.vncTabView.SendCAD();
        }

        internal void FocusConsole()
        {
            if (this.vncTabView != null)
                vncTabView.focus_vnc();
        }

        internal void SwitchIfRequired()
        {
            vncTabView.SwitchIfRequired();
        }

        internal Image Snapshot()
        {
            return vncTabView.Snapshot();
        }

        public void refreshIsoList()
        {
            vncTabView.setupCD();
        }

        public void UpdateRDPResolution(bool fullscreen = false)
        {
            vncTabView.UpdateRDPResolution(fullscreen);
        }
    }
}


text:
'use strict'

const chai = require('chai')
const assert = chai.assert
const equal = require('deep-equal')

const {
  normalizeDate,
  isNumber,
  normalizeBoolean,
  normalizeNotes,
  getDateInSecs,
  isDefined,
  getTestError,
  validateWebhookSignature,
  validatePaymentVerification
} = require('../../dist/utils/razorpay-utils')

describe('Razorpay Utils', () => {
  it('normalizeDate', () => {
    let date = 'Aug 25, 2016'
    assert.equal(
      normalizeDate(date),
      getDateInSecs(date),
      'Returns date in secs'
    )
  });

  it('isNumber', () => {
    assert.equal(
      isNumber('0.3'),
      true,
      'Number check'
    )

    assert.equal(
      isNumber('abc'),
      false,
      'Number check with alphabets'
    )
  });

  it('normalizeBoolean', () => {
    assert.equal(
      normalizeBoolean(undefined),
      undefined,
      'When undefined is passed, just return it'
    )

    assert.equal(
      normalizeBoolean(true),
      1,
      'Boolean check with true'
    )

    assert.equal(
      normalizeBoolean(false),
      0,
      'Boolean check with false'
    )
  });

  it('normalizeNotes', () => {
    assert.ok(
      equal(
        normalizeNotes({
          note1: 'This is note1',
          note2: 'This is note2'
        }),
        {
          'notes[note1]': 'This is note1',
          'notes[note2]': 'This is note2'
        }
      ),
      'Transforms the notes'
    )
  });

  it('isDefined', () => {

    assert.ok(
      !isDefined() && isDefined(""),
      'Checks if the argument is defined'
    );
  });

  it('getTestError', () => {
    const error = getTestError("", "", "");
    assert.ok(
      error.constructor.name === "Error",
      'Gets common error for all tests'
    );
  });

  it('validateWebhookSignature', () => {

    const respBody         = '{"a":1,"b":2,"c":{"d":3}}',
          secret           = "123456",
          correctSignature = "2fe04e22977002e6c7cb553adab8b460cb"+
                             "9e2a4970d5953cb27a8472752e3bbc",
          wrongSignature   = "sdfafds";

    assert.ok(
      validateWebhookSignature(respBody, correctSignature, secret) &&
      !validateWebhookSignature(respBody, wrongSignature, secret),
      'Validates webhook signature'
    );
  });

  it('Subscription Verfication', () => {

    const respBody = {
              'subscription_id':'sub_ID6MOhgkcoHj9I',
              'payment_id':'pay_IDZNwZZFtnjyym',
          },
          correctSignature = '601f383334975c714c91a7d97dd723eb56520318355863dcf3821c0d07a17693',
          wrongSignature = 'sddsfdsfs',
          secret = 'EnLs21M47BllR3X8PSFtjtbd';

       assert.ok(
        validatePaymentVerification(respBody, correctSignature, secret) &&
        !validatePaymentVerification(respBody, wrongSignature, secret),
        'Validates subscription'
      );
  })

  it('PaymentLink Verfication', () => {

    const respBody = {
              'payment_link_id':'plink_IH3cNucfVEgV68',
              'payment_id':'pay_IH3d0ara9bSsjQ',
              'payment_link_reference_id':'TSsd1989',
              'payment_link_status':'paid'
          },
          correctSignature = '07ae18789e35093e51d0a491eb9922646f3f82773547e5b0f67ee3f2d3bf7d5b',
          wrongSignature = 'sddsfdsfs',
          secret = 'EnLs21M47BllR3X8PSFtjtbd';

       assert.ok(
        validatePaymentVerification(respBody, correctSignature, secret) &&
        !validatePaymentVerification(respBody, wrongSignature, secret),
        'Validates paymentlink'
      );
  })

  it('Payment Verfication', () => {

          const respBody = {
            'order_id':'order_IEIaMR65cu6nz3',
            'payment_id':'pay_IH4NVgf4Dreq1l',
          },
          correctSignature = '0d4e745a1838664ad6c9c9902212a32d627d68e917290b0ad5f08ff4561bc50f',
          wrongSignature = 'sddsfdsfs',
          secret = 'EnLs21M47BllR3X8PSFtjtbd';

       assert.ok(
        validatePaymentVerification(respBody, correctSignature, secret) &&
        !validatePaymentVerification(respBody, wrongSignature, secret),
        'Validates payment'
      );
  })
})

redpajama_set_name: RedPajamaGithub


text:
/*
*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    (at your option) any later version.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>
*    @author <author>
*    @Fecha <fecha>
*    @use <USE DESCRIPCION>
*/

var app = angular.module('myApp',[])
app.controller('myCtrl',function($scope){
	$('#BicicletasparaalquilereDetalle').YellowText();
	$scope.guardar = function(){
		$('form#BicicletasparaalquilereEditForm').submit();
	};
	$scope.cancelar = function(){
		window.history.back();
	};
})

/***
$(document).ready(function(){
	IniciarEventos();
})

function IniciarEventos(){
	$('#guardar').click(guardardatos)

	$('#cancelar').click(function(){})
}

function guardardatos(){

}

**/


text:
package io.druid.sql.avatica;

import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import io.druid.java.util.common.ISE;
import io.druid.java.util.common.guava.Sequence;
import io.druid.java.util.common.guava.Sequences;
import io.druid.java.util.common.guava.Yielder;
import io.druid.java.util.common.guava.Yielders;
import io.druid.sql.calcite.planner.Calcites;
import io.druid.sql.calcite.planner.PlannerFactory;
import io.druid.sql.calcite.planner.PlannerResult;
import io.druid.sql.calcite.rel.QueryMaker;
import org.apache.calcite.avatica.AvaticaParameter;
import org.apache.calcite.avatica.ColumnMetaData;
import org.apache.calcite.avatica.Meta;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeField;
import org.apache.calcite.tools.Planner;

import javax.annotation.concurrent.GuardedBy;
import java.io.Closeable;
import java.io.IOException;
import java.sql.DatabaseMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * Statement handle for {@link DruidMeta}. Thread-safe.
 */
public class DruidStatement implements Closeable
{
  public static final long START_OFFSET = 0;

  enum State
  {
    NEW,
    PREPARED,
    RUNNING,
    DONE
  }

  private final String connectionId;
  private final int statementId;
  private final Object lock = new Object();

  private State state = State.NEW;
  private String query;
  private long maxRowCount;
  private PlannerResult plannerResult;
  private Meta.Signature signature;
  private Yielder<Object[]> yielder;
  private int offset = 0;

  public DruidStatement(final String connectionId, final int statementId)
  {
    this.connectionId = connectionId;
    this.statementId = statementId;
  }

  public static List<ColumnMetaData> createColumnMetaData(final RelDataType rowType)
  {
    final List<ColumnMetaData> columns = new ArrayList<>();
    List<RelDataTypeField> fieldList = rowType.getFieldList();

    for (int i = 0; i < fieldList.size(); i++) {
      RelDataTypeField field = fieldList.get(i);
      final ColumnMetaData.Rep rep = QueryMaker.rep(field.getType().getSqlTypeName());
      final ColumnMetaData.ScalarType columnType = ColumnMetaData.scalar(
          field.getType().getSqlTypeName().getJdbcOrdinal(),
          field.getType().getSqlTypeName().getName(),
          rep
      );
      columns.add(
          new ColumnMetaData(
              i, // ordinal
              false, // auto increment
              true, // case sensitive
              false, // searchable
              false, // currency
              field.getType().isNullable()
              ? DatabaseMetaData.columnNullable
              : DatabaseMetaData.columnNoNulls, // nullable
              true, // signed
              field.getType().getPrecision(), // display size
              field.getName(), // label
              null, // column name
              null, // schema name
              field.getType().getPrecision(), // precision
              field.getType().getScale(), // scale
              null, // table name
              null, // catalog name
              columnType, // avatica type
              true, // read only
              false, // writable
              false, // definitely writable
              columnType.columnClassName() // column class name
          )
      );
    }

    return columns;
  }

  public DruidStatement prepare(final PlannerFactory plannerFactory, final String query, final long maxRowCount)
  {
    try (final Planner planner = plannerFactory.createPlanner()) {
      synchronized (lock) {
        ensure(State.NEW);
        this.plannerResult = Calcites.plan(planner, query);
        this.maxRowCount = maxRowCount;
        this.query = query;
        this.signature = Meta.Signature.create(
            createColumnMetaData(plannerResult.rowType()),
            query,
            new ArrayList<AvaticaParameter>(),
            Meta.CursorFactory.ARRAY,
            Meta.StatementType.SELECT // We only support SELECT
        );
        this.state = State.PREPARED;
      }
    }
    catch (Exception e) {
      throw Throwables.propagate(e);
    }

    return this;
  }

  public DruidStatement execute()
  {
    synchronized (lock) {
      ensure(State.PREPARED);

      final Sequence<Object[]> baseSequence = plannerResult.run();

      // We can't apply limits greater than Integer.MAX_VALUE, ignore them.
      final Sequence<Object[]> retSequence =
          maxRowCount >= 0 && maxRowCount <= Integer.MAX_VALUE
          ? Sequences.limit(baseSequence, (int) maxRowCount)
          : baseSequence;

      yielder = Yielders.each(retSequence);
      state = State.RUNNING;

      return this;
    }
  }

  public String getConnectionId()
  {
    return connectionId;
  }

  public int getStatementId()
  {
    return statementId;
  }

  public String getQuery()
  {
    synchronized (lock) {
      ensure(State.PREPARED, State.RUNNING, State.DONE);
      return query;
    }
  }

  public Meta.Signature getSignature()
  {
    synchronized (lock) {
      ensure(State.PREPARED, State.RUNNING, State.DONE);
      return signature;
    }
  }

  public RelDataType getRowType()
  {
    synchronized (lock) {
      ensure(State.PREPARED, State.RUNNING, State.DONE);
      return plannerResult.rowType();
    }
  }

  public long getCurrentOffset()
  {
    synchronized (lock) {
      ensure(State.RUNNING, State.DONE);
      return offset;
    }
  }

  public boolean isDone()
  {
    synchronized (lock) {
      return state == State.DONE;
    }
  }

  public Meta.Frame nextFrame(final long fetchOffset, final int fetchMaxRowCount)
  {
    synchronized (lock) {
      ensure(State.RUNNING);
      Preconditions.checkState(fetchOffset == offset, "fetchOffset[%,d] != offset[%,d]", fetchOffset, offset);

      try {
        final List<Object> rows = new ArrayList<>();
        while (!yielder.isDone() && (fetchMaxRowCount < 0 || offset < fetchOffset + fetchMaxRowCount)) {
          rows.add(yielder.get());
          yielder = yielder.next(null);
          offset++;
        }

        final boolean done = yielder.isDone();
        if (done) {
          close();
        }

        return new Meta.Frame(fetchOffset, done, rows);
      }
      catch (Throwable t) {
        try {
          close();
        }
        catch (Throwable t1) {
          t.addSuppressed(t1);
        }
        throw t;
      }
    }
  }

  @Override
  public void close()
  {
    synchronized (lock) {
      state = State.DONE;

      if (yielder != null) {
        Yielder<Object[]> theYielder = this.yielder;
        this.yielder = null;

        // Put the close last, so any exceptions it throws are after we did the other cleanup above.
        try {
          theYielder.close();
        }
        catch (IOException e) {
          throw Throwables.propagate(e);
        }
      }
    }
  }

  @GuardedBy("lock")
  private void ensure(final State... desiredStates)
  {
    for (State desiredState : desiredStates) {
      if (state == desiredState) {
        return;
      }
    }
    throw new ISE("Invalid action for state[%s]", state);
  }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: lute
 * Date: 27/12/15
 * Time: 17:31
 */

namespace Mo\UserBundle\Model;

interface MailComposerInterface
{
    public function __construct($render, $from);

    public function compose(MailInterface $mail);

}


text:
include(joinpath(dirname(@__FILE__), "ExtensionTests.jl"))

Docile.Cache.register_module(joinpath(dirname(@__FILE__), "ExtensionTests.jl"))

import ExtensionTests
import Docile: Cache, Formats

Cache.getmeta(ExtensionTests)[:format] = Formats.PlaintextFormatter

facts("Extensions.") do

    context("!!set and !!get") do

        @fact Cache.getparsed(qs(ExtensionTests, :set_and_get)...)      --> "test"
        @fact Cache.getmeta(qs(ExtensionTests, :set_and_get)...)[:name] --> "test"

    end

    context("!!var") do

        @fact Cache.getparsed(qs(ExtensionTests, :var)...)      --> "test"
        @fact Cache.getmeta(qs(ExtensionTests, :var)...)[:name] --> "test"

    end

    context("!!summary") do

        @fact Cache.getparsed(qs(ExtensionTests, :summary)...)         --> "summary"
        @fact Cache.getmeta(qs(ExtensionTests, :summary)...)[:summary] --> "summary"

    end

    context("!!longform") do

        @fact Cache.getparsed(qs(ExtensionTests, :longform)...) --> "..."

    end

    context("!!include") do

        @fact Cache.getparsed(qs(ExtensionTests, :includes)...)         --> "one\n"
        @fact Cache.getparsed(qs(ExtensionTests, :set_includes_get)...) --> " one\n test"

    end

    context("!!include with metas") do

        @fact Cache.getparsed(qs(ExtensionTests, :includes_nested)...) -->
            string("Text with Outer\nLevel1\nLevel2\nLevel3\nLevel4\nLevel5\nLevel6\n\n",
                   "Some unicode 所以不多说了 бежал мета\n Get the inner again: бежал мета")

        @fact Cache.getmeta(qs(ExtensionTests, :includes_nested)...)[:level6] --> "Level6"

    end

end


text:
package io.github.stormcloud_dev.stormcloud.object.monster;

public class Naut extends Monster {

    public Naut(int x, int y, String name, boolean locked, String code, double scaleX, double scaleY, long colour, double rotation) {
        super(x, y, name, locked, code, scaleX, scaleY, colour, rotation);
        setZRange(80);
        initNaut();
    }

    public Naut(int x, int y) {
        super(x, y);
        setZRange(80);
        initNaut();
    }

    private void initNaut() {
        setName("Whorl");
        setCanJump(true);
        setDamage(17F * getEnemyBuff() * getDamageCoefficient());
    }
}


text:
package org.opencypher.grammar;

import java.util.Arrays;
import java.util.List;

import org.hamcrest.Matcher;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.opencypher.grammar.CodePointSet.codePoints;
import static org.opencypher.grammar.CodePointSet.range;
import static org.opencypher.grammar.CodePointSet.single;
import static org.opencypher.grammar.CodePointSet.union;

@RunWith(Enclosed.class)
public class CodePointSetTest
{
    @RunWith(Parameterized.class)
    public static class Parser
    {
        private final ParsingTest test;

        public Parser( ParsingTest test )
        {
            this.test = test;
        }

        @Test
        public void parse() throws Exception
        {
            test.parsing();
        }

        @Parameterized.Parameters(name = "{0}")
        public static List<Object[]> tests()
        {
            return Arrays.asList(
                    parses( "[a]", single( 'a' ) ),
                    parses( "[a-z]", range( 'a', 'z' ) ),
                    parses( "[a-z0-9]", range( 'a', 'z' ), range( '0', '9' ) ),
                    parses( "[aoueiy]", codePoints( 'a', 'o', 'u', 'e', 'i', 'y' ) ),
                    parses( "[\\a]", single( 0x07 ) ),
                    parses( "[\\b]", single( '\b' ) ),
                    parses( "[\\e]", single( 0x1B ) ),
                    parses( "[\\f]", single( '\f' ) ),
                    parses( "[\\n]", single( '\n' ) ),
                    parses( "[\\r]", single( '\r' ) ),
                    parses( "[\\t]", single( '\t' ) ),
                    parses( "[\\v]", single( 0x0B ) ),
                    fails( "[a-]", containsString( "cannot end in '-' or '\\'" ) ),
                    fails( "[a--b]", containsString( "'-' may not follow '-'" ) ),
                    fails( "[-z]", containsString( "'-' must be preceded by single char" ) ),
                    fails( "[\\]", containsString( "cannot end in '-' or '\\'" ) ),
                    fails( "[\\x]", containsString( "Invalid escape character" ) ),
                    fails( "a-z", containsString( "must be enclosed in '[...]" ) ),
                    fails( "[a-z", containsString( "must be enclosed in '[...]" ) ),
                    fails( "a-z]", containsString( "must be enclosed in '[...]" ) )
            );
        }
    }

    static abstract class ParsingTest
    {
        final String input;

        ParsingTest( String input )
        {
            this.input = input;
        }

        abstract void parsing();

        @Override
        public String toString()
        {
            switch ( getClass().getEnclosingMethod().getName() )
            {
            case "parses":
                return "should parse \"" + input + '"';
            case "fails":
                return "should fail to parse \"" + input + '"';
            default:
                return '"' + input + '"';
            }
        }
    }

    private static Object[] parses( String input, CodePointSet... expected )
    {
        return new Object[]{new ParsingTest( input )
        {
            @Override
            void parsing()
            {
                assertParses( input, expected );
            }
        }};
    }

    private static Object[] fails( String input, Matcher<String> message )
    {
        return new Object[]{new ParsingTest( input )
        {
            @Override
            void parsing()
            {
                assertParsingFails( input, message );
            }
        }};
    }

    static void assertParses( String input, CodePointSet... expected )
    {
        assertEquals( union( expected ), CodePointSet.parse( input ) );
    }

    static void assertParsingFails( String input, Matcher<String> message )
    {
        try
        {
            CodePointSet.parse( input );
        }
        catch ( IllegalArgumentException e )
        {
            assertThat( e.getMessage(), message );
        }
    }
}


text:
package com.epam.catgenome.entity.blast;

public enum BlastDatabaseSource {
    CUSTOM(1),
    NCBI(2);

    private Long sourceId;

    BlastDatabaseSource(final long sourceId) {
        this.sourceId = sourceId;
    }

    public Long getSourceId() {
        return sourceId;
    }

    /**
     * @param sourceId
     * @return a {@code BlastDatabaseSource} instance corresponding to the input ID
     */
    public static BlastDatabaseSource getSourceById(final Long sourceId) {
        for (BlastDatabaseSource source : BlastDatabaseSource.values()) {
            if (source.getSourceId().equals(sourceId)) {
                return source;
            }
        }
        throw new IllegalArgumentException("Invalid Blast database source ID");
    }
}


text:
module ResultWorthy.Tests.Util where

import ResultWorthy.Util
import Test.HUnit

tests = TestLabel "The Util Tests" $ TestList [
          TestLabel "withIndeces" $ TestCase
            $ assertEqual "Arrays should be equal"
              (withIndeces ["foo", "bar", "baz", "bong"])
              [(0, "foo"), (1, "bar"), (2, "baz"), (3, "bong")]
          ,
          TestLabel "trimLeadingWhitespace" $ TestCase
            $ assertEqual "Output should make sense"
              [" foo", "bar", "       baz"]
              (trimLeadingWhitespace ["   foo", " bar", "         baz"])
        ]


text:
ofxTCPServer::ofxTCPServer(){
	verbose		= true;
	connected	= false;
	count		= 0;
	port		= 0;
	str			= "";

	TCPConnections = new ofxTCPClient[TCP_MAX_CLIENTS];
}

//--------------------------
ofxTCPServer::~ofxTCPServer(){
	close();
}

//--------------------------
void ofxTCPServer::setVerbose(bool _verbose){
	verbose = _verbose;
}

//--------------------------
bool ofxTCPServer::setup(int _port, bool blocking){
	if( !TCPServer.Create() ){
		if(verbose)printf("ofxTCPServer: create() failed\n");
		return false;
	}
	if( !TCPServer.Bind(_port) ){
		if(verbose)printf("ofxTCPServer: bind(port = %i) failed\n", _port);
		return false;
	}

	connected		= true;
	port			= _port;
	bClientBlocking = blocking;

	startThread(true, false);
	return true;
}

//--------------------------
bool ofxTCPServer::close(){

	if(!connected) return true;

	for(int i = 0; i < count; i++){
		TCPConnections[i].close();
	}

	stopThread(); //stop the thread

	if( !TCPServer.Close() ){
		if(verbose)printf("ofxTCPServer: unable to close connection\n");
		return false;
	}else{
		connected = false;
		return true;
	}
}

//--------------------------
bool ofxTCPServer::disconnectClient(int clientID){
	if( !isClientSetup(clientID) ){
		if(verbose)printf("ofxTCPServer: client %i doesn't exist\n", clientID);
		return false;
	}
	else if(TCPConnections[clientID].close()){
		return true;
	}
	return false;
}

//--------------------------
bool ofxTCPServer::send(int clientID, string message){
	if( !isClientSetup(clientID) ){
		if(verbose)printf("ofxTCPServer: client %i doesn't exist\n", clientID);
		return false;
	}
	else{
		TCPConnections[clientID].send(message);
		return true;
	}
}

//--------------------------
bool ofxTCPServer::sendToAll(string message){
	if(count == 0) return false;

	for(int i = 0; i < count; i++){
		if(TCPConnections[i].isConnected())TCPConnections[i].send(message);
	}
	return true;
}

//--------------------------
string ofxTCPServer::receive(int clientID){
	if( !isClientSetup(clientID) ){
		if(verbose)printf("ofxTCPServer: client %i doesn't exist\n", clientID);
		return "client doesn't exist";
	}

	return TCPConnections[clientID].receive();
}

//--------------------------
bool ofxTCPServer::sendRawBytes(int clientID, const char * rawBytes, const int numBytes){
	if( !isClientSetup(clientID) ){
		if(verbose)printf("ofxTCPServer: client %i doesn't exist\n", clientID);
		return false;
	}
	else{
		return TCPConnections[clientID].sendRawBytes(rawBytes, numBytes);
	}
}

//--------------------------
bool ofxTCPServer::sendRawBytesToAll(const char * rawBytes, const int numBytes){
	if(count == 0 || numBytes <= 0) return false;

	for(int i = 0; i < count; i++){
		if(TCPConnections[i].isConnected())TCPConnections[i].sendRawBytes(rawBytes, numBytes);
	}
	return true;
}

//--------------------------
int ofxTCPServer::getNumReceivedBytes(int clientID){
	if( !isClientSetup(clientID) ){
		if(verbose)printf("ofxTCPServer: client %i doesn't exist\n", clientID);
		return 0;
	}

	return TCPConnections[clientID].getNumReceivedBytes();
}

//--------------------------
int ofxTCPServer::receiveRawBytes(int clientID, char * receiveBytes,  int numBytes){
	if( !isClientSetup(clientID) ){
		if(verbose)printf("ofxTCPServer: client %i doesn't exist\n", clientID);
		return 0;
	}

	return TCPConnections[clientID].receiveRawBytes(receiveBytes, numBytes);
}

//--------------------------
int ofxTCPServer::getClientPort(int clientID){
	if( !isClientSetup(clientID) ){
		if(verbose)printf("ofxTCPServer: client %i doesn't exist\n", clientID);
		return 0;
	}
	else return TCPConnections[clientID].getPort();
}

//--------------------------
string ofxTCPServer::getClientIP(int clientID){
	if( !isClientSetup(clientID) ){
		if(verbose)printf("ofxTCPServer: client %i doesn't exist\n", clientID);
		return "000.000.000.000";
	}
	else return TCPConnections[clientID].getIP();
}

//--------------------------
int ofxTCPServer::getNumClients(){
	return count;
}

//--------------------------
int ofxTCPServer::getPort(){
	return port;
}

//--------------------------
bool ofxTCPServer::isConnected(){
	return connected;
}

//--------------------------
bool ofxTCPServer::isClientSetup(int clientID){
	return (clientID < count && clientID < TCP_MAX_CLIENTS);
}

//--------------------------
bool ofxTCPServer::isClientConnected(int clientID){
	return isClientSetup(clientID) && TCPConnections[clientID].isConnected();
}

//don't call this
//--------------------------
void ofxTCPServer::threadedFunction(){

	while( isThreadRunning() ){

		if(count == TCP_MAX_CLIENTS){
			if(verbose)printf("ofxTCPServer: reached max connected clients! \nofxTCPServer: no more connections accepted\n");
			break;
		}

		if( !TCPServer.Listen(TCP_MAX_CLIENTS) ){
			if(verbose)printf("ofxTCPServer: Listen() failed\n");
		}

		if( !TCPServer.Accept(TCPConnections[count].TCPClient) ){
			if(verbose)printf("ofxTCPServer: Accept() failed\n");
			continue;
		}else{
			TCPConnections[count].setup(count, bClientBlocking);
			count++;
			if(verbose)printf("ofxTCPServer: client %i connected on port %i\n", count, TCPConnections[count].getPort());
		}
	}
	if(verbose)printf("ofxTCPServer: listen thread ended\n");
}


text:
<?php

namespace App\Models\Auth\Traits\Relationship;

use App\Models\System\Session;
use App\Models\Auth\SocialAccount;
use App\Models\Auth\PasswordHistory;

/**
 * Class UserRelationship.
 */
trait UserRelationship
{
    /**
     * @return mixed
     */
    public function providers()
    {
        return $this->hasMany(SocialAccount::class);
    }

    /**
     * @return mixed
     */
    public function sessions()
    {
        return $this->hasMany(Session::class);
    }

    /**
     * @return mixed
     */
    public function passwordHistories()
    {
        return $this->hasMany(PasswordHistory::class);
    }
}


text:
Tutorial
========

This is a tutorial

.. automodule:: pywatson


text:
from java import awt
from java.awt import image
from javax import swing
from geoscript import geom, proj, style
from org.geotools.geometry.jts import ReferencedEnvelope
from org.geotools.map import DefaultMapContext, DefaultMapLayer
from org.geotools.renderer.lite import StreamingRenderer
from org.geotools.swing import JMapPane
from org.geotools.swing.action import *
from org.geotools.swing.control import *

class MapWindow:
   """
   Renderer that produces a map window based on JMapPane.

   The map window provides basic map viewing controls such as pan, zoom, etc..
   """

   def __init__(self):
      pass

   def render(self, layers, styles, bounds, size, **options):
      self.map = DefaultMapContext(bounds.proj._crs)
      self.map.setAreaOfInterest(bounds)

      for i in range(len(layers)):
        self.map.addLayer(DefaultMapLayer(layers[i]._source,styles[i]._style()))

      w,h = (size[0], size[1])

      hints = {}
      hints [awt.RenderingHints.KEY_ANTIALIASING] = awt.RenderingHints.VALUE_ANTIALIAS_ON

      renderer = StreamingRenderer()
      renderer.java2DHints = awt.RenderingHints(hints)

      mappane = JMapPane(self.map)
      mappane.renderer = renderer
      mappane.size = (w,h)
      mappane.visible = True

      f = Frame(mappane)
      f.setSize(w,h)
      f.setVisible(True)

   def dispose(self):
      if self.map:
         self.map.dispose()

class Frame(swing.JFrame):

   def __init__(self, mappane):
      self.init(mappane)

   def init(self,mappane):
      self.add(mappane,awt.BorderLayout.CENTER)

      statusBar = JMapStatusBar.createDefaultStatusBar(mappane)
      #statusBar.addItem(CRSStatusBarItem(mappane))
      #statusBar.addItem(ExtentStatusBarItem(mappane))
      self.add(statusBar, awt.BorderLayout.SOUTH)

      toolBar = swing.JToolBar()
      toolBar.setOrientation(swing.JToolBar.HORIZONTAL)
      toolBar.setFloatable(False)

      cursorToolGrp = swing.ButtonGroup()
      zoomInBtn = swing.JButton(ZoomInAction(mappane))
      toolBar.add(zoomInBtn)
      cursorToolGrp.add(zoomInBtn)

      zoomOutBtn = swing.JButton(ZoomOutAction(mappane))
      toolBar.add(zoomOutBtn)
      cursorToolGrp.add(zoomOutBtn)

      toolBar.addSeparator()

      panBtn = swing.JButton(PanAction(mappane))
      toolBar.add(panBtn)
      cursorToolGrp.add(panBtn)

      toolBar.addSeparator()

      resetBtn = swing.JButton(ResetAction(mappane))
      toolBar.add(resetBtn)

      toolBar.addSeparator()

      infoBtn = swing.JButton(InfoAction(mappane))
      toolBar.add(infoBtn)

      self.add( toolBar, awt.BorderLayout.NORTH )


text:
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>Archetype Created Web Application</display-name>
    <listener>
        <listener-class>
            org.tinygroup.weblayer.ApplicationStartupListener
        </listener-class>
    </listener>
    <filter>
        <filter-name>TinyFilter</filter-name>
        <filter-class>org.tinygroup.weblayer.TinyHttpFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>TinyFilter</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>
</web-app>


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.ai.textanalytics;

import com.azure.ai.textanalytics.models.DetectedLanguage;
import com.azure.core.credential.AzureKeyCredential;

/**
 * Sample demonstrates how to detect the language of document.
 */
public class DetectLanguage {
    /**
     * Main method to invoke this demo about how to detect the language of document.
     *
     * @param args Unused arguments to the program.
     */
    public static void main(String[] args) {
        // Instantiate a client that will be used to call the service.
        TextAnalyticsClient client = new TextAnalyticsClientBuilder()
                                         .credential(new AzureKeyCredential("{key}"))
                                         .endpoint("{endpoint}")
                                         .buildClient();

        // The document that needs be analyzed.
        String document = "hello world";

        final DetectedLanguage detectedLanguage = client.detectLanguage(document);
        System.out.printf("Detected primary language: %s, ISO 6391 name: %s, confidence score: %f.%n",
            detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getConfidenceScore());
    }
}


text:
angular-ms-time
===============

An Angular.js directive that binds to a milliseconds model
and shows time formatted as hr:min:sec

Add the directive to an element, and pass in your millisecond model.

**If the element is an ```input``` or ``textarea``, you get two-way binding:**
The element will display the milliseconds converted
to human-readable time. When a user updates the time, the directive will check
if they entered a valid time on element blur. If it is invalid, the element will
get the ng-invalid class, and not update the model. Otherwise, the model will be
updated with the correct number of milliseconds. Changing the model from somewhere
else will also update the time displayed.

**If you add the directive to a non-input element (like a ```p```), you get one-way binding:**
The element will simply display the time
in the element's text area, and will update whenever the model is changed.

Get started
-----------

Download the repo directly, or use bower:
```
bower install angular-ms-time --save
```

Add ```angular-ms-time.js``` to your index.html.

Add ```angularMSTime``` as a module dependency for your module.

```JavaScript
angular.module('myApp', [
    ...,
    angularMSTime
  ])
```

Add the directive to an element
-------------------------------
On any element - ```input```, ```textarea```, or other (like ```p```),
add the ```ms-time``` element, and pass in the millisecond model you want to
bind to.

Examples:
```html
<p ms-time="myCtrl.milliseconds"></p>
```

```html
<input type="text" ms-time="myCtrl.milliseconds"></p>
```

Add text before and/or after the time
-------------------------------------
Since angular-ms-time replaces all the text in an element, you may want
to add some text before or after (like "time left: 1:02").

Add the attributes ```ms-time-pre``` or ```ms-time-post```
with your text and that text will be added to the element. Note that this only
works with non-input elements.

Examples:
```html
<p ms-time="myCtrl.milliseconds" ms-time-pre="Time: "></p>
```

```html
<p ms-time="myCtrl.milliseconds" ms-time-pre="There is " ms-time-post=" remaining"></p>
```

Example
-------
To see it in action, check out
[prompt](http://prompt.whentheresawill.net "prompt.whentheresawill.net"),
live or on
[github](http://github.com/whenther/prompt "whenther/prompt"),
an online teleprompter that scrolls a text document over a given amount of time.


text:
.class public Lcom/htc/protobuf/Descriptors$DescriptorValidationException;
.super Ljava/lang/Exception;
.source "Descriptors.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/htc/protobuf/Descriptors;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x9
    name = "DescriptorValidationException"
.end annotation

# static fields
.field private static final serialVersionUID:J = 0x4fccd5afd98283ccL

# instance fields
.field private final description:Ljava/lang/String;

.field private final name:Ljava/lang/String;

.field private final proto:Lcom/htc/protobuf/Message;

# direct methods
.method private constructor <init>(Lcom/htc/protobuf/Descriptors$FileDescriptor;Ljava/lang/String;)V
    .locals 2
    .parameter "problemDescriptor"
    .parameter "description"

    .prologue
    .line 1903
    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    invoke-virtual {p1}, Lcom/htc/protobuf/Descriptors$FileDescriptor;->getName()Ljava/lang/String;

    move-result-object v1

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v1, ": "

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0, p2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    invoke-direct {p0, v0}, Ljava/lang/Exception;-><init>(Ljava/lang/String;)V

    .line 1908
    invoke-virtual {p1}, Lcom/htc/protobuf/Descriptors$FileDescriptor;->getName()Ljava/lang/String;

    move-result-object v0

    iput-object v0, p0, Lcom/htc/protobuf/Descriptors$DescriptorValidationException;->name:Ljava/lang/String;

    .line 1909
    invoke-virtual {p1}, Lcom/htc/protobuf/Descriptors$FileDescriptor;->toProto()Lcom/htc/protobuf/DescriptorProtos$FileDescriptorProto;

    move-result-object v0

    iput-object v0, p0, Lcom/htc/protobuf/Descriptors$DescriptorValidationException;->proto:Lcom/htc/protobuf/Message;

    .line 1910
    iput-object p2, p0, Lcom/htc/protobuf/Descriptors$DescriptorValidationException;->description:Ljava/lang/String;

    .line 1911
    return-void
.end method

.method synthetic constructor <init>(Lcom/htc/protobuf/Descriptors$FileDescriptor;Ljava/lang/String;Lcom/htc/protobuf/Descriptors$1;)V
    .locals 0
    .parameter "x0"
    .parameter "x1"
    .parameter "x2"

    .prologue
    .line 1848
    invoke-direct {p0, p1, p2}, Lcom/htc/protobuf/Descriptors$DescriptorValidationException;-><init>(Lcom/htc/protobuf/Descriptors$FileDescriptor;Ljava/lang/String;)V

    return-void
.end method

.method private constructor <init>(Lcom/htc/protobuf/Descriptors$GenericDescriptor;Ljava/lang/String;)V
    .locals 1
    .parameter "problemDescriptor"
    .parameter "description"

    .prologue
    .line 1883
    const/4 v0, 0x0

    invoke-direct {p0, p1, p2, v0}, Lcom/htc/protobuf/Descriptors$DescriptorValidationException;-><init>(Lcom/htc/protobuf/Descriptors$GenericDescriptor;Ljava/lang/String;Ljava/lang/Throwable;)V

    .line 1884
    return-void
.end method

.method synthetic constructor <init>(Lcom/htc/protobuf/Descriptors$GenericDescriptor;Ljava/lang/String;Lcom/htc/protobuf/Descriptors$1;)V
    .locals 0
    .parameter "x0"
    .parameter "x1"
    .parameter "x2"

    .prologue
    .line 1848
    invoke-direct {p0, p1, p2}, Lcom/htc/protobuf/Descriptors$DescriptorValidationException;-><init>(Lcom/htc/protobuf/Descriptors$GenericDescriptor;Ljava/lang/String;)V

    return-void
.end method

.method private constructor <init>(Lcom/htc/protobuf/Descriptors$GenericDescriptor;Ljava/lang/String;Ljava/lang/Throwable;)V
    .locals 2
    .parameter "problemDescriptor"
    .parameter "description"
    .parameter "cause"

    .prologue
    .line 1890
    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    invoke-interface {p1}, Lcom/htc/protobuf/Descriptors$GenericDescriptor;->getFullName()Ljava/lang/String;

    move-result-object v1

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v1, ": "

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0, p2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    invoke-direct {p0, v0, p3}, Ljava/lang/Exception;-><init>(Ljava/lang/String;Ljava/lang/Throwable;)V

    .line 1895
    invoke-interface {p1}, Lcom/htc/protobuf/Descriptors$GenericDescriptor;->getFullName()Ljava/lang/String;

    move-result-object v0

    iput-object v0, p0, Lcom/htc/protobuf/Descriptors$DescriptorValidationException;->name:Ljava/lang/String;

    .line 1896
    invoke-interface {p1}, Lcom/htc/protobuf/Descriptors$GenericDescriptor;->toProto()Lcom/htc/protobuf/Message;

    move-result-object v0

    iput-object v0, p0, Lcom/htc/protobuf/Descriptors$DescriptorValidationException;->proto:Lcom/htc/protobuf/Message;

    .line 1897
    iput-object p2, p0, Lcom/htc/protobuf/Descriptors$DescriptorValidationException;->description:Ljava/lang/String;

    .line 1898
    return-void
.end method

.method synthetic constructor <init>(Lcom/htc/protobuf/Descriptors$GenericDescriptor;Ljava/lang/String;Ljava/lang/Throwable;Lcom/htc/protobuf/Descriptors$1;)V
    .locals 0
    .parameter "x0"
    .parameter "x1"
    .parameter "x2"
    .parameter "x3"

    .prologue
    .line 1848
    invoke-direct {p0, p1, p2, p3}, Lcom/htc/protobuf/Descriptors$DescriptorValidationException;-><init>(Lcom/htc/protobuf/Descriptors$GenericDescriptor;Ljava/lang/String;Ljava/lang/Throwable;)V

    return-void
.end method

# virtual methods
.method public getDescription()Ljava/lang/String;
    .locals 1

    .prologue
    .line 1874
    iget-object v0, p0, Lcom/htc/protobuf/Descriptors$DescriptorValidationException;->description:Ljava/lang/String;

    return-object v0
.end method

.method public getProblemProto()Lcom/htc/protobuf/Message;
    .locals 1

    .prologue
    .line 1865
    iget-object v0, p0, Lcom/htc/protobuf/Descriptors$DescriptorValidationException;->proto:Lcom/htc/protobuf/Message;

    return-object v0
.end method

.method public getProblemSymbolName()Ljava/lang/String;
    .locals 1

    .prologue
    .line 1856
    iget-object v0, p0, Lcom/htc/protobuf/Descriptors$DescriptorValidationException;->name:Ljava/lang/String;

    return-object v0
.end method


text:
package com.facebook.buck.util;

import static org.hamcrest.Matchers.emptyString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

import com.facebook.buck.util.environment.Platform;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;

import org.junit.Test;

import java.nio.CharBuffer;

/**
 * Tests for {@link SimpleProcessListener}.
 */
public class SimpleProcessListenerTest {

  @Test
  public void echoTextReceivedOnStdout() throws Exception {
    ListeningProcessExecutor executor = new ListeningProcessExecutor();
    SimpleProcessListener listener = new SimpleProcessListener();
    ProcessExecutorParams params;
    if (Platform.detect() == Platform.WINDOWS) {
      params = ProcessExecutorParams.ofCommand("cmd.exe", "/c", "echo", "Hello");
    } else {
      params = ProcessExecutorParams.ofCommand("echo", "Hello");
    }
    ListeningProcessExecutor.LaunchedProcess process = executor.launchProcess(
        params,
        listener);
    int returnCode = executor.waitForProcess(process);
    assertThat(returnCode, equalTo(0));
    assertThat(listener.getStdout(), equalTo(String.format("Hello%n")));
    assertThat(listener.getStderr(), is(emptyString()));
  }

  @Test
  public void catTextSentToStdinReceivedOnStdout() throws Exception {
    ProcessExecutorParams params;
    if (Platform.detect() == Platform.WINDOWS) {
      params = ProcessExecutorParams.ofCommand(
          "python",
          "-c",
          "import sys, shutil; shutil.copyfileobj(sys.stdin, sys.stdout)");
    } else {
      params = ProcessExecutorParams.ofCommand("cat");
    }
    ListeningProcessExecutor executor = new ListeningProcessExecutor();
    SimpleProcessListener listener = new SimpleProcessListener(String.format("Meow%n"));
    ListeningProcessExecutor.LaunchedProcess process = executor.launchProcess(
        params,
        listener);
    process.wantWrite();
    int returnCode = executor.waitForProcess(process);
    assertThat(returnCode, equalTo(0));
    assertThat(listener.getStdout(), equalTo(String.format("Meow%n")));
    assertThat(listener.getStderr(), is(emptyString()));
  }

  @Test
  public void supplierBasedInput() throws Exception {
    ProcessExecutorParams params;
    if (Platform.detect() == Platform.WINDOWS) {
      params = ProcessExecutorParams.ofCommand(
          "python",
          "-c",
          "import sys, shutil; shutil.copyfileobj(sys.stdin, sys.stdout)");
    } else {
      params = ProcessExecutorParams.ofCommand("cat");
    }
    ListeningProcessExecutor executor = new ListeningProcessExecutor();
    SimpleProcessListener listener = new SimpleProcessListener(
        ImmutableList.of(
            CharBuffer.wrap("Meow"),
            CharBuffer.wrap("Wow")
        ).iterator(),
        Charsets.UTF_8);
    ListeningProcessExecutor.LaunchedProcess process = executor.launchProcess(
        params,
        listener);
    process.wantWrite();
    int returnCode = executor.waitForProcess(process);
    assertThat(returnCode, equalTo(0));
    assertThat(listener.getStdout(), equalTo(String.format("MeowWow")));
    assertThat(listener.getStderr(), is(emptyString()));
  }
}


text:
Arachne is a simplistic net & spider toolbox. It contains the utilities you might have use for when storing link data mined on the Internet. It can also be used to validate and normalize data.

This repository is going to be populated with a selection of restructured utilities that already live in the system ecology at [Jajja][1].

## Timeline

The project to gather and simplify tools currently used for crawling and handling net resources is ongoing. The current priority is:

* Documentation and examples
* URLs, Parameters (parsing and resolve)
* HTTP, Cookies, Proxies (possibly by wrapping an existing client)

[1]: http://www.jajja.com


text:
<!doctype html>

<meta charset="utf-8">
<title>Experimenting with Creative Technologies – Charlie Gerard</title>
<meta name="description" content="A few days ago, I gave a talk at a ThoughtWorks event about experimenting with Creative Technologies and why I believe it is very important...">
<meta name="keywords" content="technology, creative technologies, robots, robotics, hardware, art, programming, creative coding, innovation">

<meta name="twitter:title" content="Experimenting with Creative Technologies">
<meta name="twitter:description" content="A few days ago, I gave a talk at a ThoughtWorks event about experimenting with Creative Technologies and why I believe it is very important...">
<meta name="twitter:site" content="@devdevcharlie">
<meta name="twitter:creator" content="@devdevcharlie">

<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://charliegerard.github.io/blog/images/default-thumb.png">

<meta property="og:locale" content="en_US">
<meta property="og:type" content="article">
<meta property="og:title" content="Experimenting with Creative Technologies">
<meta property="og:description" content="A few days ago, I gave a talk at a ThoughtWorks event about experimenting with Creative Technologies and why I believe it is very important...">
<meta property="og:url" content="http://charliegerard.github.io/blog/Experimenting-Creative-Technologies/">
<meta property="og:site_name" content="Charlie Gerard">

<meta property="og:image" content="http://charliegerard.github.io/blog/images/default-thumb.png">

<link rel="canonical" href="http://charliegerard.github.io/blog/Experimenting-Creative-Technologies/">
<link href="http://charliegerard.github.io/blog/feed.xml" type="application/atom+xml" rel="alternate" title="Charlie Gerard Feed">

<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="http://charliegerard.github.io/blog/assets/css/main.css">

<meta http-equiv="cleartype" content="on">

<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700%7CPT+Serif:400,700,400italic' rel='stylesheet' type='text/css'>

<link rel="shortcut icon" href="http://charliegerard.github.io/blog/favicon.ico">

<link rel="shortcut icon" href="http://charliegerard.github.io/blog/favicon.png">

<link rel="apple-touch-icon-precomposed" href="http://charliegerard.github.io/blog/images/apple-touch-icon-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="72x72" href="http://charliegerard.github.io/blog/images/apple-touch-icon-72x72-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="114x114" href="http://charliegerard.github.io/blog/images/apple-touch-icon-114x114-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://charliegerard.github.io/blog/images/apple-touch-icon-144x144-precomposed.png">

		Charlie Gerard

About

All Posts

Portfolio

Charlie Gerard

Software Developer & Creative technologist, I am passionate about the mix of science, art and technology

   Email
   Twitter

   Google+

   Github

Experimenting with Creative Technologies

A few days ago, I gave a talk at a ThoughtWorks event about experimenting with Creative Technologies and why I believe it is very important.

I love experimenting with tech on my own time but I usually face comments like "But what is the business value?".

As much as I totally understand where people are coming from, I do believe that experimenting with a project that may not bring value, is in itself valuable.

The amount I have learnt on personal projects, building things that don't solve problems, has a lot of value to me, but not only to me.

As a field that is innovating and changing very fast, I believe that keeping up to date with new technologies is very important if you wanna stay competitive and if you want to grow as a developer.

Also, the more I experiment with devices or technologies, the more I start thinking about ideas that would actually solve problems.

For examples, when I bought a brain sensor, I wanted to pair it with the Sphero robotic ball to be able to make it roll with the movement of my eyes.
However, when I got the headset, I realised there was no JavaScript framework available with it (I've been mainly programming robots with Node.js so far…), so I started wondering how long it would actually get me to get something to work! :/

And then I realised there was a library allowing you to create Node.js addons for C++ libraries and this is exactly what I needed!
So I got to create the first JS framework for the EPOC brain sensor and this by itself was a great thing to learn!

But then, when I finally got the Sphero to move by looking left, a new idea came to my mind. I started thinking about building a brain keyboard; a screen-based keyboard on which you could select letters by moving your eyes and that could help so many disabled people!

Unfortunately, I didn't get enough time to work on this new idea yet, but my point is that I would have never thought of this idea if I didn't start by trying to move a robotic ball.

In my presentation, I added a few examples of where technology is used in fields or projects that many people may not find valuable but also examples where these same technologies are then used to solve real problems in innovative ways.

If you're interested in seeing them, here's the link to the slides:

Experimenting with Creative Technologies

Share on

       Twitter

       Facebook

       Google+

Experimenting with Creative Technologies was published on <time datetime="2016-03-23T00:00:00+01:00">March 23, 2016</time>.

You might also enjoy (View all posts)

Getting started with Pact testing

Control the Sphero and Parrot AR Drone with the Neurosky brain sensor in Cylon.js

Virtual Reality In the Browser with Three.JS

© 2017 Charlie Gerard. Powered by Jekyll using the Minimal Mistakes theme.

Please enable JavaScript to view the comments powered by Disqus.
comments powered by Disqus


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" android:layout_height="match_parent"
    android:orientation="horizontal">

    <ImageView android:id="@+id/iv_icon" android:layout_width="wrap_content"
        android:layout_height="match_parent" android:paddingTop="8dp" android:paddingBottom="8dp" />
    <View android:layout_width="0.5dp" android:layout_height="match_parent"
        android:background="#CDCDCD" />
</LinearLayout><!-- From: file:/Users/Logan/development/android/as_workspace/EaseChatDemo/easeUI/src/main/res/layout/ease_scroll_tab_item.xml -->


text:
using namespace lldb_private;

bool lldb_private::NameMatches(llvm::StringRef name, NameMatch match_type,
                               llvm::StringRef match) {
  switch (match_type) {
  case NameMatch::Ignore:
    return true;
  case NameMatch::Equals:
    return name == match;
  case NameMatch::Contains:
    return name.contains(match);
  case NameMatch::StartsWith:
    return name.startswith(match);
  case NameMatch::EndsWith:
    return name.endswith(match);
  case NameMatch::RegularExpression: {
    RegularExpression regex(match);
    return regex.Execute(name);
  }
  }
  return false;
}


text:
@implementation RNNTopTabsOptions

@end


text:
//go:build !ignore_autogenerated
// +build !ignore_autogenerated

// Code generated by conversion-gen. DO NOT EDIT.

package v1beta1

import (
	unsafe "unsafe"

	conversion "k8s.io/apimachinery/pkg/conversion"
	runtime "k8s.io/apimachinery/pkg/runtime"
	config "k8s.io/controller-manager/config"
)

func init() {
	localSchemeBuilder.Register(RegisterConversions)
}

// RegisterConversions adds conversion functions to the given scheme.
// Public to allow building arbitrary schemes.
func RegisterConversions(s *runtime.Scheme) error {
	if err := s.AddGeneratedConversionFunc((*ControllerLeaderConfiguration)(nil), (*config.ControllerLeaderConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_v1beta1_ControllerLeaderConfiguration_To_config_ControllerLeaderConfiguration(a.(*ControllerLeaderConfiguration), b.(*config.ControllerLeaderConfiguration), scope)
	}); err != nil {
		return err
	}
	if err := s.AddGeneratedConversionFunc((*config.ControllerLeaderConfiguration)(nil), (*ControllerLeaderConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_config_ControllerLeaderConfiguration_To_v1beta1_ControllerLeaderConfiguration(a.(*config.ControllerLeaderConfiguration), b.(*ControllerLeaderConfiguration), scope)
	}); err != nil {
		return err
	}
	if err := s.AddGeneratedConversionFunc((*LeaderMigrationConfiguration)(nil), (*config.LeaderMigrationConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_v1beta1_LeaderMigrationConfiguration_To_config_LeaderMigrationConfiguration(a.(*LeaderMigrationConfiguration), b.(*config.LeaderMigrationConfiguration), scope)
	}); err != nil {
		return err
	}
	if err := s.AddGeneratedConversionFunc((*config.LeaderMigrationConfiguration)(nil), (*LeaderMigrationConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error {
		return Convert_config_LeaderMigrationConfiguration_To_v1beta1_LeaderMigrationConfiguration(a.(*config.LeaderMigrationConfiguration), b.(*LeaderMigrationConfiguration), scope)
	}); err != nil {
		return err
	}
	return nil
}

func autoConvert_v1beta1_ControllerLeaderConfiguration_To_config_ControllerLeaderConfiguration(in *ControllerLeaderConfiguration, out *config.ControllerLeaderConfiguration, s conversion.Scope) error {
	out.Name = in.Name
	out.Component = in.Component
	return nil
}

// Convert_v1beta1_ControllerLeaderConfiguration_To_config_ControllerLeaderConfiguration is an autogenerated conversion function.
func Convert_v1beta1_ControllerLeaderConfiguration_To_config_ControllerLeaderConfiguration(in *ControllerLeaderConfiguration, out *config.ControllerLeaderConfiguration, s conversion.Scope) error {
	return autoConvert_v1beta1_ControllerLeaderConfiguration_To_config_ControllerLeaderConfiguration(in, out, s)
}

func autoConvert_config_ControllerLeaderConfiguration_To_v1beta1_ControllerLeaderConfiguration(in *config.ControllerLeaderConfiguration, out *ControllerLeaderConfiguration, s conversion.Scope) error {
	out.Name = in.Name
	out.Component = in.Component
	return nil
}

// Convert_config_ControllerLeaderConfiguration_To_v1beta1_ControllerLeaderConfiguration is an autogenerated conversion function.
func Convert_config_ControllerLeaderConfiguration_To_v1beta1_ControllerLeaderConfiguration(in *config.ControllerLeaderConfiguration, out *ControllerLeaderConfiguration, s conversion.Scope) error {
	return autoConvert_config_ControllerLeaderConfiguration_To_v1beta1_ControllerLeaderConfiguration(in, out, s)
}

func autoConvert_v1beta1_LeaderMigrationConfiguration_To_config_LeaderMigrationConfiguration(in *LeaderMigrationConfiguration, out *config.LeaderMigrationConfiguration, s conversion.Scope) error {
	out.LeaderName = in.LeaderName
	out.ResourceLock = in.ResourceLock
	out.ControllerLeaders = *(*[]config.ControllerLeaderConfiguration)(unsafe.Pointer(&in.ControllerLeaders))
	return nil
}

// Convert_v1beta1_LeaderMigrationConfiguration_To_config_LeaderMigrationConfiguration is an autogenerated conversion function.
func Convert_v1beta1_LeaderMigrationConfiguration_To_config_LeaderMigrationConfiguration(in *LeaderMigrationConfiguration, out *config.LeaderMigrationConfiguration, s conversion.Scope) error {
	return autoConvert_v1beta1_LeaderMigrationConfiguration_To_config_LeaderMigrationConfiguration(in, out, s)
}

func autoConvert_config_LeaderMigrationConfiguration_To_v1beta1_LeaderMigrationConfiguration(in *config.LeaderMigrationConfiguration, out *LeaderMigrationConfiguration, s conversion.Scope) error {
	out.LeaderName = in.LeaderName
	out.ResourceLock = in.ResourceLock
	out.ControllerLeaders = *(*[]ControllerLeaderConfiguration)(unsafe.Pointer(&in.ControllerLeaders))
	return nil
}

// Convert_config_LeaderMigrationConfiguration_To_v1beta1_LeaderMigrationConfiguration is an autogenerated conversion function.
func Convert_config_LeaderMigrationConfiguration_To_v1beta1_LeaderMigrationConfiguration(in *config.LeaderMigrationConfiguration, out *LeaderMigrationConfiguration, s conversion.Scope) error {
	return autoConvert_config_LeaderMigrationConfiguration_To_v1beta1_LeaderMigrationConfiguration(in, out, s)
}


text:
import {AnimationMetadata, AnimationMetadataType} from '@angular/animations';

import {buildAnimationAst} from '../../src/dsl/animation_ast_builder';
import {MockAnimationDriver} from '../../testing';

{
  describe('buildAnimationAst', () => {
    it('should build the AST without any errors and warnings', () => {
      const driver = new MockAnimationDriver();
      const errors: Error[] = [];
      const warnings: string[] = [];
      const animationAst = buildAnimationAst(
          driver, <AnimationMetadata>{
            animation: [{
              styles: {
                offset: null,
                styles: {backgroundColor: '#000'},
                type: AnimationMetadataType.Style
              },
              timings: {delay: 0, duration: 1000, easing: 'ease-in-out'},
              type: AnimationMetadataType.Animate
            }],
            options: null,
            selector: 'body',
            type: AnimationMetadataType.Query
          },
          errors, warnings);

      expect(errors).toEqual([]);
      expect(warnings).toEqual([]);
      expect(animationAst).toEqual(<ReturnType<typeof buildAnimationAst>>{
        type: 11,
        selector: 'body',
        limit: 0,
        optional: false,
        includeSelf: false,
        animation: {
          type: 4,
          timings: {delay: 0, duration: 1000, easing: 'ease-in-out'},
          style: {
            type: 6,
            styles: [new Map([['backgroundColor', '#000']])],
            easing: null,
            offset: null,
            containsDynamicStyles: false,
            options: null,
            isEmptyStep: false
          },
          options: null
        },
        originalSelector: 'body',
        options: {}
      });
    });
  });
}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('characters', '0006_modify_verbose_names'),
    ]

    operations = [
        migrations.CreateModel(
            name='Item',
            fields=[
                ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),
                ('name', models.CharField(max_length=200)),
                ('description', models.TextField()),
                ('value', models.IntegerField(default=0)),
                ('weight', models.IntegerField(default=1)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.AddField(
            model_name='character',
            name='inventory',
            field=models.ManyToManyField(to='characters.Item'),
            preserve_default=True,
        ),
    ]


text:
module Fog
  module Compute
    class Vsphere
      class Customvalues < Fog::Collection
        autoload :Customvalue, File.expand_path('../customvalue', __FILE__)

        model Fog::Compute::Vsphere::Customvalue

        attr_accessor :vm

        def all(filters = {})
          requires :vm
          case vm
            when Fog::Compute::Vsphere::Server
              load service.list_vm_customvalues(vm.id)
            else
            raise 'customvalues should have vm'
          end
        end

        def get(key)
          requires :vm
          case vm
            when Fog::Compute::Vsphere::Server
              load service.list_vm_customvalues(vm.id)
            else
            raise 'customvalues should have vm'
          end.find { | cv | cv.key == key }
        end
     end
    end
  end
end


text:
'use strict';

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;

exports.__esModule = true;
exports.get = get;
exports.getEnforcing = getEnforcing;

var _invariant = _interopRequireDefault(require("fbjs/lib/invariant"));

function get(name) {
  return null;
}

function getEnforcing(name) {
  const module = get(name);
  (0, _invariant.default)(module != null, "TurboModuleRegistry.getEnforcing(...): '" + name + "' could not be found. " + 'Verify that a module by this name is registered in the native binary.');
  return module;
}


text:
const AWS = require('aws-sdk');
const s3 = new AWS.S3({ region: process.env.AWS_REGION || 'us-west-2', signatureVersion: 'v4' });

import logger from './logger';

export const createMainBucket = async name => {
  // Create the parameters for calling createBucket
  const bucketParams = { Bucket: name };

  try {
    return await s3.headBucket(bucketParams).promise();
  } catch (error) {
    logger.error(error);

    try {
      return await s3.createBucket(bucketParams).promise();
    } catch (error) {
      logger.error(error);
      throw error;
    }
  }
};

export const createAttachment = async ({ name, filename, fileBuffer }) => {
  const params = {
    Bucket: name,
    Key: `${filename}`,
    ACL: 'public-read',
    Body: fileBuffer
  };

  try {
    logger.info('createAttachment - uploading file', { bucket: name });
    const data = await s3.putObject(params).promise();

    logger.info('createAttachment - uploaded file');

    return data;
  } catch (error) {
    logger.error('something bad happened', error);

    throw error;
  }
};

export const getAttachmentUrl = async ({ name, filename }) => {
  logger.info('getAttachmentUrl', { name, filename });

  const params = {
    Bucket: name,
    Key: `${filename}`
  };

  return await s3.getSignedUrl('getObject', params);
};

export const getAttachments = async ({ name, owner }) => {
  logger.info('getAttachments', { name, owner });

  const params = { Bucket: name, Prefix: `${owner}/` };
  logger.info('getAttachments - retrieving list');

  const { Contents: contents } = await s3.listObjectsV2(params).promise();
  const uploads = [];
  logger.info('getAttachments - retreieved list', contents);

  for (let i = 0; i < contents.length; i++) {
    const filename = contents[i].Key;
    const url = await getAttachmentUrl({ name, filename });

    uploads.push({ filename: filename.replace(`${owner}/`, ''), url });
  }

  return uploads;
};

module.exports = {
  createAttachment,
  createMainBucket,
  getAttachmentUrl,
  getAttachments
};


text:
function fruitLandings(house, trees, numOfFruits, ap, org) {
    var applesLanded = 0;
    var orangesLanded = 0;
    var apples = ap.map(function(val){
        var apple = parseInt(trees[0]) + parseInt(val)
        if ( apple >= house[0] && apple <= house[1] ) {
           applesLanded++;
       }
    });

    var oranges = org.map(function(val){
    var orange = parseInt(trees[1]) + parseInt(val)
    if ( orange >= house[0] && orange <= house[1] ) {
           orangesLanded++;
       }
    });
    return applesLanded + '\n' + orangesLanded;

}

function main() {
    var s_temp = readLine().split(' ');
    var s = parseInt(s_temp[0]);
    var t = parseInt(s_temp[1]);
    var a_temp = readLine().split(' ');
    var a = parseInt(a_temp[0]);
    var b = parseInt(a_temp[1]);
    var m_temp = readLine().split(' ');
    var m = parseInt(m_temp[0]);
    var n = parseInt(m_temp[1]);
    apple = readLine().split(' ');
    apple = apple.map(Number);
    orange = readLine().split(' ');
    orange = orange.map(Number);

    var res = fruitLandings(s_temp, a_temp, m_temp, apple, orange );
    console.log(res);

}


text:
<?php

namespace App\Models\Front\Locale;
use App\Models\Model;

class Country extends Model {
    public function getCountry($country_id) {
        $key = 'country.' . $country_id;
        $cachefile = Cache::get($key);

        if (is_bool($cachefile)):
            $query = DB::query("
				SELECT *
				FROM " . DB::prefix() . "country
				WHERE country_id = '" . (int)$country_id . "'
				AND status = '1'
			");

            if ($query->num_rows):
                $cachefile = $query->row;
                Cache::set($key, $cachefile);
            else:
                Cache::set($key, array());
                return array();
            endif;
        endif;

        return $cachefile;
    }

    public function getCountries() {
        $key = 'countries.all';
        $cachefile = Cache::get($key);

        if (is_bool($cachefile)):
            $query = DB::query("
				SELECT *
				FROM " . DB::prefix() . "country
				WHERE status = '1'
				ORDER BY name ASC
			");

            if ($query->num_rows):
                $cachefile = $query->rows;
                Cache::set($key, $cachefile);
            else:
                Cache::set($key, array());
                return array();
            endif;
        endif;

        return $cachefile;
    }
}


text:
types_of_people = 10
x = "There are #{types_of_people} types of people."
binary = "binary"
do_not = "don't"
y = "Those who know #{binary} and those who #{do_not}."

puts x
puts y

puts "I said: #{x}."
puts "I also said: '#{y}'."

hilarious = false
joke_evaluation = "Isn't that joke so funny?! #{hilarious}."

puts joke_evaluation

w = "This is the left side of..."
e = "a string with a right side."

puts w + e


text:
'''
Creates a few custom exceptions used throughout the application.
'''

class InvalidGamingSessionException(Exception):
    '''
    Session is invalid or does not exist.
    '''
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

class SessionNotAuthorizedException(Exception):
    '''
    Client is not authorized to access this session.
    '''
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

class TokenExpiredException(Exception):
    '''
    The token has expired.
    '''
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

class ClientExistsException(Exception):
    '''
    Client already exists in database.
    '''
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

class MissingHeadersException(Exception):
    '''
    Request is incomplete, with missing headers.
    '''
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)


text:
'use strict';

// Fixture for documentStore
var documentStoreSeed = {
  'test-doc': {
    documentId: 'test-doc',
    schemaName: 'prose-article',
    schemaVersion: '1.0.0',
    version: 1 // document has one change = version 1
  },
  'test-doc-2': {
    documentId: 'test-doc-2',
    schemaName: 'prose-article',
    schemaVersion: '1.0.0',
    version: 3 // document has 3 changes = version 3
  }
};

module.exports = documentStoreSeed;


text:
<?php

return 'Invalid return';


text:
<?php

namespace System\Web\Mvc;

class RedirectResult extends ActionResult {

    protected $httpContext;
    protected $location;
    protected $absolutePath;
    protected $https = false;

    public function __construct(\System\Web\HttpContext $httpContext, $location){
        if(is_string($location)){
            $this->httpContext = $httpContext;
            $this->location = $location;
        }
    }

    public function absolutePath($bool){
        $this->absolutePath = $bool;
        return $this;
    }

    public function https($bool){
        $this->https = $bool;
        return $this;
    }

    public function execute(){
        if($this->absolutePath){
            $host = $this->httpContext->getRequest()->getServer('HTTP_HOST');
            $port = $this->httpContext->getRequest()->getServer('SERVER_PORT');

            $location = (($this->https)? 'https' : 'http') . '://' . $host;
            if((int)$port != 80){
                $location .= ':'.$port;
            }
            $location .= '/'.ltrim($this->location, '/');
        }else{
            $location = $this->location;
        }
        return $this->httpContext->getResponse()->redirect($location, false);
    }
}


text:
<?php

namespace Archer\MeetEntryBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class GenderType extends AbstractType
{
        /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('abbreviation')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Archer\MeetEntryBundle\Entity\Gender'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'archer_meetentrybundle_gender';
    }
}


text:
'use strict';

var numberUtils = require('@nrk/yr-number-utils');

var RADIUS_UNITS = {
  feet: 20908800,
  yards: 6969600,
  miles: 3960,
  mi: 3960,
  kilometers: 6371,
  km: 6371,
  meters: 6371000,
  m: 6371000
};
var DEFAULT_UNIT = 'meters';

/**
 * Retrieve geographic distance between 'start' and 'end' lat/lon points
 * Options:
 *  - {Boolean} exact: return floating point value (default false)
 *  - {Boolean} format: return value + unit as string (default false)
 *  - {Number} limit: return boolean value if calculated distance is greater
 *  - {String} unit: return value in specified unit (default meters)
 *
 * @param {Object} start
 * @param {Object) end
 * @param {Object) options
 * @returns {Number}
 */
module.exports = function getDistance(start, end, options) {
  options = options || {};

  var earthRadius = getEarthRadius(options.unit);
  var latDelta = numberUtils.degreesToRadians(end.lat - start.lat);
  var latDeltaSin = Math.sin(latDelta * 0.5);
  var lonDelta = numberUtils.degreesToRadians(end.lon - start.lon);
  var lonDeltaSin = Math.sin(lonDelta * 0.5);
  var startLatRad = numberUtils.degreesToRadians(start.lat);
  var endLatRad = numberUtils.degreesToRadians(end.lat);
  var a = latDeltaSin * latDeltaSin + lonDeltaSin * lonDeltaSin * Math.cos(startLatRad) * Math.cos(endLatRad);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var dist = earthRadius * c;

  if (!options.exact) dist = Math.floor(dist);
  if (options.limit) return options.limit > dist ? true : false;
  if (options.format) dist = dist + ' ' + (options.unit || DEFAULT_UNIT);

  return dist;
};

/**
 * Retrieve radius of earth in specified 'unit'
 * @param {String} unit
 * @returns {Number}
 */
function getEarthRadius(unit) {
  unit = unit || DEFAULT_UNIT;
  unit = unit.toLowerCase();
  if (!RADIUS_UNITS[unit]) unit = DEFAULT_UNIT;

  return RADIUS_UNITS[unit];
}


text:
using MasterDevs.ChromeDevTools;

namespace MasterDevs.ChromeDevTools.Protocol.Runtime
{
	/// <summary>
	/// Issued when new execution context is created.
	/// </summary>
	[Event(ProtocolName.Runtime.ExecutionContextCreated)]
	public class ExecutionContextCreatedEvent
	{
		/// <summary>
		/// Gets or sets A newly created execution contex.
		/// </summary>
		public ExecutionContextDescription Context { get; set; }
	}
}


text:
#include "webrtc/modules/rtp_rtcp/source/playout_delay_oracle.h"

#include "webrtc/base/checks.h"
#include "webrtc/base/logging.h"
#include "webrtc/modules/rtp_rtcp/include/rtp_rtcp_defines.h"
#include "webrtc/modules/rtp_rtcp/source/rtp_header_extension.h"

namespace webrtc {

PlayoutDelayOracle::PlayoutDelayOracle()
    : high_sequence_number_(0),
      send_playout_delay_(false),
      ssrc_(0),
      min_playout_delay_ms_(-1),
      max_playout_delay_ms_(-1) {}

PlayoutDelayOracle::~PlayoutDelayOracle() {}

void PlayoutDelayOracle::UpdateRequest(uint32_t ssrc,
                                       PlayoutDelay playout_delay,
                                       uint16_t seq_num) {
  rtc::CritScope lock(&crit_sect_);
  RTC_DCHECK_LE(playout_delay.min_ms, kPlayoutDelayMaxMs);
  RTC_DCHECK_LE(playout_delay.max_ms, kPlayoutDelayMaxMs);
  RTC_DCHECK_LE(playout_delay.min_ms, playout_delay.max_ms);
  int64_t unwrapped_seq_num = unwrapper_.Unwrap(seq_num);
  if (playout_delay.min_ms >= 0 &&
      playout_delay.min_ms != min_playout_delay_ms_) {
    send_playout_delay_ = true;
    min_playout_delay_ms_ = playout_delay.min_ms;
    high_sequence_number_ = unwrapped_seq_num;
  }

  if (playout_delay.max_ms >= 0 &&
      playout_delay.max_ms != max_playout_delay_ms_) {
    send_playout_delay_ = true;
    max_playout_delay_ms_ = playout_delay.max_ms;
    high_sequence_number_ = unwrapped_seq_num;
  }
  ssrc_ = ssrc;
}

// If an ACK is received on the packet containing the playout delay extension,
// we stop sending the extension on future packets.
void PlayoutDelayOracle::OnReceivedRtcpReportBlocks(
    const ReportBlockList& report_blocks) {
  rtc::CritScope lock(&crit_sect_);
  for (const RTCPReportBlock& report_block : report_blocks) {
    if ((ssrc_ == report_block.sourceSSRC) && send_playout_delay_ &&
        (report_block.extendedHighSeqNum > high_sequence_number_)) {
      send_playout_delay_ = false;
    }
  }
}

}  // namespace webrtc


text:
package com.ongres.pgdeploy.pgconfig.properties.exceptions;

public class PropertyNotFoundException extends Exception {
  public PropertyNotFoundException(String s) {
    super(s);
  }
}


text:
<?php

namespace Filters\Key;

use RValidate\Filters\Key\Regex;

class RegexTest extends \PHPUnit_Framework_TestCase
{
    public function testFilter_rightData()
    {
        $filter = new Regex('/foo_\d/');

        $data = [
            'foo_1' => 'bar',
            'foo_a' => 'baz'
        ];

        $result = $filter->filter($data);

        static::assertEquals(['foo_1' => 'bar'], $result);
    }

    public function testFilter_wrongData()
    {
        $filter = new Regex('/foo_\d/');

        $data = '';

        $result = $filter->filter($data);

        static::assertEquals([], $result);
    }
}


text:
"""Generic image operators"""
from .default import default_schedule as _default_schedule

def schedule_dilation2d_nchw(outs):
    """Schedule for dilation2d
    Parameters
    ----------
    outs : Array of Tensor
        The computation graph description of dilation2d
        in the format of an array of tensors.
    Returns
    -------
    sch : Schedule
        The computation schedule for the op.
    """
    return _default_schedule(outs, False)

def schedule_dilation2d_nhwc(outs):
    """Schedule for dilation2d
    Parameters
    ----------
    outs : Array of Tensor
        The computation graph description of dilation2d
        in the format of an array of tensors.
    Returns
    -------
    sch : Schedule
        The computation schedule for the op.
    """
    return _default_schedule(outs, False)


text:
url_get_id()
{

	url=$(printf $1)

	url=$(printf $url | sed --regexp-extended --expression='s/http:\/\/requestb.in\///g')
	url=$(printf $url | sed --regexp-extended --expression='s/https:\/\/requestb.in\///g')
	url=$(printf $url | sed --regexp-extended --expression='s/requestb.in\///g')
	url=$(printf $url | sed --regexp-extended --expression='s/\?.+$//g')

	printf $url

}

# Formatage de l'url
url_correction()
{

	url=$(printf $1)

	url=$(printf $url | sed --regexp-extended --expression='s/http:\/\/requestb.in\///g')
	url=$(printf $url | sed --regexp-extended --expression='s/https:\/\/requestb.in\///g')
	url=$(printf $url | sed --regexp-extended --expression='s/requestb.in\///g')
	url=$(printf $url | sed --regexp-extended --expression='s/\?.+$//g')

	url_prev=$(printf "aHR0cHM6Ly9yZXF1ZXN0Yi5pbi8K" | base64 -d)
	url_last=$(printf "P2Nvb2tpZT0K" | base64 -d)
	curl_last=$(printf "P2luc3BlY3QK" | base64 -d)

	url_curl=$(printf "%s%s%s" $url_prev $url $curl_last)
	url_hook=$(printf "%s%s%s" $url_prev $url $url_last)

	printf "%s|%s" $url_curl $url_hook

}

# Férification de l'ID
url_verification()
{

	url=$(printf $1)

	result=$(curl --request GET "$url" --silent)

	if [ $? -eq 0 ]; then

		if [[ "$result" == "Not found" ]]; then

			printf "false2"	# L'ID n'existe pas

		else

			if [[ "$(echo $result | sed --regexp-extended --expression='s/.+(<title>404 Not Found<\/title>
Not Found<\/h1>).+/\1/g')" == "<title>404 Not Found</title>
Not Found
"  ]]; then

				printf "false3"

			else

				printf "true"

			fi

		fi

	else

		printf "false1" # Hôte injoignable

	fi

}

# Formatage des infos concernant les urls
url_find()
{

	url=$(printf $1)

	content=$(curl --request GET "$url" --silent)

	echo "$content" |\
	sed --regexp-extended --silent --expression='/(span class="querystring")|()/p' |\
	sed --regexp-extended --expression='s/^.+\?//g' |\
	sed --regexp-extended --expression='s/^.+/time\t= /g' |\
	sed --regexp-extended --expression='s/cookie=/cookie\t= /g' |\
	sed --regexp-extended --expression='s/<\/span>$//g'

}


text:
namespace XenAdmin.Dialogs
{
    partial class NewDiskDialog
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NewDiskDialog));
            this.SrListBox = new XenAdmin.Controls.SrPicker();
            this.CloseButton = new System.Windows.Forms.Button();
            this.OkButton = new System.Windows.Forms.Button();
            this.NameTextBox = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.DescriptionTextBox = new System.Windows.Forms.TextBox();
            this.label3 = new System.Windows.Forms.Label();
            this.label1 = new System.Windows.Forms.Label();
            this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
            this.label4 = new System.Windows.Forms.Label();
            this.label6 = new System.Windows.Forms.Label();
            this.diskSpinner1 = new XenAdmin.Controls.DiskSpinner();
            this.tableLayoutPanel1.SuspendLayout();
            this.SuspendLayout();
            //
            // SrListBox
            //
            this.tableLayoutPanel1.SetColumnSpan(this.SrListBox, 3);
            this.SrListBox.Connection = null;
            resources.ApplyResources(this.SrListBox, "SrListBox");
            this.SrListBox.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
            this.SrListBox.Name = "SrListBox";
            this.SrListBox.NodeIndent = 3;
            this.SrListBox.RootAlwaysExpanded = false;
            this.SrListBox.ShowCheckboxes = false;
            this.SrListBox.ShowDescription = true;
            this.SrListBox.ShowImages = true;
            this.SrListBox.ShowRootLines = true;
            this.SrListBox.SelectedIndexChanged += new System.EventHandler(this.srListBox_SelectedIndexChanged);
            //
            // CloseButton
            //
            resources.ApplyResources(this.CloseButton, "CloseButton");
            this.CloseButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.CloseButton.Name = "CloseButton";
            this.CloseButton.UseVisualStyleBackColor = true;
            this.CloseButton.Click += new System.EventHandler(this.CloseButton_Click);
            //
            // OkButton
            //
            resources.ApplyResources(this.OkButton, "OkButton");
            this.OkButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.OkButton.Name = "OkButton";
            this.OkButton.UseVisualStyleBackColor = true;
            this.OkButton.Click += new System.EventHandler(this.OkButton_Click);
            //
            // NameTextBox
            //
            this.tableLayoutPanel1.SetColumnSpan(this.NameTextBox, 3);
            resources.ApplyResources(this.NameTextBox, "NameTextBox");
            this.NameTextBox.Name = "NameTextBox";
            this.NameTextBox.TextChanged += new System.EventHandler(this.NameTextBox_TextChanged);
            //
            // label2
            //
            resources.ApplyResources(this.label2, "label2");
            this.label2.Name = "label2";
            //
            // DescriptionTextBox
            //
            this.tableLayoutPanel1.SetColumnSpan(this.DescriptionTextBox, 3);
            resources.ApplyResources(this.DescriptionTextBox, "DescriptionTextBox");
            this.DescriptionTextBox.Name = "DescriptionTextBox";
            this.DescriptionTextBox.TextChanged += new System.EventHandler(this.NameTextBox_TextChanged);
            //
            // label3
            //
            resources.ApplyResources(this.label3, "label3");
            this.label3.Name = "label3";
            //
            // label1
            //
            resources.ApplyResources(this.label1, "label1");
            this.label1.Name = "label1";
            //
            // tableLayoutPanel1
            //
            resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
            this.tableLayoutPanel1.Controls.Add(this.CloseButton, 3, 6);
            this.tableLayoutPanel1.Controls.Add(this.label2, 0, 2);
            this.tableLayoutPanel1.Controls.Add(this.label1, 0, 4);
            this.tableLayoutPanel1.Controls.Add(this.NameTextBox, 1, 2);
            this.tableLayoutPanel1.Controls.Add(this.DescriptionTextBox, 1, 3);
            this.tableLayoutPanel1.Controls.Add(this.SrListBox, 1, 5);
            this.tableLayoutPanel1.Controls.Add(this.label3, 0, 3);
            this.tableLayoutPanel1.Controls.Add(this.label4, 0, 5);
            this.tableLayoutPanel1.Controls.Add(this.label6, 0, 1);
            this.tableLayoutPanel1.Controls.Add(this.OkButton, 2, 6);
            this.tableLayoutPanel1.Controls.Add(this.diskSpinner1, 1, 4);
            this.tableLayoutPanel1.Name = "tableLayoutPanel1";
            //
            // label4
            //
            resources.ApplyResources(this.label4, "label4");
            this.label4.Name = "label4";
            //
            // label6
            //
            resources.ApplyResources(this.label6, "label6");
            this.tableLayoutPanel1.SetColumnSpan(this.label6, 4);
            this.label6.Name = "label6";
            //
            // diskSpinner1
            //
            resources.ApplyResources(this.diskSpinner1, "diskSpinner1");
            this.tableLayoutPanel1.SetColumnSpan(this.diskSpinner1, 3);
            this.diskSpinner1.Name = "diskSpinner1";
            this.diskSpinner1.SelectedSizeChanged += new System.Action(this.diskSpinner1_SelectedSizeChanged);
            //
            // NewDiskDialog
            //
            this.AcceptButton = this.OkButton;
            resources.ApplyResources(this, "$this");
            this.CancelButton = this.CloseButton;
            this.Controls.Add(this.tableLayoutPanel1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
            this.Name = "NewDiskDialog";
            this.tableLayoutPanel1.ResumeLayout(false);
            this.tableLayoutPanel1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label1;
        private XenAdmin.Controls.SrPicker SrListBox;
        private System.Windows.Forms.Button CloseButton;
        private System.Windows.Forms.Button OkButton;
        private System.Windows.Forms.TextBox NameTextBox;
        private System.Windows.Forms.TextBox DescriptionTextBox;
        private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.Label label6;
        private Controls.DiskSpinner diskSpinner1;
    }
}


text:
<?php

use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\RequestContext;

/**
 * appProdUrlMatcher
 *
 * This class has been auto-generated
 * by the Symfony Routing Component.
 */
class appProdUrlMatcher extends Symfony\Bundle\FrameworkBundle\Routing\RedirectableUrlMatcher
{
    /**
     * Constructor.
     */
    public function __construct(RequestContext $context)
    {
        $this->context = $context;
    }

    public function match($pathinfo)
    {
        $allow = array();
        $pathinfo = rawurldecode($pathinfo);
        $context = $this->context;
        $request = $this->request;

        // user_practice_index
        if (rtrim($pathinfo, '/') === '') {
            if (substr($pathinfo, -1) !== '/') {
                return $this->redirect($pathinfo.'/', 'user_practice_index');
            }

            return array (  '_controller' => 'User\\PracticeBundle\\Controller\\MainController::homeAction',  '_route' => 'user_practice_index',);
        }

        // user_practice_homepage
        if ($pathinfo === '/home') {
            return array (  '_controller' => 'User\\PracticeBundle\\Controller\\MainController::homeAction',  '_route' => 'user_practice_homepage',);
        }

        throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException();
    }
}


text:
<?php

defined('C5_EXECUTE') or die("Access Denied.");

class Concrete5_Library_LogEntry extends Object {

	public function getType() {return $this->logType;}
	public function getText() {return $this->logText;}
	public function getID() {return $this->logID;}
	public function getUserID() { return $this->logUserID;}

	public function getTimestamp($type = 'system') {
		if(ENABLE_USER_TIMEZONES && $type == 'user') {
			$dh = Loader::helper('date');
			$timestamp = $dh->getLocalDateTime($this->timestamp);
		} else {
			$timestamp = $this->timestamp;
		}
		return $timestamp;
	}

	/**
	 * Returns a log entry by ID
	 */
	public static function getByID($logID) {
		$db = Loader::db();
		$r = $db->Execute("select * from Logs where logID = ?", array($logID));
		if ($r) {
			$row = $r->FetchRow();
			$obj = new LogEntry();
			$obj->setPropertiesFromArray($row);
			return $obj;
		}
	}

}