text:
@interface ESPTextFieldMaskerTests : XCTestCase

@property (nonatomic, strong) UITextField *defaultTextField;

@end

@implementation ESPTextFieldMaskerTests

- (void) setUp
{
    [super setUp];
    self.defaultTextField = [[UITextField alloc] init];

}

- (void) tearDown
{
    [super tearDown];
}

#pragma mark - Format Tests
- (void) testFormatInit
{
    ESPFormatter *formatter = [[ESPFormatter alloc] initWithMask:@"__/__/__" placeholder:@"_"];
    formatter.ignoredChars = @[@"/"];
    XCTAssertNotNil(formatter, @"Can't be nil at this point");
    XCTAssertNotNil(formatter.mask, @"Can't be nil at this point");
    XCTAssertNotNil(formatter.placeholder, @"Can't be nil at this point");
    XCTAssertNotNil(formatter.ignoredChars, @"Can't be nil at this point");
}

- (void) testFormatInitFail
{
    ESPFormatter *formatter = [[ESPFormatter alloc] initWithMask:nil placeholder:nil];
    XCTAssertNil(formatter, @"Must be nil at this point");
}

- (void) testFormattedText
{
    NSString *rawString = @"250485";
    ESPFormatter *formatter = [[ESPFormatter alloc] initWithMask:@"__/__/__" placeholder:@"_"];
    formatter.ignoredChars = @[@"/"];
    NSString *formattedString = [formatter formattedStringFromRawValue:rawString
                                                   displaysPlaceholder:YES];
    XCTAssert([formattedString isEqualToString:@"25/04/85"], @"Date must be formatted");
}

- (void) testRawText
{
    NSString *formattedString = @"25/04/85";
    ESPFormatter *formatter = [[ESPFormatter alloc] initWithMask:@"__/__/__" placeholder:@"_"];
    formatter.ignoredChars = @[@"/"];
    NSString *rawString = [formatter rawStringFromFormattedValue:formattedString];
    XCTAssert([rawString isEqualToString:@"250485"], @"Date must not contain nothing except numbers");
}

- (void) testPlaceHolderDisplay
{
    NSString *rawString = @"250485";
    ESPFormatter *formatter = [[ESPFormatter alloc] initWithMask:@"__/__/____" placeholder:@"_"];
    formatter.ignoredChars = @[@"/"];
    NSString *formattedString = [formatter formattedStringFromRawValue:rawString
                                                   displaysPlaceholder:YES];
    XCTAssert([formattedString isEqualToString:@"25/04/85__"], @"Date must be formatted with placeholder at end");
}

- (void) testPlaceHolderHidden
{
    NSString *rawString = @"250485";
    ESPFormatter *formatter = [[ESPFormatter alloc] initWithMask:@"__/__/____" placeholder:@"_"];
    formatter.ignoredChars = @[@"/"];
    NSString *formattedString = [formatter formattedStringFromRawValue:rawString
                                                   displaysPlaceholder:NO];
    XCTAssert([formattedString isEqualToString:@"25/04/85"], @"Date must be formatted with placeholder at end");
}

- (void) testFormattedTextWithMultipleMasks
{
    NSString *rawString = @"2504198";
    ESPFormatter *formatter = [[ESPFormatter alloc] initWithMasks:@[@"__/__/__", @"__/__/____"]
                                                     placeholder:@"_"];
    formatter.ignoredChars = @[@"/"];
    [formatter updateMaskForText:rawString];
    NSString *formattedString = [formatter formattedStringFromRawValue:rawString
                                                   displaysPlaceholder:YES];
    XCTAssert([formattedString isEqualToString:@"25/04/198_"], @"Date must be formatted");
}

#pragma mark - Masker Tests
- (void) testInit
{
    ESPFormatter *formatter = [[ESPFormatter alloc] initWithMask:@"__/__/__" placeholder:@"_"];
    formatter.ignoredChars = @[@"/"];
    ESPTextFieldMasker *maskedTextField = [[ESPTextFieldMasker alloc] initWithFormatter:formatter];
    XCTAssertNotNil(maskedTextField.formatter, @"Formatter should not be null");

    ESPTextFieldMasker *nulledTextFieldMasker = [[ESPTextFieldMasker alloc] init];
    XCTAssertNil(nulledTextFieldMasker.formatter, @"Formatter shoul be null");
}

- (void) testCharacterChanging
{
    XCTAssertNil(nil, @"");
}

@end


text:
var _ = require('underscore');
var $ = require('jquery');
var React = require('react/addons');
var RetinaImage = require('react-retina-image');
var Radial = require('./Radial.react');
var ImageCard = require('./ImageCard.react');
var Promise = require('bluebird');
var metrics = require('./Metrics');

var _recommended = [];
var _searchPromise = null;

var NewContainer = React.createClass({
  getInitialState: function () {
    return {
      query: '',
      loading: false,
      results: _recommended
    };
  },
  componentDidMount: function () {
    this.refs.searchInput.getDOMNode().focus();
    this.recommended();
  },
  componentWillUnmount: function () {
    if (_searchPromise) {
      _searchPromise.cancel();
    }
  },
  search: function (query) {
    if (_searchPromise) {
      _searchPromise.cancel();
      _searchPromise = null;
    }

    if (!query.length) {
      this.setState({
        query: query,
        results: _recommended,
        loading: false
      });
      return;
    }

    this.setState({
      query: query,
      loading: true
    });

    _searchPromise = Promise.delay(200).then(() => Promise.resolve($.get('https://registry.hub.docker.com/v1/search?q=' + query))).cancellable().then(data => {
      metrics.track('Searched for Images');
      this.setState({
        results: data.results,
        query: query,
        loading: false
      });
      _searchPromise = null;
    }).catch(Promise.CancellationError, () => {
    });
  },
  recommended: function () {
    if (_recommended.length) {
      return;
    }
    Promise.resolve($.ajax({
      url: 'https://kitematic.com/recommended.json',
      cache: false,
      dataType: 'json',
    })).then(res => res.repos).map(repo => {
      var query = repo.repo;
      var vals = query.split('/');
      if (vals.length === 1) {
        query = 'library/' + vals[0];
      }
      return $.get('https://registry.hub.docker.com/v1/repositories_info/' + query).then(data => {
        var res = _.extend(data, repo);
        res.description = data.short_description;
        res.is_official = data.namespace === 'library';
        res.name = data.repo;
        res.star_count = data.stars;
        return res;
      });
    }).then(results => {
      _recommended = results.filter(r => !!r);
      if (!this.state.query.length && this.isMounted()) {
        this.setState({
          results: _recommended
        });
      }
    }).catch(err => {
      console.log(err);
    });
  },
  handleChange: function (e) {
    var query = e.target.value;
    if (query === this.state.query) {
      return;
    }
    this.search(query);
  },
  render: function () {
    var title = this.state.query ? 'Results' : 'Recommended';
    var data = this.state.results;
    var results;
    if (data.length) {
      var items = data.map(function (image) {
        return (
          <ImageCard key={image.name} image={image} />
        );
      });

      results = (

          {items}

      );
    } else {
      if (this.state.results.length === 0 && this.state.query === '') {
        results = (

Loading Images

              <Radial spin="true" progress={90} thick={true} transparent={true} />

        );
      } else {
        results = (

Cannot find a matching image.

        );
      }
    }
    var loadingClasses = React.addons.classSet({
      hidden: !this.state.loading,
      loading: true
    });
    var magnifierClasses = React.addons.classSet({
      hidden: this.state.loading,
      icon: true,
      'icon-magnifier': true,
      'search-icon': true
    });
    return (

              Select a Docker image to create a new container.

                <input type="search" ref="searchInput" className="form-control" placeholder="Search Docker Hub for an image" onChange={this.handleChange}/>

                <RetinaImage className={loadingClasses} src="loading.png"/>

{title}

            {results}

    );
  }
});

module.exports = NewContainer;

redpajama_set_name: RedPajamaGithub


text:
describe KeyPairsController do
  let(:instructor) { create :instructor }

  before :each do
    allow(Settings.repository).to receive(:type).and_return('git')
  end

  describe 'GET new', :keep_memory_repos do
    before { get_as instructor, :new }
    it 'should respond with success' do
      is_expected.to respond_with(:success)
    end
    it 'should render new' do
      expect(response).to render_template(:new)
    end
  end

  describe 'POST create', :keep_memory_repos do
    shared_examples 'key_pair_create' do
      context 'a valid key' do
        let(:key) { 'ssh-rsa aaaaa' }
        let(:key_file) { 'key_pairs/id_rsa.good.pub' }
        it 'should respond with success' do
          is_expected.to respond_with(:redirect)
        end
        it 'should redirect' do
          expect(response).to redirect_to(settings_users_path)
        end
        it 'should flash a success message' do
          expect(flash[:success]).not_to be_empty
        end
      end
      context 'an invalid key' do
        let(:key) { 'aaaaa' }
        let(:key_file) { 'key_pairs/id_rsa.bad.pub' }
        it 'should render new' do
          expect(response).to render_template(:new)
        end
        it 'should flash an error message' do
          expect(flash[:error]).not_to be_empty
        end
      end
    end

    context 'uploading a string' do
      before { post_as instructor, :create, params: { key_pair: { key_string: key } } }
      it_behaves_like 'key_pair_create'
    end
    context 'uploading a file' do
      before do
        post_as instructor, :create, params: { key_pair: { file: fixture_file_upload(key_file) } }
      end
      it_behaves_like 'key_pair_create'
    end
  end

  describe 'DELETE destroy', :keep_memory_repos do
    before { delete_as instructor, :destroy, params: { id: key_pair_id } }
    context 'a key_pair exists' do
      context 'owned by the current user' do
        let(:key_pair_id) { create(:key_pair, user: instructor.user).id }
        it 'should delete the key_pair' do
          expect(KeyPair.where(id: key_pair_id)).to be_empty
        end
        it 'should respond with redirect' do
          is_expected.to respond_with(:redirect)
        end
        it 'should flash a success message' do
          expect(flash[:success]).not_to be_empty
        end
      end
      context 'not owned by the current user' do
        let(:key_pair_id) { create(:key_pair).id }
        it 'should not delete the key_pair' do
          expect(KeyPair.where(id: key_pair_id)).to exist
        end
        it 'should respond with redirect' do
          is_expected.to respond_with(:redirect)
        end
        it 'should not flash a success message' do
          expect(flash[:success]).to be_nil
        end
      end
    end
    context 'a key_pair does not exist' do
      let(:key_pair_id) { -1 }
      it 'should respond with redirect' do
        is_expected.to respond_with(:not_found)
      end
      it 'should not flash a success message' do
        expect(flash[:success]).to be_nil
      end
    end
  end
end


text:
package org.openo.nfvo.monitor.umc.res;

import java.util.Map;

public interface IResMsgHandle {
	public static final String EXTENSIONID = "org.openo.nfvo.monitor.umc.res.IResMsgHandle";
	public static final String KEY = "res.msg.handle";

	public void process(Map<String, ?> resData);
}


text:
package main

import (
	"os"
	"os/exec"
	"runtime"
)

var clear map[string]func()

func init() {
	clear = make(map[string]func())
	clear["linux"] = func() {
		cmd := exec.Command("clear")
		cmd.Stdout = os.Stdout
		cmd.Run()
	}

	clear["darwin"] = func() {
		cmd := exec.Command("clear")
		cmd.Stdout = os.Stdout
		cmd.Run()
	}

	clear["windows"] = func() {
		cmd := exec.Command("cls")
		cmd.Stdout = os.Stdout
		cmd.Run()
	}
}

func Clear() {
	value, ok := clear[runtime.GOOS]
	if ok {
		value()
	} else {
		panic("Your platform is unsupported! I can't clear terminal screen :(")
	}
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('core', '0015_merge'),
    ]

    operations = [
        migrations.AlterField(
            model_name='delegate',
            name='assignment',
            field=models.ForeignKey(related_name='delegates', blank=True, to='core.Assignment', null=True, on_delete=models.SET_NULL),
        ),
        migrations.AlterField(
            model_name='delegate',
            name='email',
            field=models.EmailField(max_length=254, null=True, blank=True),
        ),
        migrations.AlterField(
            model_name='delegate',
            name='summary',
            field=models.TextField(default=b'', null=True, blank=True),
        ),
    ]


text:
#region About and License
//=======================================================================
// Copyright Andrew Szot 2015.
// Distributed under the MIT License.
// (See accompanying file LICENSE.txt)
//=======================================================================
#endregion

namespace BaseLogic.Player.AI
{
    /// <summary>
    ///
    /// </summary>
    public abstract class AIState
    {
        /// <summary>
        /// The p_ai MGR
        /// </summary>
        protected AIMgr p_aiMgr;

        /// <summary>
        /// Sets the ai MGR.
        /// </summary>
        /// <value>
        /// The ai MGR.
        /// </value>
        public AIMgr AIMgr
        {
            set { p_aiMgr = value; }
        }

        /// <summary>
        /// Clones this instance.
        /// </summary>
        /// <returns></returns>
        public abstract AIState Clone();

        /// <summary>
        /// Enters the specified entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        public abstract void Enter(GameAIPlayer entity);

        /// <summary>
        /// Exits the specified entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        public abstract void Exit(GameAIPlayer entity);

        /// <summary>
        /// Updates the specified entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <param name="gameTime">The game time.</param>
        public abstract void Update(GameAIPlayer entity, Microsoft.Xna.Framework.GameTime gameTime);
    }
}


text:
#include "SkAutoMalloc.h"
#include "SkCanvasPriv.h"
#include "SkReadBuffer.h"
#include "SkWriter32.h"

SkAutoCanvasMatrixPaint::SkAutoCanvasMatrixPaint(SkCanvas* canvas, const SkMatrix* matrix,
                                                 const SkPaint* paint, const SkRect& bounds)
: fCanvas(canvas)
, fSaveCount(canvas->getSaveCount())
{
    if (paint) {
        SkRect newBounds = bounds;
        if (matrix) {
            matrix->mapRect(&newBounds);
        }
        canvas->saveLayer(&newBounds, paint);
    } else if (matrix) {
        canvas->save();
    }

    if (matrix) {
        canvas->concat(*matrix);
    }
}

SkAutoCanvasMatrixPaint::~SkAutoCanvasMatrixPaint() {
    fCanvas->restoreToCount(fSaveCount);
}

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

bool SkCanvasPriv::ReadLattice(SkReadBuffer& buffer, SkCanvas::Lattice* lattice) {
    lattice->fXCount = buffer.readInt();
    lattice->fXDivs = buffer.skipT<int32_t>(lattice->fXCount);
    lattice->fYCount = buffer.readInt();
    lattice->fYDivs = buffer.skipT<int32_t>(lattice->fYCount);
    int flagCount = buffer.readInt();
    lattice->fRectTypes = nullptr;
    lattice->fColors = nullptr;
    if (flagCount) {
        lattice->fRectTypes = buffer.skipT<SkCanvas::Lattice::RectType>(flagCount);
        lattice->fColors = buffer.skipT<SkColor>(flagCount);
    }
    lattice->fBounds = buffer.skipT<SkIRect>();
    return buffer.isValid();
}

size_t SkCanvasPriv::WriteLattice(void* buffer, const SkCanvas::Lattice& lattice) {
    int flagCount = lattice.fRectTypes ? (lattice.fXCount + 1) * (lattice.fYCount + 1) : 0;

    const size_t size = (1 + lattice.fXCount + 1 + lattice.fYCount + 1) * sizeof(int32_t) +
                        SkAlign4(flagCount * sizeof(SkCanvas::Lattice::RectType)) +
                        SkAlign4(flagCount * sizeof(SkColor)) +
                        sizeof(SkIRect);

    if (buffer) {
        SkWriter32 writer(buffer, size);
        writer.write32(lattice.fXCount);
        writer.write(lattice.fXDivs, lattice.fXCount * sizeof(uint32_t));
        writer.write32(lattice.fYCount);
        writer.write(lattice.fYDivs, lattice.fYCount * sizeof(uint32_t));
        writer.write32(flagCount);
        writer.writePad(lattice.fRectTypes, flagCount * sizeof(uint8_t));
        writer.write(lattice.fColors, flagCount * sizeof(SkColor));
        SkASSERT(lattice.fBounds);
        writer.write(lattice.fBounds, sizeof(SkIRect));
        SkASSERT(writer.bytesWritten() == size);
    }
    return size;
};

void SkCanvasPriv::WriteLattice(SkWriteBuffer& buffer, const SkCanvas::Lattice& lattice) {
    const size_t size = WriteLattice(nullptr, lattice);
    SkAutoSMalloc<1024> storage(size);
    WriteLattice(storage.get(), lattice);
    buffer.writePad32(storage.get(), size);
}

void SkCanvasPriv::GetDstClipAndMatrixCounts(const SkCanvas::ImageSetEntry set[], int count,
                                             int* totalDstClipCount, int* totalMatrixCount) {
    int dstClipCount = 0;
    int maxMatrixIndex = -1;
    for (int i = 0; i < count; ++i) {
        dstClipCount += 4 * set[i].fHasClip;
        if (set[i].fMatrixIndex > maxMatrixIndex) {
            maxMatrixIndex = set[i].fMatrixIndex;
        }
    }

    *totalDstClipCount = dstClipCount;
    *totalMatrixCount = maxMatrixIndex + 1;
}


text:
const toggleList = document.getElementById('toggleList');
const listDiv = document.querySelector('.list');
const descriptionInput = document.querySelector('input.description');
const descriptionP = document.querySelector('p.description');
const descriptionButton = document.querySelector('button.description');
const addItemInput = document.querySelector('input.addItemInput');
const addItemButton = document.querySelector('button.addItemButton');
const removeItemButton = document.querySelector('button.removeItemButton');
const listItems = document.getElementsByTagName('li');

toggleList.addEventListener('click', () => {
  if (listDiv.style.display == 'none') {
    toggleList.textContent = 'Hide list';
    listDiv.style.display = 'block';
  } else {
    toggleList.textContent = 'Show list';
    listDiv.style.display = 'none';
  }
});

descriptionButton.addEventListener('click', () => {
  descriptionP.innerHTML = descriptionInput.value + ':';
  descriptionInput.value = '';
});

addItemButton.addEventListener('click', () => {
  let ul = document.getElementsByTagName('ul')[0];
  let li = document.createElement('li');
  li.textContent = addItemInput.value;
  ul.appendChild(li);
  addItemInput.value = '';
});

removeItemButton.addEventListener('click', () => {
  let ul = document.getElementsByTagName('ul')[0];
  let li = document.querySelector('li:last-child');
  ul.removeChild(li);
});

for (let i = 0; i < listItems.length; i++) {
  listItems[i].addEventListener('mouseover', () => {
    listItems[i].textContent = listItems[i].textContent.toUpperCase();
  });

  listItems[i].addEventListener('mouseout', () => {
    listItems[i].textContent = listItems[i].textContent.toLowerCase();
  });
}


text:
""" -*- coding: utf-8 -*-
A distutils based setup module.
"""
from distutils.core import setup
setup(
    name='fileasobj',
    packages=['fileasobj'],
    version='2.0.0',
    description='Manage a file as a Python list.',
    author='John Hazelwood',
    author_email='jhazelwo@users.noreply.github.com',
    url='https://github.com/jhazelwo/python-fileasobj',
    download_url='https://github.com/jhazelwo/python-fileasobj/tarball/2.0.0',
    keywords=['python', 'file', 'fileasobj'],
    license='MIT',
    # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: System Administrators',
        'Topic :: Utilities',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
    ],
)


text:
NRPE Docker Container

## About
Provides NRPE Server within docker container. This allows remote monitoring of docker hosts from nagios/Icinga.

## Status
Ready for production

## Images
The docker-nrpe image is available on docker hub [totem/docker-nrpe:latest](https://registry.hub.docker.com/u/totem/docker-nrpe). It is setup using hub's automated build process.

## Running
In order to run the NRPE container , use command :

```
docker run --privileged -v /:/mnt/ROOT --rm --name nrpe -it -p 5666:5666 totem/docker-nrpe
```

Once up, you can monitor server using nagios/icinga.

Note: In order to monitor multiple disks, simply mount them under /mnt directory.


text:
package transport

import(
  "time"
  "github.com/gorilla/websocket"
  log "github.com/Sirupsen/logrus"
)

type Transport struct{
  Connection      *websocket.Conn
  ConnectionId    uint64
  LastPing        time.Time
  PingInterval    time.Duration
  ConnectedAt     time.Time

  wsUrl           string
  hasHelo         bool
  commandChannel  chan Command
  connectionMade  bool
  disconnectError error
}

func (t *Transport) PingExpired() bool{
  pingExpires := t.LastPing.Add(t.PingInterval).Add(time.Second*5)
  return time.Now().After(pingExpires) || (!t.hasHelo && time.Now().After(t.ConnectedAt.Add(time.Second*5)))
}

func (t *Transport) ClientFields() log.Fields{
  f := log.Fields{
    "address": t.Connection.RemoteAddr(),
    "pingInterval": t.PingInterval,
    "lastPing": t.LastPing,
    "connectionId": t.ConnectionId,
    "connectedAt": t.ConnectedAt,
  }

  return f
}


text:
//Write an expression that calculates trapezoid's area by given sides a and b and height h.
using System;
class Trapezoids
{
    static void Main()
    {
        double smallBase = Double.Parse(Console.ReadLine());
        double largeBase = Double.Parse(Console.ReadLine());
        double height = Double.Parse(Console.ReadLine());
        double area = (smallBase + largeBase) * height * 0.5;
        Console.WriteLine(area);
    }
}


text:
class JfifData(object):
    """NOTE: This class is auto generated by the swagger code generator program.
    Do not edit the class manually."""

    def __init__(self):
        """
        Attributes:
          swaggerTypes (dict): The key is attribute name and the value is attribute type.
          attributeMap (dict): The key is attribute name and the value is json key in definition.
        """
        self.swaggerTypes = {
            'DensityUnits': 'str',
            'Version': 'int',
            'XDensity': 'int',
            'YDensity': 'int'

        }

        self.attributeMap = {
            'DensityUnits': 'DensityUnits','Version': 'Version','XDensity': 'XDensity','YDensity': 'YDensity'}

        self.DensityUnits = None # str
        self.Version = None # int
        self.XDensity = None # int
        self.YDensity = None # int


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

namespace Aras.ViewModel.WebService.Models.Responses
{
    public class Control : Response
    {
        public Models.Control Value { get; set; }

        public Control(ViewModel.Manager.Session Session, ViewModel.Control Control)
            :base(Session)
        {
            List<ViewModel.Control> viewmodelcontrols = new List<ViewModel.Control>();
            viewmodelcontrols.Add(Control);
            List<Models.Control> controls = this.QueueControls(Session, viewmodelcontrols);
            this.Value = controls.First();
        }
    }
}


text:
#include "InputRC4XcodeStream.h"

using namespace IOBasicTypes;

InputRC4XcodeStream::InputRC4XcodeStream():mRC4()
{
	mSourceStream = NULL;
}

InputRC4XcodeStream::InputRC4XcodeStream(IByteReader* inSourceReader, const ByteList& inKey):mRC4(inKey)
{
	mSourceStream = inSourceReader;
}

InputRC4XcodeStream::~InputRC4XcodeStream(void)
{
	if (mSourceStream)
		delete mSourceStream;
}

void InputRC4XcodeStream::Assign(IByteReader* inSourceReader, const ByteList& inKey)
{
	mSourceStream = inSourceReader;
	mRC4.Reset(inKey);
}

bool InputRC4XcodeStream::NotEnded()
{
	return mSourceStream && mSourceStream->NotEnded();
}

LongBufferSizeType InputRC4XcodeStream::Read(IOBasicTypes::Byte* inBuffer, LongBufferSizeType inBufferSize)
{
	LongBufferSizeType mCurrentIndex = 0;
	Byte buffer;

	while (NotEnded() && mCurrentIndex < inBufferSize)
	{
		mSourceStream->Read(&buffer, 1);
		inBuffer[mCurrentIndex] = mRC4.DecodeNextByte(buffer);
		++mCurrentIndex;
	}

	return mCurrentIndex;
}


text:
package com.rpg.random;

public enum PlayingCard {
	clubs2("Two of Clubs", 2, CardSuit.CLUBS),
	clubs3("Three of Clubs", 3, CardSuit.CLUBS),
	clubs4("Four of Clubs", 4, CardSuit.CLUBS),
	clubs5("Five of Clubs", 5, CardSuit.CLUBS),
	clubs6("Six of Clubs", 6, CardSuit.CLUBS),
	clubs7("Seven of Clubs", 7, CardSuit.CLUBS),
	clubs8("Eight of Clubs", 8, CardSuit.CLUBS),
	clubs9("Nine of Clubs", 9, CardSuit.CLUBS),
	clubs10("Ten of Clubs", 10, CardSuit.CLUBS),
	clubsJack("Jack of Clubs", 11, CardSuit.CLUBS),
	clubsQueen("Queen of Clubs", 12, CardSuit.CLUBS),
	clubsKing("King of Clubs", 13, CardSuit.CLUBS),
	clubsAce("Ace of Clubs", 14, CardSuit.CLUBS),

	diamonds2("Two of Diamonds", 2, CardSuit.DIAMONDS),
	diamonds3("Three of Diamonds", 3, CardSuit.DIAMONDS),
	diamonds4("Four of Diamonds", 4, CardSuit.DIAMONDS),
	diamonds5("Five of Diamonds", 5, CardSuit.DIAMONDS),
	diamonds6("Six of Diamonds", 6, CardSuit.DIAMONDS),
	diamonds7("Seven of Diamonds", 7, CardSuit.DIAMONDS),
	diamonds8("Eight of Diamonds", 8, CardSuit.DIAMONDS),
	diamonds9("Nine of Diamonds", 9, CardSuit.DIAMONDS),
	diamonds10("Ten of Diamonds", 10, CardSuit.DIAMONDS),
	diamondsJack("Jack of Diamonds", 11, CardSuit.DIAMONDS),
	diamondsQueen("Queen of Diamonds", 12, CardSuit.DIAMONDS),
	diamondsKing("King of Diamonds", 13, CardSuit.DIAMONDS),
	diamondsAce("Ace of Diamonds", 14, CardSuit.DIAMONDS),

	hearts2("Two of Hearts", 2, CardSuit.HEARTS),
	hearts3("Three of Hearts", 3, CardSuit.HEARTS),
	hearts4("Four of Hearts", 4, CardSuit.HEARTS),
	hearts5("Five of Hearts", 5, CardSuit.HEARTS),
	hearts6("Six of Hearts", 6, CardSuit.HEARTS),
	hearts7("Seven of Hearts", 7, CardSuit.HEARTS),
	hearts8("Eight of Hearts", 8, CardSuit.HEARTS),
	hearts9("Nine of Hearts", 9, CardSuit.HEARTS),
	hearts10("Ten of Hearts", 10, CardSuit.HEARTS),
	heartsJack("Jack of Hearts", 11, CardSuit.HEARTS),
	heartsQueen("Queen of Hearts", 12, CardSuit.HEARTS),
	heartsKing("King of Hearts", 13, CardSuit.HEARTS),
	heartsAce("Ace of Hearts", 14, CardSuit.HEARTS),

	spades2("Two of Spades", 2, CardSuit.SPADES),
	spades3("Three of Spades", 3, CardSuit.SPADES),
	spades4("Four of Spades", 4, CardSuit.SPADES),
	spades5("Five of Spades", 5, CardSuit.SPADES),
	spades6("Six of Spades", 6, CardSuit.SPADES),
	spades7("Seven of Spades", 7, CardSuit.SPADES),
	spades8("Eight of Spades", 8, CardSuit.SPADES),
	spades9("Nine of Spades", 9, CardSuit.SPADES),
	spades10("Ten of Spades", 10, CardSuit.SPADES),
	spadesJack("Jack of Spades", 11, CardSuit.SPADES),
	spadesQueen("Queen of Spades", 12, CardSuit.SPADES),
	spadesKing("King of Spades", 13, CardSuit.SPADES),
	spadesAce("Ace of Spades", 14, CardSuit.SPADES),

	blackJoker("Black Joker", 15, CardSuit.None),
	redJoker("Red Joker", 15, CardSuit.None);

	private String name;
	private int value;
	private CardSuit suit;

	private PlayingCard(String name, int value, CardSuit suit) {
		this.name = name;
		this.value = value;
		this.suit = suit;
	}

	/**
	 * If one comes before two, return -1 If one equals two, return 0 If one
	 * comes after two, return 1
	 *
	 * If values are the same, then it checks reverse alphabetical order If one
	 * is spades2 and two is hearts2, return 1 If one is clubsQueen and two is
	 * diamondsQueen, return -1
	 *
	 * Jokers are always higher than any other card. Black joker equals red joker
	 *
	 * @return
	 */
	public static int compare(PlayingCard one, PlayingCard two) {
		if (one.getValue() > two.getValue()) {
			return 1;
		} else if (one.getValue() < two.getValue()) {
			return -1;
		} else {
			if (one.getSuit().getValue() > two.getSuit().getValue()) {
				return 1;
			} else if (one.getSuit().getValue() < two.getSuit().getValue()) {
				return -1;
			}
		}
		return 0;
	}

	public String getName() {
		return this.name;
	}

	public int getValue() {
		return this.value;
	}

	public CardSuit getSuit() {
		return this.suit;
	}

	@Override public String toString(){
		return getName();
	}
}


text:
import { useEffect, useMemo, useRef, useState } from "react";
import { useResizeDetector } from "react-resize-detector";
import { querySelectorOrThrow } from "lib/dom";
import GenieButtons from "./GenieButtons";
import usePianoGenie from "hooks/use-piano-genie";
import useMagentaPlayer from "hooks/use-magenta-player";

// Taken from the original Genie demo
// https://glitch.com/edit/#!/piano-genie

const CONSTANTS = {
  COLORS: [
    "#EE2B29",
    "#ff9800",
    "#ffff00",
    "#c6ff00",
    "#00e5ff",
    "#2979ff",
    "#651fff",
    "#d500f9",
  ],
  NUM_BUTTONS: 8,
  NOTES_PER_OCTAVE: 12,
  WHITE_NOTES_PER_OCTAVE: 7,
  LOWEST_PIANO_KEY_MIDI_NOTE: 21,
};

const defaultTemperature = 0.25;

interface Note {
  x: number;
  y: number;
  width: number;
  height: number;
  color: string;
  on: boolean;
}

/*************************
 * Floaty notes
 ************************/
class FloatyNotes {
  notes = Array<Note>(); // the notes floating on the screen.
  parent: HTMLElement;
  canvas: HTMLCanvasElement;
  context: CanvasRenderingContext2D;
  contextHeight = 0;
  detached = false;
  prevTimestamp: DOMHighResTimeStamp;

  constructor(parent: HTMLElement) {
    this.parent = parent;
    this.canvas = querySelectorOrThrow(parent, HTMLCanvasElement, "canvas");
    const context = this.canvas.getContext("2d");
    if (!context) throw new Error();
    context.lineWidth = 4;
    context.lineCap = "round";
    this.context = context;
    this.prevTimestamp = 0;
  }

  resize(whiteNoteHeight) {
    const rect = this.parent.getBoundingClientRect();
    this.canvas.width = rect.width;
    this.canvas.height = this.contextHeight = rect.height - whiteNoteHeight;
  }

  addNote(button, x, width) {
    const noteToPaint = {
      x: parseFloat(x),
      y: 0,
      width: parseFloat(width),
      height: 0,
      color: CONSTANTS.COLORS[button],
      on: true,
    };
    this.notes.push(noteToPaint);
    return noteToPaint;
  }

  stopNote(noteToPaint) {
    noteToPaint.on = false;
  }

  startDrawLoop() {
    this.prevTimestamp = performance.now();
    window.requestAnimationFrame(this.drawLoop.bind(this));
  }

  drawLoop(timestamp: DOMHighResTimeStamp) {
    const dy = 4 * (timestamp - this.prevTimestamp) * (1 / 60);
    this.prevTimestamp = timestamp;
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);

    // Remove all the notes that will be off the page;
    this.notes = this.notes.filter(
      (note) => note.on || note.y < this.contextHeight
    );

    // Advance all the notes.
    for (let i = 0; i < this.notes.length; i++) {
      const note = this.notes[i];

      // If the note is still on, then its height goes up but it
      // doesn't start sliding down yet.
      if (note.on) {
        note.height += dy;
      } else {
        note.y += dy;
      }

      this.context.globalAlpha = 1 - note.y / this.contextHeight;
      this.context.fillStyle = note.color;
      this.context.fillRect(note.x, note.y, note.width, note.height);
    }
    if (!this.detached) window.requestAnimationFrame(this.drawLoop.bind(this));
  }
}

class Piano {
  config = {
    whiteNoteWidth: 20,
    blackNoteWidth: 20,
    whiteNoteHeight: 70,
    blackNoteHeight: (2 * 70) / 3,
    octaves: 7,
  };
  svg: SVGSVGElement;
  readonly svgNS = "http://www.w3.org/2000/svg";
  parent: HTMLElement;

  constructor(parent: HTMLElement) {
    this.parent = parent;
    this.svg = querySelectorOrThrow(parent, SVGSVGElement, "svg");
  }

  resize(octaves, totalWhiteNotes) {
    const width = this.parent.getBoundingClientRect().width;
    const ratio = width / totalWhiteNotes;
    this.config.octaves = octaves;
    this.config.whiteNoteWidth = ratio;
    this.config.blackNoteWidth = (this.config.whiteNoteWidth * 2) / 3;
    this.svg.setAttribute("width", String(width));
    this.svg.setAttribute("height", String(this.config.whiteNoteHeight));
  }

  draw() {
    this.svg.innerHTML = "";
    const halfABlackNote = this.config.blackNoteWidth / 2;
    let x = 0;
    const y = 0;
    let index = 0;

    const blackNoteIndexes = [1, 3, 6, 8, 10];

    if (this.config.octaves < 6) {
      index = 2 * CONSTANTS.NOTES_PER_OCTAVE;
    }
    // First draw all the white notes.
    // Pianos start on an A (if we're using all the octaves);
    this.makeRect(
      index,
      x,
      y,
      this.config.whiteNoteWidth,
      this.config.whiteNoteHeight,
      "white",
      "#141E30"
    );
    this.makeRect(
      index + 2,
      this.config.whiteNoteWidth,
      y,
      this.config.whiteNoteWidth,
      this.config.whiteNoteHeight,
      "white",
      "#141E30"
    );
    index += 3;
    x = 2 * this.config.whiteNoteWidth;

    // Draw the white notes.
    for (let o = 0; o < this.config.octaves; o++) {
      for (let i = 0; i < CONSTANTS.NOTES_PER_OCTAVE; i++) {
        if (blackNoteIndexes.indexOf(i) === -1) {
          this.makeRect(
            index,
            x,
            y,
            this.config.whiteNoteWidth,
            this.config.whiteNoteHeight,
            "white",
            "#141E30"
          );
          x += this.config.whiteNoteWidth;
        }
        index++;
      }
    }

    // And an extra C at the end (if we're using all the octaves);
    this.makeRect(
      index,
      x,
      y,
      this.config.whiteNoteWidth,
      this.config.whiteNoteHeight,
      "white",
      "#141E30"
    );

    index = 1;
    if (this.config.octaves < 6) {
      index += 2 * CONSTANTS.NOTES_PER_OCTAVE;
    }
    // Now draw all the black notes, so that they sit on top.
    // Pianos start on an A:
    this.makeRect(
      index,
      this.config.whiteNoteWidth - halfABlackNote,
      y,
      this.config.blackNoteWidth,
      this.config.blackNoteHeight,
      "black"
    );
    index += 2;
    x = this.config.whiteNoteWidth;

    // Draw the black notes.
    for (let o = 0; o < this.config.octaves; o++) {
      for (let i = 0; i < CONSTANTS.NOTES_PER_OCTAVE; i++) {
        if (blackNoteIndexes.indexOf(i) !== -1) {
          this.makeRect(
            index,
            x + this.config.whiteNoteWidth - halfABlackNote,
            y,
            this.config.blackNoteWidth,
            this.config.blackNoteHeight,
            "black"
          );
        } else {
          x += this.config.whiteNoteWidth;
        }
        index++;
      }
    }
  }

  highlightNote(note, button) {
    // Show the note on the piano roll.
    const rect = this.svg.querySelector(`rect[data-index="${note}"]`);
    if (!rect) {
      console.log("couldnt find a rect for note", note);
      return;
    }
    rect.setAttribute("active", "true");
    rect.setAttribute("class", `color-${button}`);
    return rect;
  }

  clearNote(note) {
    const rect = this.svg.querySelector(`rect[data-index="${note}"]`);
    if (!rect) {
      console.log("couldnt find a rect for note", note);
      return;
    }
    rect.removeAttribute("active");
    rect.removeAttribute("class");
  }

  makeRect(index, x, y, w, h, fill, stroke?): SVGRectElement {
    const rect = document.createElementNS(this.svgNS, "rect");
    rect.setAttribute("data-index", index);
    rect.setAttribute("x", x);
    rect.setAttribute("y", y);
    rect.setAttribute("width", w);
    rect.setAttribute("height", h);
    rect.setAttribute("fill", fill);
    if (stroke) {
      rect.setAttribute("stroke", stroke);
      rect.setAttribute("stroke-width", "3px");
    }
    this.svg.appendChild(rect);
    return rect;
  }
}

function getAvailableNotes(octaves: number): Array<number> {
  const bonusNotes = 4; // starts on an A, ends on a C.
  const totalNotes = CONSTANTS.NOTES_PER_OCTAVE * octaves + bonusNotes;
  return Array<number>(totalNotes)
    .fill(0)
    .map((x, i) => {
      if (octaves > 6) return i;
      // Start two octaves up.
      return i + 2 * CONSTANTS.NOTES_PER_OCTAVE;
    });
}

interface Props {
  activeButton?: number;
  inView?: boolean;
  onReady?: () => void;
}

export default function GeniePiano(props: Props) {
  const { activeButton, inView, onReady } = props;

  const [piano, setPiano] = useState<Piano>();
  const [floatyNotes, setFloatyNotes] = useState<FloatyNotes>();
  const [activeNote, setActiveNote] = useState<number>();
  const [noteToPaint, setNoteToPaint] = useState<Note>();
  const [octaves, setOctaves] = useState(7);
  const genie = usePianoGenie(inView);
  const {
    playNoteDown,
    playNoteUp,
    ready: playerReady,
  } = useMagentaPlayer({
    load: inView,
  });
  const availableNotes = useMemo(() => getAvailableNotes(octaves), [octaves]);
  const ref = useRef<HTMLDivElement>(null);
  const { width, height } = useResizeDetector({
    targetRef: ref,
    refreshMode: "throttle",
    refreshRate: 5,
  });

  useEffect(() => {
    if (!ref.current) return;
    const floatyNotes = new FloatyNotes(ref.current);
    floatyNotes.startDrawLoop();
    setFloatyNotes(floatyNotes);
    const piano = new Piano(ref.current);
    setPiano(piano);

    return () => {
      setPiano(undefined);
      floatyNotes.detached = true;
      setFloatyNotes(undefined);
    };
  }, []);

  useEffect(() => {
    if (!width || !piano) return;
    const octaves = width > 700 ? 7 : 3;
    setOctaves(octaves);
    piano.config.octaves = octaves;
    const bonusNotes = 4; // starts on an A, ends on a C.
    const totalWhiteNotes =
      CONSTANTS.WHITE_NOTES_PER_OCTAVE * octaves + (bonusNotes - 1);
    piano.resize(octaves, totalWhiteNotes);
    piano.draw();
    floatyNotes?.resize(piano.config.whiteNoteHeight);
  }, [floatyNotes, piano, width]);

  useEffect(() => {
    floatyNotes?.resize(piano?.config.whiteNoteHeight);
  }, [floatyNotes, piano, height]);

  useEffect(() => {
    if (!genie || !piano || !floatyNotes) return;
    let note: number;
    let noteToPaint: Note;
    if (activeButton !== undefined) {
      if (octaves > 6) {
        note = genie.next(activeButton);
      } else {
        note = genie.nextFromKeyList(
          activeButton,
          availableNotes,
          defaultTemperature
        );
      }
      const midi = note + CONSTANTS.LOWEST_PIANO_KEY_MIDI_NOTE;
      playNoteDown({ pitch: midi });
      const rect = piano.highlightNote(note, activeButton);
      if (rect) {
        noteToPaint = floatyNotes.addNote(
          activeButton,
          rect.getAttribute("x"),
          rect.getAttribute("width")
        );
      }
    }
    setActiveNote((prev) => {
      if (prev) {
        const midi = prev + CONSTANTS.LOWEST_PIANO_KEY_MIDI_NOTE;
        playNoteUp({ pitch: midi });
        piano?.clearNote(prev);
      }
      return note;
    });
    setNoteToPaint((prev) => {
      if (prev) {
        prev.on = false;
      }
      return noteToPaint;
    });
  }, [
    activeButton,
    availableNotes,
    floatyNotes,
    genie,
    octaves,
    piano,
    playNoteDown,
    playNoteUp,
  ]);

  useEffect(() => {
    if (onReady && genie && playerReady) onReady();
  }, [genie, onReady, playerReady]);

  return (
    <>

        <canvas></canvas>
        <svg></svg>

      <GenieButtons active={activeButton}></GenieButtons>
    </>
  );
}


text:
<?php

namespace Josser\Exception;

use Josser\Exception\JosserException;
use Josser\Client\Request\RequestInterface;
use Josser\Client\Response\ResponseInterface;

/**
 * Request/Response mismatch exception.
 *
 * @author Alan Gabriel Bem <alan.bem@gmail.com>
 */
class RequestResponseMismatchException extends \RuntimeException implements JosserException
{
    public function __construct(RequestInterface $request, ResponseInterface $response)
    {
        $error = sprintf('Response id (%s) does not match request id (%s).', (string) $response->getId(), (string) $request->getId());
        parent::__construct($error);
    }

}


text:
package be.yurimoens.runemate.clividfarm.task;

import be.yurimoens.runemate.util.CMouse;
import com.runemate.game.api.hybrid.entities.GameObject;
import com.runemate.game.api.hybrid.local.Camera;
import com.runemate.game.api.hybrid.queries.results.LocatableEntityQueryResults;
import com.runemate.game.api.hybrid.region.GameObjects;
import com.runemate.game.api.hybrid.util.Timer;
import com.runemate.game.api.hybrid.util.calculations.Random;
import com.runemate.game.api.script.Execution;
import com.runemate.game.api.script.framework.task.Task;

public class FertilisePatch extends Task {

    private LocatableEntityQueryResults<GameObject> emptyPatches;
    private GameObject emptyPatch;
    private Timer timeout;

    @Override
    public boolean validate() {
        return !(emptyPatches = GameObjects.newQuery().names("Empty patch").filter((GameObject go) -> {
            if (emptyPatch != null) {
                return !go.getPosition().equals(emptyPatch.getPosition());
            } else {
                return true;
            }
        }).results()).isEmpty();
    }

    @Override
    public void execute() {
        emptyPatch = emptyPatches.nearest();

        if (!emptyPatch.isVisible()) {
            Camera.turnTo(emptyPatch, 0.666D);
        }

        if (timeout != null && timeout.isRunning()) {
            emptyPatch.hover();

            Execution.delayWhile(timeout::isRunning);
        }

        CMouse.fastInteract(emptyPatch, "Fertilise");

        timeout = new Timer(Random.nextInt(1350, 1800));
        timeout.start();

        if (GameObjects.newQuery().names("Empty patch").results().size() == 1) {
            Execution.delay(950, 1400);
        }
    }
}


text:
class AddAliasLevelToGroups < ActiveRecord::Migration
  def change
    add_column :groups, :alias_level, :integer, default: 0
  end
end


text:
//
//  OtherViewController.m
//  XXRouter
//
//  Created by Shawn on 2017/5/9.
//  Copyright © 2017年 Shawn. All rights reserved.
//

#import "OtherViewController.h"
#import "TestRouter.h"

@interface OtherViewController ()

@end

@implementation OtherViewController

+ (void)load
{
    XXRouterItem * otherItem = [[XXRouterItem alloc]initWithClassName:NSStringFromClass(self) key:@"other"];
    otherItem.needLogin = YES;
    [[TestRouter shareRouter]reigsterRouterItem:otherItem];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
}

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

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
set -o pipefail
set -e

# https://stackoverflow.com/questions/64786/error-handling-in-bash
error() {
    local parent_lineno="$1"
    local message="$2"
    local code="${3:-1}"
    if [[ -n "$message" ]] ; then
        redEcho "Error on or near line $(caller): ${message}; exiting with status ${code}"
    else
        redEcho "Error on or near line $(caller); exiting with status ${code}"
    fi
    exit "${code}"
}
trap 'error ${LINENO}' ERR

################################################################################
# util functions
################################################################################

# NOTE: $'foo' is the escape sequence syntax of bash
readonly nl=$'\n'
readonly ec=$'\033' # escape char
readonly eend=$'\033[0m' # escape end

colorEcho() {
    local color=$1
    shift

    # if stdout is console, turn on color output.
    [ -t 1 ] && echo "$ec[1;${color}m$@$eend" || echo "$@"
}

redEcho() {
     colorEcho 31 "$@"
}

yellowEcho() {
    colorEcho 33 "$@"
}

runCmd() {
    colorEcho "36" "Run under work directory $PWD :$nl$@"
    "$@"
}

die() {
    redEcho "Error: $@" 1>&2
    exit 1
}

headInfo() {
    colorEcho "0;34;46" ================================================================================
    echo "$@"
    colorEcho "0;34;46" ================================================================================
    echo
}

#################################################################################
# auto adjust pwd to project root dir, and set PROJECT_ROOT_DIR var
#################################################################################
adjustPwdToProjectRootDir() {
    while true; do
        [ / = "$PWD" ] && die "fail to detect project directory!"

        [ -f pom.xml ] && {
            readonly PROJECT_ROOT_DIR="$PWD"
            yellowEcho "Find project root dir: $PWD"
            break
        }
        cd ..
    done
}

adjustPwdToProjectRootDir

#################################################################################
# project common info
#################################################################################

readonly version=`grep '<version>.*</version>' pom.xml | awk -F'</?version>' 'NR==1{print $2}'`
readonly aid=`grep '<artifactId>.*</artifactId>' pom.xml | awk -F'</?artifactId>' 'NR==1{print $2}'`

readonly -a JAVA_CMD=(
    "$JAVA_HOME/bin/java" -Xmx128m -Xms128m -ea -Duser.language=en -Duser.country=US
    ${ENABLE_JAVA_RUN_DEBUG+
        -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005
    }
)

readonly -a MVN_CMD=( ./mvnw ${LOG4J2_VERSION:+-Dlog4j2.version=$LOG4J2_VERSION} )

isLog4j2NotSupportedByJdk() {
    local java_version=$("${JAVA_CMD[@]}" -version 2>&1 | awk '-F"' 'NR==1{print $2}')
    local log4j2_minor_version="$(echo "${LOG4J2_VERSION:-2.11.0}" | awk -F'[.]' '{print $2}')"

    # log4j2 Changelog
    # https://logging.apache.org/log4j/2.x/changelog.html
    #   Log4j 2.4 and greater requires Java 7
    #   versions 2.0-alpha1 to 2.3 required Java 6.
    [[ "$java_version" == 1.6.* ]] && (( log4j2_minor_version >= 4 ))
}

#################################################################################
# maven operation functions
#################################################################################

mvnClean() {
    runCmd ./mvnw clean || die "fail to mvn clean!"
}

mvnBuildJar() {
    # ! build jar do not modify the pom(log4j2 verion) by ${LOG4J2_VERSION:+-Dlog4j2.version=$LOG4J2_VERSION}
    runCmd ./mvnw install -Dmaven.test.skip || die "fail to build jar!"
}

mvnCompileTest() {
    runCmd ./mvnw test-compile || die "fail to mvn test-compile!"
}

mvnCopyDependencies() {
    runCmd "${MVN_CMD[@]}" dependency:copy-dependencies -DincludeScope=test || die "fail to mvn copy-dependencies!"
}

getClasspathOfDependencies() {
    local -r dependencies_dir="target/dependency"

    [ -e "$dependencies_dir" ] || mvnCopyDependencies 1>&2

    echo $dependencies_dir/*.jar | tr ' ' :
}

getClasspathWithoutTargetJar() {
    [ ! -e "target/test-classes/"  -o  "target/test-classes/" -ot src/  ] &&
        mvnCompileTest 1>&2

    echo "target/test-classes:$(getClasspathOfDependencies)"
}

getTargetJarPath() {
    local -r target_jar="target/$aid-$version.jar"

    [ ! -e "$target_jar"  -o  "$target_jar" -ot src/ ] &&
        mvnBuildJar 1>&2

    echo "$target_jar"
}

getClasspath() {
    echo "$(getTargetJarPath):$(getClasspathWithoutTargetJar)"
}

#################################################################################
# maven actions
#################################################################################

runCmd "${MVN_CMD[@]}" --version

if [ "$1" != "skipClean" ]; then
    mvnClean
fi


text:
<?php
namespace migrateur\Console;

use Carbon\Carbon;
use Doctrine\DBAL\Connection;
use migrateur\Models\ConfigModel;
use migrateur\Service\MigrationService;
use Silex\Provider\DoctrineServiceProvider;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class MigrateRunCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('migrate:migrate')
            ->setDescription('Run migrations')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $app = require_once(__DIR__.'/../../../bootstrap.php');
        /** @var ConfigModel $config */
        $config = $app['config'];
        /** @var Connection $db */
        $db = $app['db'];
        $hasRun = false;
        $unRunMigrations = $app['unRunMigrations'];
        foreach ($unRunMigrations as $name) {
            require_once('migrateur/' . $name);
        }
        $initialisedDatabases = array();
        foreach($app['databases'] as $database) {
            $name = $database['dbname'];
            $app->register(new DoctrineServiceProvider(), array(
                'dbs.options' => array(
                    $database['dbname'] => array(
                        'driver' => 'pdo_mysql',
                        'host' => 'localhost',
                        'dbname' => $database['dbname'],
                        'user' => $database['dbusername'],
                        'password' => $database['dbpassword'],
                        //'charset'   => 'utf8mb4',
                    )
                )
            ));
            $initialisedDatabases[$name]=$app['dbs'][$name];
            $app['dbs'][$name]->beginTransaction();
        };
        if(count($unRunMigrations)>0) {
            foreach($initialisedDatabases as $key=>$database) {
                foreach ($unRunMigrations as $name) {
                    $className = substr($name, 0, -4);
                    /** @var MigrationService $migration */
                    $migration = new $className($app);
                    $migration->up();
                    $hasRun = false;
                    $migration->setDb($database);
                    try {
                        if ($migration->isThereQueries()) {
                            if ($migration->run()) {
                                $hasRun = true;
                            }
                        }else{
                            $output->writeln('<info>empty migration line - '.$className.'</info>');
                        }
                    } catch (\Exception $e) {
                        /** @var Connection $db */
                        foreach($initialisedDatabases as $db){
                            $output->writeln('<error>rolling back transactions</error>');
                            $db->rollBack();
                        }
                        throw $e;
                    }
                }
            }

            if($hasRun){

                foreach($initialisedDatabases as $database){
                    $database->commit();
                }

                $table = $config->getMigrationsTable();
                $query = 'INSERT INTO `' . $table . '` (`name`, `created_at`) VALUES ("' . $name . '","' . Carbon::now()->format('Y-m-d H:i:s') . '");';
                $db->exec($query);
                $output->writeln("<info>    Running migration: $name </info>");
            }
        }else{
            $output->writeln("<comment>    All up to date!</comment>");
        }

    }
}


text:
#include "tensorflow/core/profiler/utils/hardware_type_utils.h"

#include "absl/strings/match.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/profiler/protobuf/hardware_types.pb.h"
#include "tensorflow/core/profiler/utils/xplane_schema.h"

namespace tensorflow {
namespace profiler {
namespace {

// Get theoretical upperbound of single precision FMA throughput of the GPU per
// cycle per streaming multiprocessor.
// https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#arithmetic-instructions__throughput-native-arithmetic-instructions
uint32 GetFmaMaxThroughputPerSMPerCycle(const DeviceCapabilities& device_cap) {
  if (device_cap.device_vendor() == kDeviceVendorNvidia) {
    uint32 n_fp32_cores = 0;
    uint32 n_tc_cores = 0;
    switch (device_cap.compute_capability().major()) {
      case 2:
        // Fermi
        n_fp32_cores = 32;
        break;
      case 3:
        // Kepler
        n_fp32_cores = 192;
        break;
      case 5:
        // Maxwell
        n_fp32_cores = 128;
        break;
      case 6:
        // Pascal
        if (device_cap.compute_capability().minor() > 0) {
          // Pascal SM61/62
          n_fp32_cores = 128;
        } else {
          // Pascal SM60
          n_fp32_cores = 64;
        }
        break;
      case 7:
        // Volta and Turing
        n_fp32_cores = 64;
        n_tc_cores = 8;
        break;
      case 8:
        // Ampere
        if (device_cap.compute_capability().minor() >= 6) {
          // Ampere SM86
          n_fp32_cores = 128;
        } else {
          // Ampere SM80
          n_fp32_cores = 64;
        }
        n_tc_cores = 4;
        break;
      default:
        LOG(ERROR) << "Invalid GPU compute capability.";
        break;
    }
    // GPU TensorCore can execute 64 FMAs per cycle.
    // https://devblogs.nvidia.com/programming-tensor-cores-cuda-9/
    return n_fp32_cores + n_tc_cores * 64;
  } else if (device_cap.device_vendor() == kDeviceVendorAMD) {
    uint32_t n_xdlops = 0;
    uint32_t n_fp32_cores = 0;

    if (device_cap.compute_capability().major() <= 9) {
      n_fp32_cores = 64;
    } else {
      n_fp32_cores = 32;
    }
    // TODO(rocm-profiler): verify with new devices
    return n_fp32_cores + n_xdlops * 1;
  } else {
    LOG(ERROR) << "Unknown device vendor " << device_cap.device_vendor();
    return 0;
  }
}

}  // namespace

double GetFlopMaxThroughputPerSM(const DeviceCapabilities& device_cap) {
  // One FMA = 2 floating point operations, one multiply and one add.
  return GetFmaMaxThroughputPerSMPerCycle(device_cap) * 2 *
         device_cap.clock_rate_in_ghz();
}

absl::string_view GpuModelName(const DeviceCapabilities& device_cap) {
  if (device_cap.device_vendor() == kDeviceVendorNvidia) {
    switch (device_cap.compute_capability().major()) {
      case 2:
        return "Nvidia GPU (Fermi)";
      case 3:
        return "Nvidia GPU (Kepler)";
      case 5:
        return "Nvidia GPU (Maxwell)";
      case 6:
        return "Nvidia GPU (Pascal)";
      case 7:
        if (device_cap.compute_capability().minor() < 5) {
          return "Nvidia GPU (Volta)";
        } else {
          return "Nvidia GPU (Turing)";
        }
      case 8:
        return "Nvidia GPU (Ampere)";
      default:
        return "Nvidia GPU";
    }
  } else if (device_cap.device_vendor() == kDeviceVendorAMD) {
    switch (device_cap.compute_capability().major()) {
      case 9:
        return "AMD GPU - gfx-9XX series";
      case 10:
        return "AMD GPU - gfx-10XX series";
      case 11:
        return "AMD GPU - gfx-11XX series";
      default:
        return "AMD GPU";
    }
  } else {
    LOG(ERROR) << "Unknown device vendor " << device_cap.device_vendor();
    return "";
  }
}

HardwareType ParseHardwareType(absl::string_view device_type) {
  if (absl::StrContains(device_type, "GPU")) return HardwareType::GPU;
  if (device_type == "CPU") return HardwareType::CPU_ONLY;
  if (device_type == "TPU") return HardwareType::TPU;
  return HardwareType::UNKNOWN_HARDWARE;
}

bool HasDevice(HardwareType x) { return x > tensorflow::profiler::CPU_ONLY; }

}  // namespace profiler
}  // namespace tensorflow


text:
import { distributionsActions } from 'actions';

const initialState = {
  loading: false,
  error: false,
  done: false,
  data: {},
};

export default (state = initialState, action) => {
  switch (action.type) {
    case distributionsActions.REQUEST:
      return {
        ...state,
        loading: true,
        done: false,
        error: false,
      };
    case distributionsActions.OK:
      return {
        ...state,
        loading: false,
        done: true,
        error: false,
        data: action.payload,
      };
    case distributionsActions.ERROR:
      return {
        ...state,
        loading: false,
        done: false,
        error: true,
      };
    default:
      return state;
  }
};


text:
import { Injectable, Component } from "angular2/core";
import { ArcVault } from "./mock-arc-items";
import { ArcItem } from "./arc-item.model";

@Injectable()
export class ArcService {
  getAllItems() {
    return ArcVault;
  }

  insertItem(item: ArcItem) {
    ArcVault.push(item);
  }

  deleteItem(item: ArcItem) {
    ArcVault.splice(ArcVault.indexOf(item), 1);
  }
}


text:
package com.yolodata.tbana.hadoop.mapred.splunk.inputformat;

import com.yolodata.tbana.hadoop.mapred.splunk.SplunkInputFormat;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.util.Tool;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

class TestMapper extends MapReduceBase implements Mapper<LongWritable, List<Text>, LongWritable, Text> {

    @Override
    public void map(LongWritable key, List<Text> values, OutputCollector<LongWritable, Text> outputCollector, Reporter reporter) throws IOException {
        Text output = new Text(StringUtils.join(values, ","));
        outputCollector.collect(key, output);
    }
}

class TestReducer extends MapReduceBase implements Reducer<LongWritable, Text, LongWritable, Text> {
    @Override
    public void reduce(LongWritable longWritable, Iterator<Text> textIterator, OutputCollector<LongWritable, Text> longWritableTextOutputCollector, Reporter reporter) throws IOException {
        while(textIterator.hasNext())
            longWritableTextOutputCollector.collect(longWritable,textIterator.next());
    }
}

class SplunkTestRunner extends Configured implements Tool {

    public int run(String[] args) throws Exception {
        JobConf jobConf = new JobConf(getConf());

        jobConf.set(SplunkInputFormat.INPUTFORMAT_MODE,args[0]);
        jobConf.setJarByClass(SplunkTestRunner.class);
        jobConf.setNumReduceTasks(1);
        jobConf.setMapperClass(TestMapper.class);
        jobConf.setReducerClass(TestReducer.class);

        jobConf.setInputFormat(SplunkInputFormat.class);
        jobConf.setOutputKeyClass(LongWritable.class);
        jobConf.setOutputValueClass(Text.class);

        TextOutputFormat.setOutputPath(jobConf ,new Path(args[1]));

        JobClient.runJob(jobConf);

        return 0;
    }

    public SplunkTestRunner(Configuration conf) {
        super(conf);
    }
}


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="wrap_content"
    android:background="@color/ebpay_black_transparent"
    android:gravity="center"
    android:paddingBottom="20dp"
    android:paddingLeft="30dp"
    android:paddingRight="30dp"
    android:paddingTop="20dp" >

    <ProgressBar
        android:id="@+id/loading_progress_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:indeterminateDrawable="@drawable/ebpay_loading"
        android:minHeight="33.5dp"
        android:minWidth="28.5dp" />

    <TextView
        android:id="@+id/dialog_msg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:text="@string/ebpay_safe_handle"
        android:textColor="@color/ebpay_white" />

</LinearLayout>


text:
source test.functions

testAdvertisedListeners() {
	# Given a hostname is provided
	export KAFKA_ADVERTISED_LISTENERS="PLAINTEXT://my.domain.com:9040"
	export KAFKA_LISTENERS="PLAINTEXT://:9092"

	# When the script is invoked
	source "$START_KAFKA"

	# Then the configuration file is correct
	assertExpectedConfig 'advertised.listeners=PLAINTEXT://my.domain.com:9040'
	assertExpectedConfig 'listeners=PLAINTEXT://:9092'
}

testAdvertisedListeners


text:
Param(
  [string]$arch,
  [string]$mixinPassword,
  [string]$vsoPAT
)

. .\build\tfs\win32\node.ps1
. .\scripts\env.ps1
. .\build\tfs\win32\lib.ps1

# Create a _netrc file to download distro dependencies
# In order to get _netrc to work, we need a HOME variable setup
"machine monacotools.visualstudio.com password ${vsoPAT}" | Out-File "$env:HOME\_netrc" -Encoding ASCII

# Set the right architecture
$env:npm_config_arch="$arch"
$env:CHILD_CONCURRENCY="1"

step "Install dependencies" {
  exec { & yarn }
}

step "Hygiene" {
  exec { & npm run gulp -- hygiene }
}

step "Monaco Editor Check" {
	exec { & .\node_modules\.bin\tsc -p .\src\tsconfig.monaco.json --noEmit }
}

$env:VSCODE_MIXIN_PASSWORD = $mixinPassword
step "Mix in repository from vscode-distro" {
  exec { & npm run gulp -- mixin }
}

step "Get Electron" {
  exec { & npm run gulp -- "electron-$global:arch" }
}

step "Install distro dependencies" {
  exec { & node build\tfs\common\installDistro.js }
}

step "Build minified" {
  exec { & npm run gulp -- "vscode-win32-$global:arch-min" }
}

step "Copy Inno updater" {
  exec { & npm run gulp -- "vscode-win32-$global:arch-copy-inno-updater" }
}

# step "Create loader snapshot" {
#   exec { & 	node build\lib\snapshotLoader.js --arch=$global:arch }
# }

step "Run unit tests" {
  exec { & .\scripts\test.bat --build --reporter dot }
}

# step "Run integration tests" {
#   exec { & .\scripts\test-integration.bat }
# }

# step "Run smoke test" {
# 	$Artifacts = "$env:AGENT_BUILDDIRECTORY\smoketest-artifacts"
# 	Remove-Item -Recurse -Force -ErrorAction Ignore $Artifacts

# 	exec { & npm run smoketest -- --build "$env:AGENT_BUILDDIRECTORY\VSCode-win32-$global:arch" --log "$Artifacts" }
# }

done


text:
package de.timroes.axmlrpc;

/**
 * The XMLRPCCallback interface must be implemented by a listener for an
 * asynchronous call to a server method.
 * When the server responds, the corresponding method on the listener is called.
 *
 * @author Tim Roes
 */
public interface XMLRPCCallback {

    /**
     * This callback is called whenever the server successfully responds.
     *
     * @param id     The id as returned by the XMLRPCClient.asyncCall(..) method for this request.
     * @param result The Object returned from the server.
     */
    public void onResponse(long id, Object result);

    /**
     * This callback is called whenever an error occurs during the method call.
     *
     * @param id    The id as returned by the XMLRPCClient.asyncCall(..) method for this request.
     * @param error The error occured.
     */
    public void onError(long id, XMLRPCException error);

    /**
     * This callback is called whenever the server returns an error.
     *
     * @param id    The id as returned by the XMLRPCClient.asyncCall(..) method for this request.
     * @param error The error returned from the server.
     */
    public void onServerError(long id, XMLRPCServerException error);

}


text:
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _FormGroup = require('./FormGroup');

var _FormGroup2 = _interopRequireDefault(_FormGroup);

var InputBase = (function (_React$Component) {
  function InputBase() {
    _classCallCheck(this, InputBase);

    _get(Object.getPrototypeOf(InputBase.prototype), 'constructor', this).apply(this, arguments);
  }

  _inherits(InputBase, _React$Component);

  _createClass(InputBase, [{
    key: 'getInputDOMNode',
    value: function getInputDOMNode() {
      return _react2['default'].findDOMNode(this.refs.input);
    }
  }, {
    key: 'getValue',
    value: function getValue() {
      if (this.props.type === 'static') {
        return this.props.value;
      } else if (this.props.type) {
        if (this.props.type === 'select' && this.props.multiple) {
          return this.getSelectedOptions();
        } else {
          return this.getInputDOMNode().value;
        }
      } else {
        throw 'Cannot use getValue without specifying input type.';
      }
    }
  }, {
    key: 'getChecked',
    value: function getChecked() {
      return this.getInputDOMNode().checked;
    }
  }, {
    key: 'getSelectedOptions',
    value: function getSelectedOptions() {
      var values = [];

      Array.prototype.forEach.call(this.getInputDOMNode().getElementsByTagName('option'), function (option) {
        if (option.selected) {
          var value = option.getAttribute('value') || option.innerHtml;
          values.push(value);
        }
      });

      return values;
    }
  }, {
    key: 'isCheckboxOrRadio',
    value: function isCheckboxOrRadio() {
      return this.props.type === 'checkbox' || this.props.type === 'radio';
    }
  }, {
    key: 'isFile',
    value: function isFile() {
      return this.props.type === 'file';
    }
  }, {
    key: 'renderInputGroup',
    value: function renderInputGroup(children) {
      var addonBefore = this.props.addonBefore ? _react2['default'].createElement(
        'span',
        { className: 'input-group-addon', key: 'addonBefore' },
        this.props.addonBefore
      ) : null;

      var addonAfter = this.props.addonAfter ? _react2['default'].createElement(
        'span',
        { className: 'input-group-addon', key: 'addonAfter' },
        this.props.addonAfter
      ) : null;

      var buttonBefore = this.props.buttonBefore ? _react2['default'].createElement(
        'span',
        { className: 'input-group-btn' },
        this.props.buttonBefore
      ) : null;

      var buttonAfter = this.props.buttonAfter ? _react2['default'].createElement(
        'span',
        { className: 'input-group-btn' },
        this.props.buttonAfter
      ) : null;

      var inputGroupClassName = undefined;
      switch (this.props.bsSize) {
        case 'small':
          inputGroupClassName = 'input-group-sm';break;
        case 'large':
          inputGroupClassName = 'input-group-lg';break;
      }

      return addonBefore || addonAfter || buttonBefore || buttonAfter ? _react2['default'].createElement(
        'div',
        { className: (0, _classnames2['default'])(inputGroupClassName, 'input-group'), key: 'input-group' },
        addonBefore,
        buttonBefore,
        children,
        addonAfter,
        buttonAfter
      ) : children;
    }
  }, {
    key: 'renderIcon',
    value: function renderIcon() {
      var classes = {
        'glyphicon': true,
        'form-control-feedback': true,
        'glyphicon-ok': this.props.bsStyle === 'success',
        'glyphicon-warning-sign': this.props.bsStyle === 'warning',
        'glyphicon-remove': this.props.bsStyle === 'error'
      };

      return this.props.hasFeedback ? _react2['default'].createElement('span', { className: (0, _classnames2['default'])(classes), key: 'icon' }) : null;
    }
  }, {
    key: 'renderHelp',
    value: function renderHelp() {
      return this.props.help ? _react2['default'].createElement(
        'span',
        { className: 'help-block', key: 'help' },
        this.props.help
      ) : null;
    }
  }, {
    key: 'renderCheckboxAndRadioWrapper',
    value: function renderCheckboxAndRadioWrapper(children) {
      var classes = {
        'checkbox': this.props.type === 'checkbox',
        'radio': this.props.type === 'radio'
      };

      return _react2['default'].createElement(
        'div',
        { className: (0, _classnames2['default'])(classes), key: 'checkboxRadioWrapper' },
        children
      );
    }
  }, {
    key: 'renderWrapper',
    value: function renderWrapper(children) {
      return this.props.wrapperClassName ? _react2['default'].createElement(
        'div',
        { className: this.props.wrapperClassName, key: 'wrapper' },
        children
      ) : children;
    }
  }, {
    key: 'renderLabel',
    value: function renderLabel(children) {
      var classes = {
        'control-label': !this.isCheckboxOrRadio()
      };
      classes[this.props.labelClassName] = this.props.labelClassName;

      return this.props.label ? _react2['default'].createElement(
        'label',
        { htmlFor: this.props.id, className: (0, _classnames2['default'])(classes), key: 'label' },
        children,
        this.props.label
      ) : children;
    }
  }, {
    key: 'renderInput',
    value: function renderInput() {
      if (!this.props.type) {
        return this.props.children;
      }

      switch (this.props.type) {
        case 'select':
          return _react2['default'].createElement(
            'select',
            _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, 'form-control'), ref: 'input', key: 'input' }),
            this.props.children
          );
        case 'textarea':
          return _react2['default'].createElement('textarea', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, 'form-control'), ref: 'input', key: 'input' }));
        case 'static':
          return _react2['default'].createElement(
            'p',
            _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, 'form-control-static'), ref: 'input', key: 'input' }),
            this.props.value
          );
      }

      var className = this.isCheckboxOrRadio() || this.isFile() ? '' : 'form-control';
      return _react2['default'].createElement('input', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, className), ref: 'input', key: 'input' }));
    }
  }, {
    key: 'renderFormGroup',
    value: function renderFormGroup(children) {
      return _react2['default'].createElement(
        _FormGroup2['default'],
        this.props,
        children
      );
    }
  }, {
    key: 'renderChildren',
    value: function renderChildren() {
      return !this.isCheckboxOrRadio() ? [this.renderLabel(), this.renderWrapper([this.renderInputGroup(this.renderInput()), this.renderIcon(), this.renderHelp()])] : this.renderWrapper([this.renderCheckboxAndRadioWrapper(this.renderLabel(this.renderInput())), this.renderHelp()]);
    }
  }, {
    key: 'render',
    value: function render() {
      var children = this.renderChildren();
      return this.renderFormGroup(children);
    }
  }]);

  return InputBase;
})(_react2['default'].Component);

InputBase.propTypes = {
  type: _react2['default'].PropTypes.string,
  label: _react2['default'].PropTypes.node,
  help: _react2['default'].PropTypes.node,
  addonBefore: _react2['default'].PropTypes.node,
  addonAfter: _react2['default'].PropTypes.node,
  buttonBefore: _react2['default'].PropTypes.node,
  buttonAfter: _react2['default'].PropTypes.node,
  bsSize: _react2['default'].PropTypes.oneOf(['small', 'medium', 'large']),
  bsStyle: _react2['default'].PropTypes.oneOf(['success', 'warning', 'error']),
  hasFeedback: _react2['default'].PropTypes.bool,
  id: _react2['default'].PropTypes.string,
  groupClassName: _react2['default'].PropTypes.string,
  wrapperClassName: _react2['default'].PropTypes.string,
  labelClassName: _react2['default'].PropTypes.string,
  multiple: _react2['default'].PropTypes.bool,
  disabled: _react2['default'].PropTypes.bool,
  value: _react2['default'].PropTypes.any
};

exports['default'] = InputBase;
module.exports = exports['default'];


text:
'use strict';

const symphonySelector = '.player-PlayerInfo__infoEl--2jhHY span:nth-child(3) span:first-child';
const commonNameSelector = '.player-PlayerInfo__infoEl--2jhHY span:nth-child(3) span:nth-child(2)';
const directorSelector = '.player-PlayerInfo__recordingInfo--15VMv>span:first-child span';
const trackSelector = '.player-PlayerInfo__infoEl--2jhHY';
const pauseButtonSelector = '.player-PlayerControls__btn--1r-vy:nth-child(2) .util-IconLabel__component--3Uitr span';

Connector.playerSelector = '.player-PlayerBar__bar--2yos_';

Connector.artistSelector = '.player-PlayerInfo__infoEl--2jhHY span:first-child';

Connector.getTrack = getCurrentTrack;

Connector.getAlbum = getCurrentSymphony;

Connector.currentTimeSelector = '.player-PlayerProgress__progress--2F0qB>span';

Connector.durationSelector = '.player-PlayerProgress__timeTotal--3aHlj span';

Connector.isPlaying = () => Util.getTextFromSelectors(pauseButtonSelector) === 'Pause';

Connector.isScrobblingAllowed = () => Util.getTextFromSelectors('.player-PlayerInfo__recordingInfo--15VMv') !== 'Sponsor message';

function getCurrentTrack() {
	/*
	 * Idagio puts composer and piece all in the same div element, so we have to undo this.
	 * First split the tag by dashes. Include spaces to avoid issues with names containing dashes.
	 * The first part is the composer name. We want to exclude this, so we slice it off.
	 * Then, replace the dashes with colons, this makes the tag more in line with what is expected.
	 * Finally, trim as a "just in case" in preparation for the next step. Unnecessary in the cases I've seen, but extremely simple and might prevent something down the line.
	 * Example from https://app.idagio.com/albums/saint-saens-violin-sonata-no-1-cello-sonata-no-1-and-piano-trio-no-2:
	 * "Camille Saint-Saëns – Sonata for Violin and Piano No. 1 in D minor op. 75 R 123 – I. Allegro agitato –"
	 * -> ["Camille Saint-Saëns", "Sonata for Violin and Piano No. 1 in D minor op. 75 R 123", "I. Allegro agitato –"]
	 * -> ["Sonata for Violin and Piano No. 1 in D minor op. 75 R 123", "I. Allegro agitato –"]
	 * -> "Sonata for Violin and Piano No. 1 in D minor op. 75 R 123: I. Allegro agitato –"
	 */
	let track = Util.getTextFromSelectors(trackSelector).split(' – ').slice(1).join(': ').trim();
	/*
	 * Now remove trailing dash if exists.
	 * Example: "Sonata for Violin and Piano No. 1 in D minor op. 75 R 123: I. Allegro agitato –"
	 * -> "Sonata for Violin and Piano No. 1 in D minor op. 75 R 123: I. Allegro agitato " (the space is trimmed later in core)
	 */
	if (track.slice(-1) === '–') {
		track = track.slice(0, -1);
	}
	return track;
}

function getCurrentSymphony() {
	const symphonyShort = Util.getTextFromSelectors(symphonySelector).split(/ in [A-G]| op. [0-9]| KV [0-9]/)[0];
	const commonName = Util.getTextFromSelectors(commonNameSelector) || '';
	const director = removeParenthesis(Util.getTextFromSelectors(directorSelector));
	return `${symphonyShort}${commonName} (${director})`;
}

function removeParenthesis(text) {
	return text.replace(/\s*\(.*?\)\s*/g, '');
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <link rel="stylesheet" href="/assets/css/main.css">

    <link rel="shortcut icon" href="/assets/favicon.ico" type="image/x-icon">

    <link rel="canonical" href="http://172.17.1.189:40001/portfolio/hanoi">

    <link rel="alternate" type="application/atom+xml" title="程序员游记" href="http://172.17.1.189:40001///feed.xml"/>

    <link rel="stylesheet" type="text/css" href="/assets/css/font-awesome.min.css">

    <link href="//fonts.googleapis.com/css?family=Source+Sans+Pro:400,700,700italic,400italic" rel="stylesheet" type="text/css">

    <link rel="stylesheet" type="text/css" href="/assets/css/katex.min.css">

<title>Tower of Hanoi</title>
<meta property="og:title" content="Tower of Hanoi" />
<meta property="og:locale" content="en_US" />
<link rel="canonical" href="http://172.17.1.189:40001/portfolio/hanoi" />
<meta property="og:url" content="http://172.17.1.189:40001/portfolio/hanoi" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2014-09-01T00:00:00+08:00" />

			程序员游记

                Search

                Tags

Tower of Hanoi

    September 1, 2014

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?

转载本站文章时请标明出处和作者


text:
namespace Envoy {
namespace Network {

namespace {
Address::IpVersion getVersionFromAddress(Address::InstanceConstSharedPtr addr) {
  if (addr->ip() != nullptr) {
    return addr->ip()->version();
  }
  throw EnvoyException("Unable to set socket option on non-IP sockets");
}

absl::optional<Address::IpVersion> getVersionFromSocket(const Socket& socket) {
  try {
    // We have local address when the socket is used in a listener but have to
    // infer the IP from the socket FD when initiating connections.
    // TODO(htuch): Figure out a way to obtain a consistent interface for IP
    // version from socket.
    if (socket.localAddress()) {
      return {getVersionFromAddress(socket.localAddress())};
    } else {
      return {getVersionFromAddress(Address::addressFromFd(socket.ioHandle().fd()))};
    }
  } catch (const EnvoyException&) {
    // Ignore, we get here because we failed in getsockname().
    // TODO(htuch): We should probably clean up this logic to avoid relying on exceptions.
  }

  return absl::nullopt;
}

SocketOptionImplOptRef getOptionForSocket(const Socket& socket, SocketOptionImpl& ipv4_option,
                                          SocketOptionImpl& ipv6_option) {
  auto version = getVersionFromSocket(socket);
  if (!version.has_value()) {
    return absl::nullopt;
  }

  // If the FD is v4, we can only try the IPv4 variant.
  if (*version == Network::Address::IpVersion::v4) {
    return {ipv4_option};
  }
  // If the FD is v6, we first try the IPv6 variant if the platform supports it and fallback to the
  // IPv4 variant otherwise.
  ASSERT(*version == Network::Address::IpVersion::v6);
  if (ipv6_option.isSupported()) {
    return {ipv6_option};
  }
  return {ipv4_option};
}

} // namespace

bool AddrFamilyAwareSocketOptionImpl::setOption(
    Socket& socket, envoy::config::core::v3::SocketOption::SocketState state) const {
  return setIpSocketOption(socket, state, ipv4_option_, ipv6_option_);
}

absl::optional<Socket::Option::Details> AddrFamilyAwareSocketOptionImpl::getOptionDetails(
    const Socket& socket, envoy::config::core::v3::SocketOption::SocketState state) const {
  auto option = getOptionForSocket(socket, *ipv4_option_, *ipv6_option_);

  if (!option.has_value()) {
    return absl::nullopt;
  }

  return option->get().getOptionDetails(socket, state);
}

bool AddrFamilyAwareSocketOptionImpl::setIpSocketOption(
    Socket& socket, envoy::config::core::v3::SocketOption::SocketState state,
    const std::unique_ptr<SocketOptionImpl>& ipv4_option,
    const std::unique_ptr<SocketOptionImpl>& ipv6_option) {
  auto option = getOptionForSocket(socket, *ipv4_option, *ipv6_option);

  if (!option.has_value()) {
    ENVOY_LOG(warn, "Failed to set IP socket option on non-IP socket");
    return false;
  }

  return option->get().setOption(socket, state);
}

} // namespace Network
} // namespace Envoy


text:
.. Sajou documentation master file, created by
   sphinx-quickstart on Sun Feb 26 15:52:22 2017.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Sajou
=====

Introduction
------------
Sajou is a simple Structural Analysis module for Python, that enables the static computation of 2D structures.
It implements the finite element method with a *civil engineering* oriented approach, that allows the obtention of relevant information,
like moments and axial forces of beams, in an easy manner.

Although currently only 2D models are implemented, the code has been designed with 3D support in mind, and will be implemented at
some point in the future.
In a similar way, the element library should be expanded in the future, implementing diverse and useful elements like plates or shells.

.. warning:: Sajou is currently in a very early stage of development. As such, expect major bugs, radical
    changes in the API, inexplicably burn down of your computer and sudden deaths of kittens. Use under your own
    responsability.

Contents
--------

.. toctree::
    :maxdepth: 1

    install
    quickstart
    tutorial/index
    doc/index
    apiref/index

Indices and tables
------------------

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
/**
 * @file callback_send_impl.cpp
 * @author
 * @date 2012/11/13 11:27:56
 * @version 1.0.0
 * @brief
 *
 **/

#include <bgcc.h>
#include "callback_send_impl.h"

std::map<std::string, demo::SSLCallbackRecverProxy*> g_proxys;
bgcc::Mutex g_mutex;

demo::CallbackResult callback_send_impl_t::AddClient(
        const std::map<std::string, std::string>& ctx)
{
    std::map<std::string, std::string>::const_iterator it = ctx.find("ProxyName");

    if (it == ctx.end()) {
        BGCC_WARN("server", "not find proxyname in contex");
        return demo::CallbackResult(demo::CallbackResult::R_FAIL);
    }

    bgcc::Guard<bgcc::Mutex> lock(&g_mutex);
    if (!lock.is_locked()) {
        BGCC_WARN("server", "lock failed");
        return demo::CallbackResult(demo::CallbackResult::R_FAIL);
    }

    if (g_proxys.find(it->second) != g_proxys.end()) {
        BGCC_WARN("server", "proxy name:%s is exists", it->second.c_str());
        return demo::CallbackResult(demo::CallbackResult::R_FAIL);
    }

    demo::SSLCallbackRecverProxy * px = new(std::nothrow) demo::SSLCallbackRecverProxy(it->second, 1);

    if (!px) {
        BGCC_WARN("server", "create proxy(%s) failed", it->second.c_str());
        return demo::CallbackResult(demo::CallbackResult::R_FAIL);
    }

    g_proxys.insert(std::pair<std::string, demo::SSLCallbackRecverProxy*>(it->second.c_str() , px));

    BGCC_TRACE("server", "Add Client %s SUCC", it->second.c_str());
    return demo::CallbackResult(demo::CallbackResult::R_SUCC);
}

demo::CallbackResult callback_send_impl_t::DelClient(
        const std::map<std::string, std::string>& ctx)
{

    std::map<std::string, std::string>::const_iterator it = ctx.find("ProxyName");

    if (it == ctx.end()) {
        BGCC_WARN("server", "not find proxyname in contex");
        return demo::CallbackResult(demo::CallbackResult::R_FAIL);
    }

    bgcc::Guard<bgcc::Mutex> lock(&g_mutex);
    if (!lock.is_locked()) {
        BGCC_WARN("server", "lock failed");
        return demo::CallbackResult(demo::CallbackResult::R_FAIL);
    }

    if (g_proxys.find(it->second) == g_proxys.end()) {
        BGCC_WARN("server", "proxy name:%s is not exists", it->second.c_str());
        return demo::CallbackResult(demo::CallbackResult::R_FAIL);
    }

    demo::SSLCallbackRecverProxy* proxy = g_proxys[it->second];

    g_proxys.erase(it->second);

    delete proxy;
    proxy = NULL;

    BGCC_TRACE("server", "Del Client %s SUCC", it->second.c_str());
    return demo::CallbackResult(demo::CallbackResult::R_SUCC);
}

int32_t callback_send_thrd_t::operator()(const bool * isstopped, void* /*arg*/)
{
    int32_t count = 0;
    while (!(*isstopped)) {
        bgcc::TimeUtil::safe_sleep_s(1);
        {
            bgcc::Guard<bgcc::Mutex> lock(&g_mutex);
            if (!lock.is_locked()) {
                continue;
            }

            if (!g_proxys.size()) {
                continue;
            }
            ++count;
            for (std::map<std::string, demo::SSLCallbackRecverProxy* >::iterator it = g_proxys.begin();
                    it != g_proxys.end();) {
                BGCC_TRACE("server", "callback begin");
                it->second->Callback(count);
                BGCC_TRACE("server", "callback end{%d} {%s}", it->second->get_errno(), strerror(it->second->get_errno()));
                if (it->second->get_errno()) {
                    delete it->second;
                    g_proxys.erase(it++);
				} else {
					++it;
				}
            }
        }
    }

    return 0;
}

/* vim: set ts=4 sw=4 sts=4 tw=100 noet: */


text:
package org.apache.heron.healthmgr.common;

import java.util.HashSet;

import com.microsoft.dhalion.events.EventManager;

import org.junit.Assert;
import org.junit.Test;

import org.apache.heron.healthmgr.common.HealthManagerEvents.TopologyUpdate;
import org.apache.heron.packing.roundrobin.RoundRobinPacking;
import org.apache.heron.proto.system.PackingPlans;
import org.apache.heron.spi.packing.PackingPlan;
import org.apache.heron.spi.statemgr.SchedulerStateManagerAdaptor;
import org.apache.heron.spi.utils.PackingTestUtils;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class PackingPlanProviderTest {
  private String topologyName = "topologyName";
  private EventManager eventManager = new EventManager();

  @Test
  public void fetchesAndCachesPackingFromStateMgr() {
    PackingPlans.PackingPlan proto
        = PackingTestUtils.testProtoPackingPlan(topologyName, new RoundRobinPacking());

    SchedulerStateManagerAdaptor adaptor = mock(SchedulerStateManagerAdaptor.class);
    when(adaptor.getPackingPlan(topologyName)).thenReturn(proto);

    PackingPlanProvider provider = new PackingPlanProvider(adaptor, eventManager, topologyName);
    PackingPlan packing = provider.get();
    Assert.assertEquals(1, packing.getContainers().size());

    // once fetched it is cached
    provider.get();
    verify(adaptor, times(1)).getPackingPlan(topologyName);
  }

  @Test
  public void refreshesPackingPlanOnUpdate() {
    PackingPlans.PackingPlan proto
        = PackingTestUtils.testProtoPackingPlan(topologyName, new RoundRobinPacking());

    SchedulerStateManagerAdaptor adaptor = mock(SchedulerStateManagerAdaptor.class);
    when(adaptor.getPackingPlan(topologyName)).thenReturn(proto);

    PackingPlanProvider provider = new PackingPlanProvider(adaptor, eventManager, topologyName);
    PackingPlan packing = provider.get();
    Assert.assertEquals(1, packing.getContainers().size());

    provider.onEvent(new TopologyUpdate(null, null));
    provider.get();
    verify(adaptor, times(2)).getPackingPlan(topologyName);
  }

  @Test
  public void providesBoltInstanceNames() {
    PackingPlans.PackingPlan proto
        = PackingTestUtils.testProtoPackingPlan(topologyName, new RoundRobinPacking());

    SchedulerStateManagerAdaptor adaptor = mock(SchedulerStateManagerAdaptor.class);
    when(adaptor.getPackingPlan(topologyName)).thenReturn(proto);

    PackingPlanProvider packing = new PackingPlanProvider(adaptor, eventManager, topologyName);

    String[] boltNames = packing.getBoltInstanceNames("testBolt");
    assertEquals(3, boltNames.length);

    HashSet<String> expectedBoltNames = new HashSet<>();
    expectedBoltNames.add("container_1_testBolt_3");
    expectedBoltNames.add("container_1_testBolt_4");
    expectedBoltNames.add("container_1_testBolt_5");

    for (String name : boltNames) {
      expectedBoltNames.remove(name);
    }
    assertEquals(0, expectedBoltNames.size());
  }
}


text:
from __future__ import absolute_import, print_function, unicode_literals
from datetime import datetime
try:
    import mock
except ImportError:
    import unittest.mock as mock

def test_indexer_on_save():
    db = mock.Mock()
    archivist = mock.Mock()
    archivist.bucket = 'test-bucket'
    resource = mock.Mock()
    resource.data = {
        "Item": {
            "itemtype": "Item/Page/Article/Blogpost",
            "updated": datetime.now().isoformat(),
            "guid": "test-guid",
            "category": {"name": "test/category"}
        }
    }

    from webquills.indexer.item import on_save
    on_save(db, archivist, resource)
    db.Table().put_item.assert_called_with(Item=mock.ANY)

def test_indexer_on_remove():
    db = mock.Mock()
    archivist = mock.Mock()
    archivist.bucket = 'test-bucket'
    key = "_A/Item/Page/Article/Blogpost/asdf.json"

    expect_key = {
        "bucket_itemclass": "test-bucket|Item/Page/Article",
        "s3key": "_A/Item/Page/Article/Blogpost/asdf.json"
    }
    from webquills.indexer.item import on_remove
    on_remove(db, archivist, key)
    db.Table().delete_item.assert_called_with(Key=expect_key)


text:
package io.kimo.base.example.data;

import java.io.Serializable;

public class Student implements Serializable {
    private String name;
    private String description;
    private String course;
    private String imageUrl;

    public Student(String name, String description, String imageUrl, String course) {
        this.name = name;
        this.description = description;
        this.imageUrl = imageUrl;
        this.course = course;
    }

    public String getName() {
        return name;
    }

    public String getCourse() {
        return course;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public String getDescription() {
        return description;
    }
}