text:
'use strict';

const Gatherer = require('./gatherer');

/**
 * This gatherer changes the options.url so that its pass loads the http page.
 * After load it detects if its on a crypographic scheme.
 * TODO: Instead of abusing a loadPage pass for this test, it could likely just do an XHR instead
 */
class HTTPRedirect extends Gatherer {
  constructor() {
    super();
    this._preRedirectURL = undefined;
  }

  beforePass(options) {
    this._preRedirectURL = options.url;
    options.url = this._preRedirectURL.replace(/^https/, 'http');
  }

  afterPass(options) {
    // Reset the options.
    options.url = this._preRedirectURL;

    // Allow override for faster testing.
    const timeout = options._testTimeout || 10000;

    const securityPromise = options.driver.getSecurityState()
      .then(state => {
        return {
          value: state.schemeIsCryptographic,
        };
      });

    let noSecurityChangesTimeout;
    const timeoutPromise = new Promise((resolve, reject) => {
      // Set up a timeout for ten seconds in case we don't get any
      // security events at all. If that happens, bail.
      noSecurityChangesTimeout = setTimeout(_ => {
        reject(new Error('Timed out waiting for HTTP redirection.'));
      }, timeout);
    });

    return Promise.race([
      securityPromise,
      timeoutPromise,
    ]).then(result => {
      // Clear timeout. No effect if it won, no need to wait if it lost.
      clearTimeout(noSecurityChangesTimeout);
      return result;
    }).catch(err => {
      clearTimeout(noSecurityChangesTimeout);
      throw err;
    });
  }
}

module.exports = HTTPRedirect;

redpajama_set_name: RedPajamaGithub


text:
from dstools.pipeline.CodeDiffer import CodeDiffer

def test_python_differ_ignores_docstrings():

    a = '''
def x():
    """This is some docstring
    """
    pass
'''

    b = '''
def x():
    """This is a docstring and should be ignored
    """
    pass
'''

    differ = CodeDiffer()
    assert not differ.code_is_different(a, b, language='python')

def test_python_differ_ignores_comments():

    a = '''
def x():
    # this is a comment
    # another comment
    var = 100
'''

    b = '''
def x():
    # one comment
    var = 100 # this is a comment
'''

    differ = CodeDiffer()
    assert not differ.code_is_different(a, b, language='python')


text:
"""Unit test cases for the GenISOImage class."""

import logging

from distutils.version import StrictVersion
import mock

from COT.helpers.tests.test_helper import HelperTestCase
from COT.helpers.mkisofs import GenISOImage

logger = logging.getLogger(__name__)

# pylint: disable=missing-type-doc,missing-param-doc,protected-access

class TestGenISOImage(HelperTestCase):
    """Test cases for GenISOImage helper class."""

    def setUp(self):
        """Test case setup function called automatically prior to each test."""
        self.helper = GenISOImage()
        super(TestGenISOImage, self).setUp()

    @mock.patch('COT.helpers.helper.check_output',
                return_value="genisoimage 1.1.11 (Linux)")
    def test_get_version(self, _):
        """Test .version getter logic for genisoimage."""
        self.helper._installed = True
        self.assertEqual(StrictVersion("1.1.11"), self.helper.version)

    @mock.patch('COT.helpers.helper.check_output')
    @mock.patch('subprocess.check_call')
    def test_install_already_present(self, mock_check_call, mock_check_output):
        """Don't re-install if already installed."""
        self.helper._installed = True
        self.helper.install()
        mock_check_output.assert_not_called()
        mock_check_call.assert_not_called()

    def test_install_helper_apt_get(self):
        """Test installation via 'apt-get' of genisoimage."""
        self.apt_install_test('genisoimage', 'genisoimage')


text:
  <?php if ($vendor->base_amount > 0) : ?>

    <?php echo t('Base shipping rate is @amount', array(
      '@amount' => commerce_currency_format($vendor->base_amount, commerce_default_currency())
      ), array('context' => 'Multivendor shipping')) ?>

  <?php endif; ?>

  <?php if ($vendor->package_amount > 0) : ?>

    <?php echo t('Each package with @size items costs @amount',
      array(
      	'@size' => $vendor->package_size,
        '@amount' => commerce_currency_format($vendor->package_amount, commerce_default_currency()),
      ), array('context' => 'Multivendor shipping')); ?>

  <?php endif; ?>

  <?php if (!empty($vendor->description)) : ?>

    <?php echo t($vendor->description, array(), array('context' => 'Multivendor shipping')); ?>

  <?php endif; ?>


text:
<?php

namespace Nikapps\OrtcPhp\Handlers;

use GuzzleHttp\Message\FutureResponse;
use Nikapps\OrtcPhp\Exceptions\InvalidBalancerUrlException;
use Nikapps\OrtcPhp\Models\Responses\BalancerUrlResponse;

class BalancerUrlResponseHandler extends OrtcResponseHandler
{
    /**
     * handle response from guzzle.
     *
     * @param FutureResponse $response
     *
     * @return BalancerUrlResponse
     */
    public function handle($response)
    {
        $body = trim((string) $response);

        $url = $this->parseUrl($body);
        $this->validate($url);

        $balancerUrlResponse = new BalancerUrlResponse();
        $balancerUrlResponse->setUrl($url);

        return $balancerUrlResponse;
    }

    /**
     * validating response.
     *
     * @param string $url
     *
     * @throws InvalidBalancerUrlException
     */
    public function validate($url)
    {
        if (preg_match('/https?:\/\/undefined(:undefined)?/', $url)) {
            $invalidBalancerUrlException = new InvalidBalancerUrlException();
            $invalidBalancerUrlException->setUrl($url);

            throw $invalidBalancerUrlException;
        }

        if (!filter_var($url, FILTER_VALIDATE_URL)) {
            $invalidBalancerUrlException = new InvalidBalancerUrlException();
            $invalidBalancerUrlException->setUrl($url);

            throw $invalidBalancerUrlException;
        }
    }

    /**
     * parse body to find url.
     *
     * @param string $body
     *
     * @throws InvalidBalancerUrlException
     *
     * @return string
     */
    public function parseUrl($body)
    {
        if (!preg_match('/https?:\/\/[^\"]+/', $body, $matches)) {
            $invalidBalancerUrlException = new InvalidBalancerUrlException();
            $invalidBalancerUrlException->setUrl($body);

            throw $invalidBalancerUrlException;
        }

        return trim($matches[0]);
    }
}


text:
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
{{ define "flags" }}

Command Line Flags

            Flag
            Value

        {{range $index, $element := . }}

		        {{ $element.Flag }}

		          	{{ if eq $element.Flag "rootId"}}

						{{ $element.FlagVal }}
					{{ else }}
						{{ if eq $element.Flag "policySpreadsheetId"}}

							{{ $element.FlagVal }}
						{{ else }}
							{{ $element.FlagVal }}
						{{ end }}
					{{ end }}

        {{ end }}

{{ end }}


text:
package org.motechproject.commcare.tasks.builder;

import org.apache.commons.lang3.StringUtils;
import org.motechproject.commcare.config.Config;
import org.motechproject.commcare.domain.CommcareApplicationJson;
import org.motechproject.commcare.domain.CommcareModuleJson;
import org.motechproject.commcare.domain.FormSchemaJson;
import org.motechproject.commcare.domain.FormSchemaQuestionJson;
import org.motechproject.commcare.domain.FormSchemaQuestionOptionJson;
import org.motechproject.commcare.events.constants.DisplayNames;
import org.motechproject.commcare.events.constants.EventSubjects;
import org.motechproject.commcare.service.CommcareConfigService;
import org.motechproject.commcare.service.CommcareSchemaService;
import org.motechproject.tasks.contract.ActionEventRequest;
import org.motechproject.tasks.contract.ActionParameterRequest;
import org.motechproject.tasks.contract.builder.ActionEventRequestBuilder;
import org.motechproject.tasks.contract.builder.ActionParameterRequestBuilder;
import org.motechproject.tasks.domain.mds.ParameterType;

import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 * Class responsible for building the Task module actions, related to sending the
 * forms via submission API. The built list of {@link ActionEventRequest}s instances can
 * be passed to the Task module to register channel actions.
 */
public class FormActionBuilder implements ActionBuilder {

    private static final int MAX_LABEL_LENGTH = 255;

    private CommcareSchemaService schemaService;
    private CommcareConfigService configService;

    public FormActionBuilder(CommcareSchemaService schemaService, CommcareConfigService configService) {
        this.schemaService = schemaService;
        this.configService = configService;
    }

    @Override
    public List<ActionEventRequest> buildActions() {
        List<ActionEventRequest> actions = new ArrayList<>();

        for (Config config : configService.getConfigs().getConfigs()) {
            List<ActionEventRequest> builtActions = buildActionsForConfig(config);
            actions.addAll(builtActions);
        }

        return actions;
    }

    private List<ActionEventRequest> buildActionsForConfig(Config config) {
        List<ActionEventRequest> actions = new ArrayList<>();

        for (CommcareApplicationJson application : schemaService.retrieveApplications(config.getName())) {
            for (CommcareModuleJson module : application.getModules()) {
                for (FormSchemaJson form : module.getFormSchemas()) {
                    SortedSet<ActionParameterRequest> parameters = buildActionParameters(form);

                    String displayName = DisplayNameHelper.buildDisplayName(DisplayNames.SUBMIT_FORM, form.getFormName(),
                            application.getApplicationName(), config.getName());
                    ActionEventRequestBuilder actionBuilder = new ActionEventRequestBuilder()
                            .setDisplayName(displayName)
                            .setSubject(EventSubjects.SUBMIT_FORM + "." + form.getXmlns() + "." + config.getName())
                            .setActionParameters(parameters);
                    actions.add(actionBuilder.createActionEventRequest());
                }
            }
        }

        return actions;
    }

    private SortedSet<ActionParameterRequest> buildActionParameters(FormSchemaJson form) {
        SortedSet<ActionParameterRequest> parameters = new TreeSet<>();
        int order = 0;

        for (FormSchemaQuestionJson question : form.getQuestions()) {
            ActionParameterRequestBuilder builder = new ActionParameterRequestBuilder();

            String displayName = StringUtils.isBlank(question.getQuestionLabel()) ? question.getQuestionValue() : question.getQuestionLabel();

            if (displayName.length() > MAX_LABEL_LENGTH) {
                displayName = displayName.substring(0, MAX_LABEL_LENGTH);
            }

            builder.setDisplayName(displayName)
                    .setKey(question.getQuestionValue())
                    .setOrder(order++);

            if (question.getOptions() != null && !question.getOptions().isEmpty()) {
                builder.setType(ParameterType.SELECT.getValue());
                builder.setOptions(convertCommcareoptionsToTaskActionOptions(question.getOptions()));
            } else {
                builder.setType(ParameterType.UNICODE.getValue());
            }

            parameters.add(builder.createActionParameterRequest());
        }

        return parameters;
    }

    private SortedSet<String> convertCommcareoptionsToTaskActionOptions(List<FormSchemaQuestionOptionJson> options) {
        SortedSet availableOptions = new TreeSet<>();

        for (FormSchemaQuestionOptionJson option : options) {
            availableOptions.add(option.getValue());
        }
        return availableOptions;
    }
}


text:
Builds
======

This section contains information on the various multicopter's I have built.

.. toctree::
   :maxdepth: 1

   djif450/index.rst
   zmr250/index.rst
   alien5/index.rst


text:
package edu.usu.sdl.openstorefront.usecase;

import edu.usu.sdl.openstorefront.validation.LinkSanitizer;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;

/**
 *
 * @author dshurtleff
 */
public class SantizeUseCase
{

	@Test
	public void testSantize()
	{
		LinkSanitizer linkSanitizer = new LinkSanitizer();

		String out = (String) linkSanitizer.santize("Media.action?GeneralMedia&name=Test");
		System.out.println(out);

		out = (String) linkSanitizer.santize("ws://www.google.com/q=test&check=true");
		System.out.println(out);

		out = (String) linkSanitizer.santize("test");
		System.out.println(out);

		out = (String) linkSanitizer.santize("test2");
		System.out.println(out);

		out = (String) linkSanitizer.santize("test2");
		System.out.println(out);

	}

	@Test
	public void testStringPadRemoval()
	{
		System.out.println(StringUtils.stripStart("0001", "0"));
		System.out.println(StringUtils.stripStart("0301", "0"));
		System.out.println(StringUtils.stripStart("5", "0"));
		System.out.println(StringUtils.stripStart("0000", "0"));
		System.out.println(StringUtils.stripStart("1000", "0"));
		System.out.println(StringUtils.stripStart("0020", "0"));
		System.out.println(StringUtils.stripStart("bob", "0"));
	}

}


text:
package org.jetbrains.jsonProtocol;

public final class StringIntPair {
  public final String name;
  public final int value;

  public StringIntPair(String name, int value) {
    this.name = name;
    this.value = value;
  }

  public StringIntPair(int value, String name) {
    this(name, value);
  }
}


text:
package com.bronytunes.app;

import android.app.Application;
import android.support.annotation.NonNull;

import com.bronytunes.app.data.Injector;
import com.bronytunes.app.data.LumberYard;
import com.bronytunes.app.ui.ActivityHierarchyServer;
import com.facebook.stetho.Stetho;
import com.squareup.leakcanary.LeakCanary;

import net.danlew.android.joda.JodaTimeAndroid;

import javax.inject.Inject;

import dagger.ObjectGraph;
import timber.log.Timber;

/**
 * An app delegate which will update the track DB when the
 * application launches and hosts the object graph for
 * dependency injection.
 */
public final class BronyTunesApp extends Application {

    @Inject
    ActivityHierarchyServer activityHierarchyServer;
    @Inject
    LumberYard              lumberYard;

    private ObjectGraph objectGraph;

    @Override
    public void onCreate() {
        super.onCreate();
        JodaTimeAndroid.init(this);
        LeakCanary.install(this);

        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
            Stetho.initialize(Stetho.newInitializerBuilder(this)
                    .enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
                    .enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this))
                    .build());
        } else {
            // Crashalytics
        }

        objectGraph = ObjectGraph.create(Modules.list(this));
        objectGraph.inject(this);

        lumberYard.cleanUp();
        Timber.plant(lumberYard.tree());

        registerActivityLifecycleCallbacks(activityHierarchyServer);
    }

    @Override
    public Object getSystemService(@NonNull String name) {
        if (Injector.matchesService(name)) {
            return objectGraph;
        }
        return super.getSystemService(name);
    }
}


text:
package com.amazonaws.services.voiceid.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum FraudDetectionDecision {

    HIGH_RISK("HIGH_RISK"),
    LOW_RISK("LOW_RISK"),
    NOT_ENOUGH_SPEECH("NOT_ENOUGH_SPEECH");

    private String value;

    private FraudDetectionDecision(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return FraudDetectionDecision corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static FraudDetectionDecision fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (FraudDetectionDecision enumEntry : FraudDetectionDecision.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
package org.makersoft.shards.unit;

import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.datasource.unpooled.UnpooledDataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;

/**
 * 单元测试基类.
 *
 * @version 2012-8-7
 * @author Feng Kuok
 */
public abstract class BaseTest {

	public static final String APPLICATION_PROPERTIES = "application.properties";
	public static final String DS1_PROPERTIES = "databases/ds1.properties";
	public static final String DS2_PROPERTIES = "databases/ds2.properties";

	public static UnpooledDataSource createUnpooledDataSource(String resource)
			throws IOException {
		Properties props = Resources.getResourceAsProperties(resource);
		UnpooledDataSource ds = new UnpooledDataSource();
		ds.setDriver(props.getProperty("driver"));
		ds.setUrl(props.getProperty("url"));
		ds.setUsername(props.getProperty("username"));
		ds.setPassword(props.getProperty("password"));
		return ds;
	}

	public static PooledDataSource createPooledDataSource(String resource)
			throws IOException {
		Properties props = Resources.getResourceAsProperties(resource);
		PooledDataSource ds = new PooledDataSource();
		ds.setDriver(props.getProperty("driver"));
		ds.setUrl(props.getProperty("url"));
		ds.setUsername(props.getProperty("username"));
		ds.setPassword(props.getProperty("password"));
		return ds;
	}

	public static void runScript(DataSource ds, String resource)
			throws IOException, SQLException {
		Connection connection = ds.getConnection();
		try {
			ScriptRunner runner = new ScriptRunner(connection);
			runner.setAutoCommit(true);
			runner.setStopOnError(false);
			runner.setLogWriter(null);
			runner.setErrorLogWriter(null);
			runScript(runner, resource);
		} finally {
			connection.close();
		}
	}

	public static void runScript(ScriptRunner runner, String resource)
			throws IOException, SQLException {
		Reader reader = Resources.getResourceAsReader(resource);
		try {
			runner.runScript(reader);
		} finally {
			reader.close();
		}
	}

	public static DataSource createDataSource_1() throws IOException,
			SQLException {
		DataSource ds = createUnpooledDataSource(DS1_PROPERTIES);
		return ds;
	}

	public static DataSource createDataSource_2() throws IOException,
		SQLException {
		DataSource ds = createUnpooledDataSource(DS2_PROPERTIES);
		return ds;
	}
}


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from caffe2.python import schema
from caffe2.python.layers.arc_cosine_feature_map import ArcCosineFeatureMap
import numpy as np

class SemiRandomFeatures(ArcCosineFeatureMap):
    """
    Implementation of the semi-random kernel feature map.

    Applies H(x_rand) * x_rand^s * x_learned, where
        H is the Heaviside step function,
        x_rand is the input after applying FC with randomized parameters,
        and x_learned is the input after applying FC with learnable parameters.

    If using multilayer model with semi-random layers, then input and output records
    should have a 'full' and 'random' Scalar. The random Scalar will be passed as
    input to process the random features.

    For more information, see the original paper:
        https://arxiv.org/pdf/1702.08882.pdf

    Inputs :
        output_dims -- dimensions of the output vector
        s -- if s == 0, will obtain linear semi-random features;
             else if s == 1, will obtain squared semi-random features;
             else s >= 2, will obtain higher order semi-random features
        scale_random -- amount to scale the standard deviation
                        (for random parameter initialization when weight_init or
                        bias_init hasn't been specified)
        scale_learned -- amount to scale the standard deviation
                        (for learned parameter initialization when weight_init or
                        bias_init hasn't been specified)

        weight_init_random -- initialization distribution for random weight parameter
                              (if None, will use Gaussian distribution)
        bias_init_random -- initialization distribution for random bias pararmeter
                            (if None, will use Uniform distribution)
        weight_init_learned -- initialization distribution for learned weight parameter
                               (if None, will use Gaussian distribution)
        bias_init_learned -- initialization distribution for learned bias pararmeter
                             (if None, will use Uniform distribution)
        weight_optim -- optimizer for weight params for learned features
        bias_optim -- optimizer for bias param for learned features

        set_weight_as_global_constant -- if True, initialized random parameters
                                         will be constant across all distributed
                                         instances of the layer
    """
    def __init__(
            self,
            model,
            input_record,
            output_dims,
            s=1,
            scale_random=1.0,
            scale_learned=1.0,
            weight_init_random=None,
            bias_init_random=None,
            weight_init_learned=None,
            bias_init_learned=None,
            weight_optim=None,
            bias_optim=None,
            set_weight_as_global_constant=False,
            name='semi_random_features',
            **kwargs):

        if isinstance(input_record, schema.Struct):
            schema.is_schema_subset(
                schema.Struct(
                    ('full', schema.Scalar()),
                    ('random', schema.Scalar()),
                ),
                input_record
            )
            self.input_record_full = input_record.full
            self.input_record_random = input_record.random

        elif isinstance(input_record, schema.Scalar):
            self.input_record_full = input_record
            self.input_record_random = input_record

        super(SemiRandomFeatures, self).__init__(
            model,
            self.input_record_full,
            output_dims,
            s=s,
            scale=scale_random,       # To initialize the random parameters
            weight_init=weight_init_random,
            bias_init=bias_init_random,
            weight_optim=None,
            bias_optim=None,
            set_weight_as_global_constant=set_weight_as_global_constant,
            initialize_output_schema=False,
            name=name,
            **kwargs)

        self.output_schema = schema.Struct(
            ('full', schema.Scalar(
                (np.float32, output_dims),
                model.net.NextScopedBlob(name + '_full_output')
            ),),
            ('random', schema.Scalar(
                (np.float32, output_dims),
                model.net.NextScopedBlob(name + '_random_output')
            ),),
        )

        # To initialize the learnable parameters
        assert (scale_learned > 0.0), \
            "Expected scale (learned) > 0, got %s" % scale_learned
        self.stddev = scale_learned * np.sqrt(1.0 / self.input_dims)

        # Learned Parameters
        (self.learned_w, self.learned_b) = self._initialize_params(
            'learned_w',
            'learned_b',
            w_init=weight_init_learned,
            b_init=bias_init_learned,
            w_optim=weight_optim,
            b_optim=bias_optim
        )

    def add_ops(self, net):
        # Learned features: wx + b
        learned_features = net.FC(self.input_record_full.field_blobs() +
                                  [self.learned_w, self.learned_b],
                                  net.NextScopedBlob('learned_features'))
        # Random features: wx + b
        random_features = net.FC(self.input_record_random.field_blobs() +
                                 [self.random_w, self.random_b],
                                 net.NextScopedBlob('random_features'))
        processed_random_features = self._heaviside_with_power(
            net,
            random_features,
            self.output_schema.random.field_blobs(),
            self.s
        )
        net.Mul([processed_random_features, learned_features],
                self.output_schema.full.field_blobs())


text:
package org.pentaho.di.ui.spoon.trans;

import org.pentaho.ui.xul.containers.XulMenupopup;

public class StepMenuExtension {

  private TransGraph transGraph;
  private XulMenupopup menu;

  public StepMenuExtension( TransGraph transGraph, XulMenupopup menu ) {
    this.transGraph = transGraph;
    this.menu = menu;
  }

  public TransGraph getTransGraph() {
    return transGraph;
  }

  public void setTransGraph( TransGraph transGraph ) {
    this.transGraph = transGraph;
  }

  public XulMenupopup getMenu() {
    return menu;
  }

  public void setMenu( XulMenupopup menu ) {
    this.menu = menu;
  }
}


text:
EZLoadingActivity
==========

[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/EZLoadingActivity.svg)](https://img.shields.io/cocoapods/v/EZLoadingActivity.svg)
[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)

Lightweight Swift loading activity for iOS7+. Really simple to use, just add the class and write 1 line of code.

![demo](http://i.imgur.com/xLHKvSB.gif)

## Easy to use:
```swift
EZLoadingActivity.show("Loading...", disableUI: true)
```
'disableUI' stops user interactions until you hide loadingactivity.

## How to dismiss:
```swift
EZLoadingActivity.hide(success: true, animated: true)
```

## Failure:
```swift
EZLoadingActivity.hide(success: false, animated: true)
```
![demo](http://i.imgur.com/x2BAEmG.gif)

## Without Animation:
```swifts
EZLoadingActivity.hide(success: true, animated: false)
```
![demo](http://i.imgur.com/fXvCbIy.gif)

## Hide Directly:
```swift
EZLoadingActivity.hide()
```
![demo](http://i.imgur.com/2cySGp6.gif)

## Editing:
```swift
EZLoadingActivity.Settings.SuccessColor = UIColor.blueColor()
EZLoadingActivity.show("Loading...", disableUI: false)
```

|Settings Options|
| -------------|
|BackgroundColor|
|ActivityColor|
|TextColor|
|FontName|
|SuccessIcon|
|FailIcon|
|SuccessText|
|FailText|
|SuccessColor|
|FailColor|
|ActivityWidth|
|ActivityHeight|

## Example Use Case:

```swift
EZLoadingActivity.show("Uploading...", disableUI: false)

var postObject = PFObject(className: "className")
postObject.saveInBackgroundWithBlock { (succeeded: Bool, error: NSError!) -> Void in
    if error == nil {
       if succeeded == true {
          EZLoadingActivity.hide(success: true, animated: false)
          print("Upload Complete")
        } else {
          EZLoadingActivity.hide(success: false, animated: true)
          print("Upload Failed")
       }
    } else {
        EZLoadingActivity.hide(success: false, animated: true)
        print("Error")
    }
}
```

######Showing EZLoadingActivity for a certain time:

```swift
EZLoadingActivity.showWithDelay("Waiting...", disableUI: false, seconds: 2)
```

######Showing EZLoadingActivity from App Window(For example: for Split view controller):

```swift
EZLoadingActivity.Settings.LoadOverApplicationWindow = true
```

## No object tracking:
EZLoadingActivity is a singleton object so you don't need to keep track of its instance.

##Installation (~10 seconds)

1. Download and drop 'EZLoadingActivity.swift' in your project.
2. Congratulations!

## Install via Carthage

[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

You can install Carthage with [Homebrew](http://brew.sh/) using the following command:

```bash
$ brew update
$ brew install carthage
```

To integrate EZLoadingActivity into your Xcode project using Carthage, specify it in your `Cartfile`:

```ogdl
github "goktugyil/EZLoadingActivity"
```

Run `carthage update` to build the framework and drag the built `EZLoadingActivity.framework` into your Xcode project.

Then on the top of files where you are going to use this:

```swift
import EZLoadingActivity
```

## Install via CocoaPods

You can use [CocoaPods](http://cocoapods.org/) to install `EZLoadingActivity` by adding it to your `Podfile`:

```ruby
platform :ios, '8.0'
use_frameworks!

pod 'EZLoadingActivity' #Stable release for Swift 3.0

pod 'EZLoadingActivity', :git => 'https://github.com/goktugyil/EZLoadingActivity.git' #Latest release for Swift 3.0
pod 'EZLoadingActivity', '~> 0.8' #For Swift 2.2
```

Then on the top of files where you are going to use this:

```swift
import EZLoadingActivity
```

##Requirements

- Xcode 6 or later (Tested on 7)
- iOS 7 or later (Tested on 9)

##Possible features

- More customization
- Pod support
- OSX compatibility and add here https://github.com/AndrewSB/awesome-osx

##License
EZLoadingActivity is available under the MIT license. See the [LICENSE file](https://github.com/goktugyil/EZLoadingActivity/blob/master/LICENSE).

##Keywords
swift, hud, loading, activity, progresshud, progress, track, spinner,


text:
<?php
/**
* Orchestra.io Bootstrap for Lithium
*
* add `require __DIR__ . '/bootstrap/orchestra.php';` immediately after
* `require __DIR__ . '/bootstrap/libraries.php';` in bootstrap.php
*/
use lithium\core\Libraries;

Libraries::add('app', array('default'=> true, 'resources' => call_user_func(function() {
        if (!is_dir($resources = str_replace("//", "/", sys_get_temp_dir() . '/resources'))) {
                foreach (array($resources, "{$resources}/tmp/logs", "{$resources}/tmp/cache/templates") as $d) {
                        mkdir($d, 0777, true);
                }
        }
        return $resources;
})));


text:
import os

from matplotlib import colors
from tardis import atomic, plasma_array, util
from matplotlib import pyplot as plt

import numpy as np
import pandas as pd

#Making 2 Figures for ionization balance and level populations

plt.figure(1).clf()
ax1 = plt.figure(1).add_subplot(111)

plt.figure(2).clf()
ax2 = plt.figure(2).add_subplot(111)

# expanding the tilde to the users directory
atom_fname = os.path.expanduser('~/.tardis/si_kurucz.h5')

# reading in the HDF5 File
atom_data = atomic.AtomData.from_hdf5(atom_fname)

#The atom_data needs to be prepared to create indices. The Class needs to know which atomic numbers are needed for the
#calculation and what line interaction is needed (for "downbranch" and "macroatom" the code creates special tables)
atom_data.prepare_atom_data([14], 'scatter')

#Initializing the NebularPlasma class using the from_abundance class method.
#This classmethod is normally only needed to test individual plasma classes
#Usually the plasma class just gets the number densities from the model class
nebular_plasma = plasma.NebularPlasma.from_abundance(10000, 0.5, {'Si': 1}, 1e-13, atom_data, 10.)

#Initializing a dataframe to store the ion populations  and level populations for the different temperatures
ion_number_densities = pd.DataFrame(index=nebular_plasma.ion_populations.index)
level_populations = pd.DataFrame(index=nebular_plasma.level_populations.ix[14, 1].index)
t_rads = np.linspace(2000, 20000, 100)

#Calculating the different ion populations and level populuatios for the given temperatures
for t_rad in t_rads:
    nebular_plasma.update_radiationfield(t_rad, w=1.0)
    #getting total si number density
    si_number_density = nebular_plasma.number_density.get_value(14)
    #Normalizing the ion populations
    ion_density = nebular_plasma.ion_populations / si_number_density
    ion_number_densities[t_rad] = ion_density

    #normalizing the level_populations for Si II
    current_level_population = nebular_plasma.level_populations.ix[14, 1] / nebular_plasma.ion_populations.ix[14, 1]
    #normalizing with statistical weight
    current_level_population /= atom_data.levels.ix[14, 1].g

    level_populations[t_rad] = current_level_population

ion_colors = ['b', 'g', 'r', 'k']

for ion_number in [0, 1, 2, 3]:
    current_ion_density = ion_number_densities.ix[14, ion_number]
    ax1.plot(current_ion_density.index, current_ion_density.values, '%s-' % ion_colors[ion_number],
             label='Si %s W=1.0' % util.int_to_roman(ion_number + 1).upper())

#only plotting every 5th radiation temperature
t_rad_normalizer = colors.Normalize(vmin=2000, vmax=20000)
t_rad_color_map = plt.cm.ScalarMappable(norm=t_rad_normalizer, cmap=plt.cm.jet)

for t_rad in t_rads[::5]:
    ax2.plot(level_populations[t_rad].index, level_populations[t_rad].values, color=t_rad_color_map.to_rgba(t_rad))
    ax2.semilogy()

#Calculating the different ion populations for the given temperatures with W=0.5
ion_number_densities = pd.DataFrame(index=nebular_plasma.ion_populations.index)
for t_rad in t_rads:
    nebular_plasma.update_radiationfield(t_rad, w=0.5)
    #getting total si number density
    si_number_density = nebular_plasma.number_density.get_value(14)
    #Normalizing the ion populations
    ion_density = nebular_plasma.ion_populations / si_number_density
    ion_number_densities[t_rad] = ion_density

    #normalizing the level_populations for Si II
    current_level_population = nebular_plasma.level_populations.ix[14, 1] / nebular_plasma.ion_populations.ix[14, 1]
    #normalizing with statistical weight
    current_level_population /= atom_data.levels.ix[14, 1].g

    level_populations[t_rad] = current_level_population

#Plotting the ion fractions

for ion_number in [0, 1, 2, 3]:
    print "w=0.5"
    current_ion_density = ion_number_densities.ix[14, ion_number]
    ax1.plot(current_ion_density.index, current_ion_density.values, '%s--' % ion_colors[ion_number],
             label='Si %s W=0.5' % util.int_to_roman(ion_number + 1).upper())

for t_rad in t_rads[::5]:
    ax2.plot(level_populations[t_rad].index, level_populations[t_rad].values, color=t_rad_color_map.to_rgba(t_rad),
             linestyle='--')
    ax2.semilogy()

t_rad_color_map.set_array(t_rads)
cb = plt.figure(2).colorbar(t_rad_color_map)

ax1.set_xlabel('T [K]')
ax1.set_ylabel('Number Density Fraction')
ax1.legend()

ax2.set_xlabel('Level Number for Si II')
ax2.set_ylabel('Number Density Fraction')
cb.set_label('T [K]')

plt.show()


text:
package com.mendeley.api.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Toast;

import com.mendeley.api.impl.DefaultMendeleySdk;
import com.mendeley.api.R;
import com.mendeley.api.auth.AuthenticationManager;
import com.mendeley.api.util.Utils;

/**
 * Display the splash screen, with buttons to sign in or create an account.
 *
 * The "create account" button starts a new web browser activity pointed at the
 * Mendeley home page.
 *
 * The "sign in" button starts DialogActivity to obtain an authorization code, which is
 * passed to AuthenticationManager.
 */
public class SignInActivity  extends Activity implements OnClickListener {
	private final static int SIGNIN_RESULT = 0;
	private final static String CREATE_ACCOUNT_URL = "http://www.mendeley.com/";

    private AuthenticationManager authenticationManager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        authenticationManager = DefaultMendeleySdk.getInstance().getAuthenticationManager();

        setContentView(R.layout.splash_layout);

        findViewById(R.id.signinButton).setOnClickListener(this);
        findViewById(R.id.signupButton).setOnClickListener(this);
    }

    /**
     * Handling click events on the custom buttons.
     * Will call DialogActivity or open the create account url in a web browser.
     */
	@Override
	public void onClick(View v) {
		if (!Utils.isOnline(this)) {
			Toast.makeText(this, R.string.no_connection, Toast.LENGTH_SHORT).show();
			return;
		}

		int id = v.getId();
		if (id == R.id.signinButton) {
			Intent intent = new Intent(this, DialogActivity.class);
			startActivityForResult(intent, SIGNIN_RESULT);
		} else if (id == R.id.signupButton) {
			openUrlInBrowser(CREATE_ACCOUNT_URL);
		}
	}

    /**
     * Opening a system web browser to load the given url
     * @param url the url to load
     */
    private void openUrlInBrowser(String url) {
    	Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    	startActivity(intent);
    }

    /**
     * Handling on activity result.
     * Will be called after the user logged in in the DialogActivity.
     * If an authorisation code is received will call authenticated method of the AuthenticationManager
     * otherwise will call failedToAuthenticate.
     */
    @Override
    protected void onActivityResult (int requestCode, int resultCode, Intent data) {
    	if (resultCode == Activity.RESULT_OK) {
    		switch(requestCode) {
	    		case SIGNIN_RESULT:
	    			String code = null;
	    			Bundle bundle = data.getExtras();
	    			if (bundle != null && bundle.containsKey("authorization_code")) {
	    				code = bundle.getString("authorization_code");
	    			}
	    			if (code != null) {
		    			authenticationManager.authenticated(true);
	    			} else {
	    				authenticationManager.failedToAuthenticate();
	    			}
	    			finish();
	    			break;
    		}
    	}
    }

	@Override
	public void onBackPressed() {
		finish();
	}

	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
		super.onSaveInstanceState(savedInstanceState);
	}

	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}
}


text:
package slf

// ParamsFilter describes function, used to filter params list
type ParamsFilter func([]Param) []Param

// denyAllP does not allow any param
func denyAllP([]Param) []Param { return []Param{} }

// allowAllP allows all packets
func allowAllP(p []Param) []Param { return p }

// wlParams contains whitelist filtering
type wlParams struct {
	allowed map[string]bool
}

func (w wlParams) filter(p []Param) []Param {
	if len(p) == 0 {
		return []Param{}
	}

	n := []Param{}
	for _, param := range p {
		if _, ok := w.allowed[param.GetKey()]; ok {
			n = append(n, param)
		}
	}

	return n
}

// wlParams contains blacklist filtering
type blParams struct {
	allowed map[string]bool
}

func (w blParams) filter(p []Param) []Param {
	if len(p) == 0 {
		return []Param{}
	}

	n := []Param{}
	for _, param := range p {
		if _, ok := w.allowed[param.GetKey()]; !ok {
			n = append(n, param)
		}
	}

	return n
}

// NewWhiteListParamsFilter return params filter, that allows only params
// with names, passed to this function
func NewWhiteListParamsFilter(allowedNames []string) ParamsFilter {
	if len(allowedNames) == 0 {
		return denyAllP
	}

	f := wlParams{allowed: make(map[string]bool, len(allowedNames))}
	for _, name := range allowedNames {
		f.allowed[name] = true
	}

	return f.filter
}

// NewBlackListParamsFilter returns params filter, that clears params
// with name, passed to this function
func NewBlackListParamsFilter(allowedNames []string) ParamsFilter {
	if len(allowedNames) == 0 {
		return allowAllP
	}

	f := blParams{allowed: make(map[string]bool, len(allowedNames))}
	for _, name := range allowedNames {
		f.allowed[name] = true
	}

	return f.filter
}


text:
package net.cserna.bence.bulletzone.core;

/**
* @author Bence Cserna (bence@cserna.net)
*/
public interface BulletZoneServerListener {
	/**
	 * Called in case of field update.
	 *
	 * @param field
	 *            current field state.
	 * @param timestamp
	 *            server's system time at the update.
	 */
	public void onFieldUpdate(int[][] field, long timestamp);

	/**
	 * For future use.
	 *
	 * @param code
	 *            - Event code.
	 * @param object
	 */
	public void onEvent(int code, Object object);
}


text:
this.SS_AjaxFile = (function () {
  function SS_AjaxFile(el, options) {
    this.$el = $(el || "#ajax-file-box");
    this.options = options || {};

    this.render();
  }

  SS_AjaxFile.additionalFileResizings = [];
  SS_AjaxFile.firesEvents = false;

  SS_AjaxFile.errors = {
    entityTooLarge: "request entity is too large"
  }

  SS_AjaxFile.addFileResizing = function() {
    for (var i = 0; i < arguments.length; i++) {
      var argument = arguments[i];
      if (argument.default) {
        for (var j = 0; j < SS_AjaxFile.additionalFileResizings.length; j++) {
          if (SS_AjaxFile.additionalFileResizings[j].default) {
            SS_AjaxFile.additionalFileResizings[j].default = false;
          }
        }
      }

      SS_AjaxFile.additionalFileResizings.push(argument);
    }
  }

  SS_AjaxFile.defaultFileResizing = function () {
    for (var i = 0; i < SS_AjaxFile.additionalFileResizings.length; i++) {
      if (SS_AjaxFile.additionalFileResizings[i].default) {
        return SS_AjaxFile.additionalFileResizings[i].value;
      }
    }

    return null;
  };

  SS_AjaxFile.defaultFileSelectHandler = function() {
    var promisses = [];
    var fileViews = [];

    for (var i = 0; i < arguments.length; i++) {
      var $argument = $(arguments[i]);
      var url = $argument.attr('href');
      if (!url) {
        continue;
      }

      var filename = $argument.data("humanized-name");

      promisses.push($.ajax({
        url: url,
        success: function(html) {
          fileViews.push({ name: filename, html: html });
        },
        error: function(xhr, status, data) {
          if (xhr.responseJSON && Array.isArray(xhr.responseJSON)) {
            alert(["== Error =="].concat(xhr.responseJSON).join("\n"));
          } else {
            alert(["== Error =="].concat(xhr.statusText).join("\n"));
          }
        }
      }));
    }

    $.when.apply($, promisses).done(function () {
      fileViews.sort(function(a,b) {
        if (a.name < b.name) return 1;
        if (a.name > b.name) return -1;
        return 0;
      });

      for (var i = 0; i < fileViews.length; i++) {
        $("#selected-files").prepend(fileViews[i].html);
      }

      $.colorbox.close();
    });
  };

  SS_AjaxFile.prototype.render = function() {
    var self = this;

    self.$el.on("submit", "form.user-file", function (ev) {
      var submitted = "attach";
      if (ev.originalEvent && ev.originalEvent.submitter) {
        submitted = ev.originalEvent.submitter.dataset.submitted;
      }
      var $form = $(this);

      var params = {
        url: $form.attr("action") + ".json",
        dataType: "json",
        success: function(data, textStatus, xhr) {
          self.submitSuccess(submitted, data);
        },
        error: function (xhr, status, error) {
          self.submitError(xhr);
        },
        complete: function (xhr, status) {
          $.rails.enableFormElements($form);
        }
      };

      $form.ajaxSubmit(params);
      ev.preventDefault();
    });

    self.$el.on("click", ".user-files .select", function(ev) {
      self.selectFiles(this);

      ev.preventDefault();
      return false;
    });

    self.$el.on("click", ".user-files .delete", function(ev) {
      self.deleteFile(ev.target);

      ev.preventDefault();
      return false;
    });

    for (var i = 0; i < SS_AjaxFile.additionalFileResizings.length; i++) {
      var fileResizing = SS_AjaxFile.additionalFileResizings[i];
      var option = $('<option />').val(fileResizing.value).text(fileResizing.label);
      if (fileResizing.default) {
        option.prop('selected', true)
      }

      self.$el.find('form.user-file .image-size').append(option);
    }
  };

  SS_AjaxFile.prototype.submitSuccess = function(submitted, data) {
    var self = this;
    var loadUrl = (submitted === "attach") ? self.options.selectedFilesPath : self.options.indexPath;
    var indexOptions = self.options.pathOptions || {};

    if (submitted === "attach" && Array.isArray(data)) {
      var select_ids = $.map(data, function(v) { return v._id });
      indexOptions = Object.assign(indexOptions, { select_ids: select_ids });
    }

    if (Object.keys(indexOptions).length) {
      loadUrl += "?" + $.param(indexOptions);
    }

    $("<div />").load(loadUrl, function () {
      var $userFiles = $(this).find(".user-files");
      if ($userFiles[0]) {
        // TODO: 差分だけをアニメーションつきで insert するとかっこよくなる
        self.$el.find(".user-files").html($userFiles.html());
        SS.renderInBox(self.$el);
      }

      self.$el.find("form.user-file [type='file']").val(null).trigger("change");

      var defaultImageSize = null;
      for (var i = 0; i < SS_AjaxFile.additionalFileResizings.length; i++) {
        var fileResizing = SS_AjaxFile.additionalFileResizings[i];
        if (fileResizing.default) {
          defaultImageSize = fileResizing.value;
          break;
        }
      }
      self.$el.find("form.user-file .image-size").val(defaultImageSize).trigger("change");

      if (submitted === "attach") {
        self.attachFiles(data);
      }
    });
  };

  SS_AjaxFile.prototype.attachFiles = function(data) {
    var self = this;

    if (!Array.isArray(data) || data.length == 0) {
      return;
    }

    var elements = [];
    $.each(data, function(index, file) {
      var item = self.$el.find(".user-files [data-id='" + file._id + "'] .select");
      elements.push(item);
    });

    self.selectFiles.apply(self, elements);
  };

  SS_AjaxFile.prototype.submitError = function(xhr) {
    if (xhr.status === 413) {
      alert(["== Error =="].concat(SS_AjaxFile.errors.entityTooLarge).join("\n"));
    } else {
      try {
        alert(["== Error =="].concat(xhr.responseJSON).join("\n"));
      } catch(_error) {
        alert(["== Error =="].concat(xhr.statusText).join("\n"));
      }
    }
  };

  SS_AjaxFile.prototype.selectFiles = function() {
    if (SS_SearchUI.anchorAjaxBox) {
      if (SS_AjaxFile.firesEvents) {
        var event = $.Event("ss:ajaxFileSelected");
        SS_SearchUI.anchorAjaxBox.trigger(event, [ arguments ]);
        if (event.isDefaultPrevented()) {
          return;
        }
      }

      var handler = SS_SearchUI.anchorAjaxBox.data('on-select');
      if (handler) {
        $.each(arguments, function() {
          handler($(this));
        });

        return true;
      }
    }

    SS_AjaxFile.defaultFileSelectHandler.apply(SS_AjaxFile, arguments);
  };

  SS_AjaxFile.prototype.deleteFile = function(el) {
    if (!confirm(i18next.t('ss.confirm.delete'))) {
      return false;
    }

    var $el = $(el);
    $.ajax({
      type: "POST",
      data: "_method=delete",
      url: $el.attr("href") + ".json",
      dataType: "json",
      beforeSend: function () {
        $el.html(SS.loading);
      },
      success: function () {
        var $target;
        if ($el.data("remove")) {
          $target = $($el.data("remove"));
        } else {
          $target = $el.closest(".file-view")
        }

        $target.slideUp("fast", function() {
          $target.remove();
          if (SS_AjaxFile.firesEvents && SS_SearchUI.anchorAjaxBox) {
            SS_SearchUI.anchorAjaxBox.trigger("ss:ajaxRemoved");
          }
        });
      },
      error: function (data, status) {
        alert(["== Error =="].concat(data.responseJSON).join("\n"));
      }
    });
  };

  return SS_AjaxFile;

})();


text:
import $ from 'jquery';
import Marionette from 'backbone.marionette';
import {cssModulesUtils} from 'pageflow/ui';
import {PreviewMessageController} from '../controllers/PreviewMessageController'
import {BlankEntryView} from './BlankEntryView';

import styles from './EntryPreviewView.module.css'

export const EntryPreviewView = Marionette.ItemView.extend({
  template: () => `
     <iframe class="${styles.iframe}" />
  `,

  className: styles.root,

  ui: cssModulesUtils.ui(styles, 'iframe'),

  modelEvents: {
    'change:emulation_mode': 'updateEmulationMode'
  },

  onRender() {
    this.appendSubview(new BlankEntryView({model: this.model}));
  },

  onShow() {
    this.messageController = new PreviewMessageController({
      entry: this.model,
      editor: this.options.editor,
      iframeWindow: this.ui.iframe[0].contentWindow
    });

    inject(this.ui.iframe[0],
           unescape($('[data-template="iframe_seed"]').html()));
  },

  onClose() {
    this.messageController.dispose();
  },

  updateEmulationMode: function() {
    this.messageController.preserveScrollPoint(() => {
      if (this.model.previous('emulation_mode')) {
        this.$el.removeClass(styles[this.emulationModeClassName(this.model.previous('emulation_mode'))]);
      }

      if (this.model.get('emulation_mode')) {
        this.$el.addClass(styles[this.emulationModeClassName(this.model.get('emulation_mode'))]);
      }
    });
  },

  emulationModeClassName: function(mode) {
    return `${mode}EmulationMode`;
  }
});

function inject(iframe, html) {
  var doc = iframe.document ||
            iframe.contentDocument ||
            iframe.contentWindow.document;

  doc.open();
  doc.writeln(html);
  doc.close();
}

function unescape(text) {
  return text.replace(/<\\\//g, '</');
}


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateMeasurementsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('measurements', function (Blueprint $table) {
            $table->increments('id');

            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')
                ->references('id')->on('users')
                ->onDelete('cascade');

            $table->decimal('weight', 10, 2)->nullable();
            $table->decimal('body_fat', 10, 2)->nullable();
            $table->decimal('neck', 10, 2)->nullable();
            $table->decimal('shoulders', 10, 2)->nullable();
            $table->decimal('arms', 10, 2)->nullable();
            $table->decimal('chest', 10, 2)->nullable();
            $table->decimal('waist', 10, 2)->nullable();
            $table->decimal('forearms', 10, 2)->nullable();
            $table->decimal('calves', 10, 2)->nullable();
            $table->decimal('thighs', 10, 2)->nullable();
            $table->decimal('hips', 10, 2)->nullable();
            $table->timestamp('date')->nullable();

            $table->timestamps();
        });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('measurements');
    }
}


text:
import typescript2 from 'rollup-plugin-typescript2';
import { terser } from 'rollup-plugin-terser';
import json from 'rollup-plugin-json';

export default [
  // browser-friendly UMD build
  {
    input: 'src/index.browser.ts',
    external: ['react'],
    output: {
      name: 'htmr',
      file: 'lib/htmr.browser.js',
      format: 'umd',
      globals: {
        react: 'React',
      },
    },
    plugins: [typescript2(), terser(), json()],
  },
  // commonJS
  {
    input: 'src/index.ts',
    external: ['htmlparser2', 'react', 'html-entities'],
    output: [{ file: 'lib/htmr.js', format: 'cjs' }],
    plugins: [typescript2(), json()],
  },
];


text:
@implementation BTZoomTransitionAnimator

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext
{
    return 0.3;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
    // Setup for animation transition
    BTHomeVC *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toVC   = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *containerView    = [transitionContext containerView];
    [containerView addSubview:fromVC.view];
    [containerView addSubview:toVC.view];

    UIView *alphaView = [[UIView alloc] initWithFrame:[transitionContext finalFrameForViewController:toVC]];
    alphaView.backgroundColor = [UIColor whiteColor];
    [containerView addSubview:alphaView];

    UIImageView *imageView = fromVC.cellImageView;
    [containerView addSubview:imageView];

    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        imageView.frame = CGRectMake(0, 0, 375, 200);
        imageView.transform = CGAffineTransformMakeScale(1.02, 1.02);
        alphaView.alpha = 0.9;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
            alphaView.alpha = 0;
            imageView.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            imageView.alpha = 0;
            [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
        }];
    }];
}

@end


text:
package com.yeamy.daily;

import static com.yeamy.daily.TimelineFragment.RESULT_ADD;
import static com.yeamy.daily.TimelineFragment.EXTRA_MISSION;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.widget.EditText;

import com.yeamy.daily.app.BaseActivity;
import com.yeamy.daily.data.HandleTask;
import com.yeamy.daily.data.Mission;

public class AddActivity extends BaseActivity implements View.OnClickListener {
    private EditText edit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);
        edit = (EditText) findViewById(R.id.edit);
        findViewById(R.id.fab).setOnClickListener(this);

        setTitle(R.string.title_add);
    }

    @Override
    public void onClick(View v) {
        String txt = edit.getText().toString();
        if (txt.length() == 0) {
            Snackbar.make(edit, R.string.empty_text, Snackbar.LENGTH_LONG).show();
            return;
        }
        final Mission mission = new Mission();
        mission.content = txt;
        HandleTask.add(this, mission, new Runnable() {
            @Override
            public void run() {
                Intent data = new Intent();
                data.putExtra(EXTRA_MISSION, mission);
                setResult(RESULT_ADD, data);
                finish();
            }
        });
    }

}


text:
var Backbone = require('backbone');
var $ = Backbone.$ = require('jquery');

var locations_template = require('../templates/locations.hbs');

module.exports = Backbone.View.extend({
	events: {
		'click a[href="#previous"]': 'clickPrevious',
		'click a[href="#next"]': 'clickNext'
	},
	initialize: function(){
		this.listenTo( this.collection, 'reset start', this.render );
		this.render();
	},
	render: function(){
		var context = {
			results: this.collection.current(),
			// determine if prev/next buttons need to be shown
			next: ( this.collection.start + 5 < this.collection.length ),
			previous: ( this.collection.start > 0 )
		};
		this.$el.html( locations_template( context ) );
	},
	clickPrevious: function( e ){
		e.preventDefault();
		this.collection.prev();
	},
	clickNext: function( e ){
		e.preventDefault();
		this.collection.next();
	}
})


text:
package cn.com.sunjiesh.wechat.model.request.event;

/**
 * 微信接收消息-点击菜单跳转链接时的事件推送
 * @author tomsun
 *
 */
public class WechatEventViewMessageRequest extends WechatEventMessageBaseRequest{
	/**
	 *
	 */
	private static final long serialVersionUID = -6567142691129426937L;

	public WechatEventViewMessageRequest(String toUserName,
			String fromUserName, String event, String eventKey) {
		super(toUserName, fromUserName, event, eventKey);
	}

}


text:
// Copyright 2004-present Facebook. All Rights Reserved.

package com.facebook.react.cxxbridge;

import java.util.Map;

import com.facebook.jni.HybridData;
import com.facebook.proguard.annotations.DoNotStrip;
import com.facebook.react.bridge.CatalystInstance;
import com.facebook.react.bridge.ExecutorToken;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReadableNativeArray;
import com.facebook.soloader.SoLoader;

/**
 * A Java Object which represents a cross-platform C++ module
 *
 */
@DoNotStrip
public class CxxModuleWrapper implements NativeModule
{
  static {
    SoLoader.loadLibrary(CatalystInstanceImpl.REACT_NATIVE_LIB);
  }

  @DoNotStrip
  private HybridData mHybridData;

  @DoNotStrip
  private static class MethodWrapper implements NativeMethod
  {
    @DoNotStrip
    HybridData mHybridData;

    MethodWrapper() {
      mHybridData = initHybrid();
    }

    public native HybridData initHybrid();

    @Override
    public native void invoke(
        CatalystInstance catalystInstance,
        ExecutorToken executorToken,
        ReadableNativeArray args);

    @Override
    public native String getType();
  }

  public CxxModuleWrapper(String library, String factory) {
    SoLoader.loadLibrary(library);
    mHybridData =
      initHybrid(SoLoader.unpackLibraryAndDependencies(library).getAbsolutePath(), factory);
  }

  @Override
  public native String getName();

  @Override
  public native Map<String, NativeMethod> getMethods();

  public native String getConstantsJson();

  @Override
  public void initialize() {
    // do nothing
  }

  @Override
  public boolean canOverrideExistingModule() {
    return false;
  }

  @Override
  public boolean supportsWebWorkers() {
    return false;
  }

  @Override
  public void onCatalystInstanceDestroy() {
    mHybridData.resetNative();
  }

  // For creating a wrapper from C++, or from a derived class.
  protected CxxModuleWrapper(HybridData hd) {
    mHybridData = hd;
  }

  private native HybridData initHybrid(String soPath, String factory);
}


text:
export default class Item extends Phaser.Sprite {
    constructor (game, x, y, key, frame) {
        super(game, x, y, key, frame);

        this.game.physics.enable(this, Phaser.Physics.ARCADE);

        this.player = this.game.player;
        this.spawnRate = 1; // value between 0 and 1, 1 means always 0 means practically never
        this.events.onInputDown.add(this.clicked, this);
    }

    update () {
        if (this.x < this.width - 100) { // kill items when they are off the screen
            this.destroy();
        } else {
            this.game.physics.arcade.overlap(this, this.player.cart, () => {this.collided()});
        }
    }

    clicked () {
        console.log('Something Clicked');
    }

    collided () {
        console.log('Something Collided');
    }
}


text:
[![browser status](http://ci.testling.com/dominictarr/event-stream.png)]
(http://ci.testling.com/dominictarr/event-stream)

[Streams](http://nodejs.org/api/stream.html "Stream") are node's best and most misunderstood idea, and
_EventStream_ is a toolkit to make creating and working with streams easy.

Normally, streams are only used for IO,
but in event stream we send all kinds of objects down the pipe.
If your application's input and output are streams,
shouldn't the throughput be a stream too?

The *EventStream* functions resemble the array functions,
because Streams are like Arrays, but laid out in time, rather than in memory.

All the `event-stream` functions return instances of `Stream`.

`event-stream` creates
[0.8 streams](https://github.com/joyent/node/blob/v0.8/doc/api/stream.markdown)
, which are compatible with [0.10 streams](http://nodejs.org/api/stream.html "Stream")

>NOTE: I shall use the term "through stream" to refer to a stream that is writable and readable.

###[simple example](https://github.com/dominictarr/event-stream/blob/master/examples/pretty.js):

``` js

//pretty.js

if(!module.parent) {
  var es = require('event-stream')
  es.pipeline(                         //connect streams together with `pipe`
    process.openStdin(),              //open stdin
    es.split(),                       //split stream to break on newlines
    es.map(function (data, callback) {//turn this async function into a stream
      callback(null
        , inspect(JSON.parse(data)))  //render it nicely
    }),
    process.stdout                    // pipe it to stdout !
    )
  }
```
run it ...

``` bash
curl -sS registry.npmjs.org/event-stream | node pretty.js
```

[node Stream documentation](http://nodejs.org/api/stream.html)

## through (write?, end?)

Reemits data synchronously. Easy way to create syncronous through streams.
Pass in an optional `write` and `end` methods. They will be called in the
context of the stream. Use `this.pause()` and `this.resume()` to manage flow.
Check `this.paused` to see current flow state. (write always returns `!this.paused`)

this function is the basis for most of the syncronous streams in `event-stream`.

``` js

es.through(function write(data) {
    this.emit('data', data)
    //this.pause()
  },
  function end () { //optional
    this.emit('end')
  })

```

##map (asyncFunction)

Create a through stream from an asyncronous function.

``` js
var es = require('event-stream')

es.map(function (data, callback) {
  //transform data
  // ...
  callback(null, data)
})

```

Each map MUST call the callback. It may callback with data, with an error or with no arguments,

  * `callback()` drop this data.
    this makes the map work like `filter`,
    note:`callback(null,null)` is not the same, and will emit `null`

  * `callback(null, newData)` turn data into newData

  * `callback(error)` emit an error for this item.

>Note: if a callback is not called, `map` will think that it is still being processed,
>every call must be answered or the stream will not know when to end.
>
>Also, if the callback is called more than once, every call but the first will be ignored.

## mapSync (syncFunction)

Same as `map`, but the callback is called synchronously. Based on `es.through`

## split (matcher)

Break up a stream and reassemble it so that each line is a chunk. matcher may be a `String`, or a `RegExp`

Example, read every line in a file ...

``` js
  es.pipeline(
    fs.createReadStream(file, {flags: 'r'}),
    es.split(),
    es.map(function (line, cb) {
       //do something with the line
       cb(null, line)
    })
  )

```

`split` takes the same arguments as `string.split` except it defaults to '\n' instead of ',', and the optional `limit` paremeter is ignored.
[String#split](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split)

## join (separator)

Create a through stream that emits `separator` between each chunk, just like Array#join.

(for legacy reasons, if you pass a callback instead of a string, join is a synonym for `es.wait`)

## merge (stream1,...,streamN)
> concat → merge

Merges streams into one and returns it.
Incoming data will be emitted as soon it comes into - no ordering will be applied (for example: `data1 data1 data2 data1 data2` - where `data1` and `data2` is data from two streams).
Counts how many streams was passed to it and emits end only when all streams emitted end.

```js
es.merge(
  process.stdout,
  process.stderr
).pipe(fs.createWriteStream('output.log'));
```

## replace (from, to)

Replace all occurences of `from` with `to`. `from` may be a `String` or a `RegExp`.
Works just like `string.split(from).join(to)`, but streaming.

## parse

Convienience function for parsing JSON chunks. For newline separated JSON,
use with `es.split`

``` js
fs.createReadStream(filename)
  .pipe(es.split()) //defaults to lines.
  .pipe(es.parse())
```

## stringify

convert javascript objects into lines of text. The text will have whitespace escaped and have a `\n` appended, so it will be compatible with `es.parse`

``` js
objectStream
  .pipe(es.stringify())
  .pipe(fs.createWriteStream(filename))
```

##readable (asyncFunction)

create a readable stream (that respects pause) from an async function.
while the stream is not paused,
the function will be polled with `(count, callback)`,
and `this`  will be the readable stream.

``` js

es.readable(function (count, callback) {
  if(streamHasEnded)
    return this.emit('end')

  //...

  this.emit('data', data) //use this way to emit multiple chunks per call.

  callback() // you MUST always call the callback eventually.
             // the function will not be called again until you do this.
})
```
you can also pass the data and the error to the callback.
you may only call the callback once.
calling the same callback more than once will have no effect.

##readArray (array)

Create a readable stream from an Array.

Just emit each item as a data event, respecting `pause` and `resume`.

``` js
  var es = require('event-stream')
    , reader = es.readArray([1,2,3])

  reader.pipe(...)
```

## writeArray (callback)

create a writeable stream from a callback,
all `data` events are stored in an array, which is passed to the callback when the stream ends.

``` js
  var es = require('event-stream')
    , reader = es.readArray([1, 2, 3])
    , writer = es.writeArray(function (err, array){
      //array deepEqual [1, 2, 3]
    })

  reader.pipe(writer)
```

## pipeline (stream1,...,streamN)

Turn a pipeline into a single stream. `pipeline` returns a stream that writes to the first stream
and reads from the last stream.

Listening for 'error' will recieve errors from all streams inside the pipe.

> `connect` is an alias for `pipeline`.

``` js

  es.pipeline(                         //connect streams together with `pipe`
    process.openStdin(),              //open stdin
    es.split(),                       //split stream to break on newlines
    es.map(function (data, callback) {//turn this async function into a stream
      callback(null
        , inspect(JSON.parse(data)))  //render it nicely
    }),
    process.stdout                    // pipe it to stdout !
    )
```

## pause  ()

A stream that buffers all chunks when paused.

``` js
  var ps = es.pause()
  ps.pause() //buffer the stream, also do not allow 'end'
  ps.resume() //allow chunks through
```

## duplex (writeStream, readStream)

Takes a writable stream and a readable stream and makes them appear as a readable writable stream.

It is assumed that the two streams are connected to each other in some way.

(This is used by `pipeline` and `child`.)

``` js
  var grep = cp.exec('grep Stream')

  es.duplex(grep.stdin, grep.stdout)
```

## child (child_process)

Create a through stream from a child process ...

``` js
  var cp = require('child_process')

  es.child(cp.exec('grep Stream')) // a through stream

```

## wait (callback)

waits for stream to emit 'end'.
joins chunks of a stream into a single string.
takes an optional callback, which will be passed the
complete string when it receives the 'end' event.

also, emits a single 'data' event.

``` js

readStream.pipe(es.wait(function (err, text) {
  // have complete text here.
}))

```

# Other Stream Modules

These modules are not included as a part of *EventStream* but may be
useful when working with streams.

## [reduce (syncFunction, initial)](https://github.com/parshap/node-stream-reduce)

Like `Array.prototype.reduce` but for streams. Given a sync reduce
function and an initial value it will return a through stream that emits
a single data event with the reduced value once the input stream ends.

``` js
var reduce = require("stream-reduce");
process.stdin.pipe(reduce(function(acc, data) {
  return acc + data.length;
}, 0)).on("data", function(length) {
  console.log("stdin size:", length);
});
```


text:
import { Component, OnInit, Inject, NgZone } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
import { AuthService } from './../../shared/auth.service';
import { Router } from '@angular/router';
import { SnackbarService } from '../../shared/snackbar.service';
import { environment } from '../../../environments/environment';
import { RecaptchaDynamicLanguageLoaderService } from '../../shared/recaptcha-dynamic-language-loader.service';
import { RecaptchaLoaderService } from 'ng-recaptcha';

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
    hide = true;
    loginForm: FormGroup;
    clientKey: string = environment.recaptcha.clientKey;
    loaderReady = false;

    constructor(
        public auth: AuthService,
        private formBuilder: FormBuilder,
        private router: Router,
        private snackBar: SnackbarService,
        @Inject(RecaptchaLoaderService) private loader: RecaptchaDynamicLanguageLoaderService,
        private zone: NgZone,
    ) {
        this.loginForm = this.formBuilder.group({
            email: ['test@example.com', [Validators.required, Validators.email]],
            password: ['123456', Validators.required],
            recaptcha: [null, Validators.required]
        });
    }

    ngOnInit() {
        this.loader.ready.subscribe(v => {
            this.loginForm.get('recaptcha').reset();
            this.zone.run(() => this.loaderReady = !!v);
        });
    }

    login() {
        const inputValue = this.loginForm.value;
        this.auth.login(inputValue.email, inputValue.password)
            .then(() => this.router.navigate(['/images']))
            .catch(error => this.errorHandler(error.code));

    }

    socialLogin(provider: string) {
        this.auth.loginWithProvider(provider)
            .then(success => { this.router.navigate(['/images']); })
            .catch(error => this.errorHandler(error.code));
    }

    private errorHandler(error: any) {
        this.snackBar.open('toast.serverResponse.' + error, 'toast.close');
    }

}


text:
package org.ams.repstats.entity;

import com.selesse.gitwrapper.myobjects.Author;
import com.selesse.gitwrapper.myobjects.Commit;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

/**
 * Сущность для отображения в таблице
 * Created with IntelliJ IDEA
 * User: Maxim Amosov <faystmax@gmail.com>
 * Date: 27.04.2017
 * Time: 9:00
 */
public class RepositoryObs {

    private SimpleIntegerProperty id;
    private SimpleStringProperty name;
    private SimpleStringProperty url;
    private SimpleObjectProperty<Date> dateOfCreation;
    private SimpleIntegerProperty idDeveloperResponsible;
    private SimpleStringProperty FIO;
    private SimpleStringProperty description;
    private SimpleIntegerProperty id_project_repository;

    //доп. поля
    private SimpleIntegerProperty commitCount = new SimpleIntegerProperty(0);
    private SimpleIntegerProperty linesAdd = new SimpleIntegerProperty(0);
    private SimpleIntegerProperty linesDelete = new SimpleIntegerProperty(0);
    private SimpleIntegerProperty netContribution = new SimpleIntegerProperty(0);
    private Author author;

    private Collection<Commit> commits = new ArrayList<Commit>();

    public RepositoryObs(int id, String name, String url, Date dateOfCreation, int idDeveloperResponsible, String FIO, String description, int id_project_repository) {
        this.id = new SimpleIntegerProperty(id);
        this.name = new SimpleStringProperty(name);
        this.url = new SimpleStringProperty(url);
        this.dateOfCreation = new SimpleObjectProperty<Date>(dateOfCreation);
        this.idDeveloperResponsible = new SimpleIntegerProperty(idDeveloperResponsible);
        this.FIO = new SimpleStringProperty(FIO);
        this.description = new SimpleStringProperty(description);
        this.id_project_repository = new SimpleIntegerProperty(id_project_repository);
        commitCount = new SimpleIntegerProperty(0);
        linesAdd = new SimpleIntegerProperty(0);
        linesDelete = new SimpleIntegerProperty(0);
        netContribution = new SimpleIntegerProperty(0);
    }

    public RepositoryObs(String url, Author author) {
        this.url = new SimpleStringProperty(url);
        this.author = author;
    }

    public int getId() {
        return id.get();
    }

    public SimpleIntegerProperty idProperty() {
        return id;
    }

    public void setId(int id) {
        this.id.set(id);
    }

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

    public SimpleStringProperty nameProperty() {
        return name;
    }

    public void setName(String name) {
        this.name.set(name);
    }

    public String getUrl() {
        return url.get();
    }

    public SimpleStringProperty urlProperty() {
        return url;
    }

    public void setUrl(String url) {
        this.url.set(url);
    }

    public Date getDateOfCreation() {
        return dateOfCreation.get();
    }

    public SimpleObjectProperty<Date> dateOfCreationProperty() {
        return dateOfCreation;
    }

    public void setDateOfCreation(Date dateOfCreation) {
        this.dateOfCreation.set(dateOfCreation);
    }

    public int getIdDeveloperResponsible() {
        return idDeveloperResponsible.get();
    }

    public SimpleIntegerProperty idDeveloperResponsibleProperty() {
        return idDeveloperResponsible;
    }

    public void setIdDeveloperResponsible(int idDeveloperResponsible) {
        this.idDeveloperResponsible.set(idDeveloperResponsible);
    }

    public String getFIO() {
        return FIO.get();
    }

    public SimpleStringProperty FIOProperty() {
        return FIO;
    }

    public void setFIO(String FIO) {
        this.FIO.set(FIO);
    }

    public String getDescription() {
        return description.get();
    }

    public SimpleStringProperty descriptionProperty() {
        return description;
    }

    public void setDescription(String description) {
        this.description.set(description);
    }

    public int getId_project_repository() {
        return id_project_repository.get();
    }

    public SimpleIntegerProperty id_project_repositoryProperty() {
        return id_project_repository;
    }

    public void setId_project_repository(int id_project_repository) {
        this.id_project_repository.set(id_project_repository);
    }

    public int getCommitCount() {
        return commitCount.get();
    }

    public SimpleIntegerProperty commitCountProperty() {
        return commitCount;
    }

    public void setCommitCount(int commitCount) {
        this.commitCount.set(commitCount);
    }

    public int getLinesAdd() {
        return linesAdd.get();
    }

    public SimpleIntegerProperty linesAddProperty() {
        return linesAdd;
    }

    public void setLinesAdd(int linesAdd) {
        this.linesAdd.set(linesAdd);
    }

    public int getLinesDelete() {
        return linesDelete.get();
    }

    public SimpleIntegerProperty linesDeleteProperty() {
        return linesDelete;
    }

    public void setLinesDelete(int linesDelete) {
        this.linesDelete.set(linesDelete);
    }

    public int getNetContribution() {
        return netContribution.get();
    }

    public SimpleIntegerProperty netContributionProperty() {
        return netContribution;
    }

    public void setNetContribution(int netContribution) {
        this.netContribution.set(netContribution);
    }

    public Collection<Commit> getCommits() {
        return commits;
    }

    public void setCommits(Collection<Commit> commits) {
        this.commits = commits;
    }

    public void addCommits(Collection<Commit> commits) {
        this.commits.addAll(commits);
    }

    public void addCommitCount(int commitCount) {
        this.commitCount.set(this.commitCount.get() + commitCount);
    }

    public void addLinesAdd(int linesAdd) {
        this.linesAdd.set(this.linesAdd.get() + linesAdd);
    }

    public void addLinesDelete(int linesDelete) {
        this.linesDelete.set(this.linesDelete.get() + linesDelete);
    }

    public void addNetContributiont(int netContribution) {
        this.netContribution.set(this.netContribution.get() + netContribution);
    }

    public Author getAuthor() {
        return author;
    }

    public void setAuthor(Author author) {
        this.author = author;
    }
}


text:
<html><head>
<meta name="description" content="exercise on multiplication of decimal numbers"/>
<meta name="author" content="annemarie.govindraj">
<meta name="keywords" content=" decimal point, decimal numbers, multiplication, mathematics, exercise, interactive, school">
</head><body>
<applet code="Decimals.java" width="100%" height="100%">
<param name="archive" value="decimals.jar">
<param name="level" value="3">
</applet></body>
</html>


text:
module Ijson
  module Command
    def self.included(base)
      base.send(:include, Hash) if base == ::Hash
      base.send(:include, Array) if base == ::Array
    end

    def self.use_binding_of env
      Ripl.shell.binding = env.instance_eval { binding }
    end

    def self.root=(value)
      use_binding_of value
      ChangeDir.root = value
    end

    module Hash
      def ls(value=nil)
        value ? self[value].ls : self.keys
      end
    end

    module Array
      def ls(value=nil)
        value ? self[value].ls : (0...size).to_a
      end
    end

    class ChangeDir
      class << self
        attr_accessor :root
        attr_accessor :current_path
      end

      def klass
        self.class
      end

      def initialize(env, paths, options={})
        @env = env
        @root = options[:root]
        @paths = paths
      end

      def is_root?
        @root
      end

      def run
        env = new_env
        return "invalid path #{@paths}" unless env

        klass.current_path = absolute_path
        Command.use_binding_of env
      end

      def new_env
        root = @root ? klass.root : @env
        @paths.inject(root) {|acc, path|
          case acc[path]
          when Hash, Array
            acc[path]
          else
            false
          end
        }
      end

      def absolute_path
        @root ? @paths : Array(klass.current_path) + @paths
      end
    end

    ChangeDir.current_path = []

    def cd *paths
      ChangeDir.new(self, paths).run
    end

    def cd! *paths
      ChangeDir.new(self, paths, :root => true).run
    end

    def pwd
      ChangeDir.current_path.map {|i| "[#{i}]" }.join
    end

    def cat *paths
      paths.inject(self) {|a, e| a[e]}
    end

  end
end


text:
package server

import (
	"errors"
	"net"
	"net/http"

	"github.com/docker/docker/context"
	"github.com/docker/docker/daemon"
)

// NewServer sets up the required Server and does protocol specific checking.
func (s *Server) newServer(proto, addr string) ([]serverCloser, error) {
	var (
		ls []net.Listener
	)
	switch proto {
	case "tcp":
		l, err := s.initTCPSocket(addr)
		if err != nil {
			return nil, err
		}
		ls = append(ls, l)

	default:
		return nil, errors.New("Invalid protocol format. Windows only supports tcp.")
	}

	var res []serverCloser
	for _, l := range ls {
		res = append(res, &HTTPServer{
			&http.Server{
				Addr:    addr,
				Handler: s.router,
			},
			l,
		})
	}
	return res, nil

}

// AcceptConnections allows router to start listening for the incoming requests.
func (s *Server) AcceptConnections(ctx context.Context, d *daemon.Daemon) {
	s.daemon = d
	s.registerSubRouter(ctx)
	// close the lock so the listeners start accepting connections
	select {
	case <-s.start:
	default:
		close(s.start)
	}
}

func allocateDaemonPort(addr string) error {
	return nil
}


text:
package org.apache.cassandra.distributed.impl;

import org.apache.cassandra.config.Config;
import org.apache.cassandra.config.ParameterizedClass;
import org.apache.cassandra.distributed.api.IInstanceConfig;
import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.locator.SimpleSeedProvider;
import org.apache.cassandra.locator.SimpleSnitch;

import java.io.File;
import java.lang.reflect.Field;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

public class InstanceConfig implements IInstanceConfig
{
    private static final Object NULL = new Object();

    public final int num;
    public int num() { return num; }

    public final UUID hostId;
    public UUID hostId() { return hostId; }
    private final Map<String, Object> params = new TreeMap<>();

    private volatile InetAddressAndPort broadcastAddressAndPort;

    @Override
    public InetAddressAndPort broadcastAddressAndPort()
    {
        if (broadcastAddressAndPort == null)
        {
            try
            {
                broadcastAddressAndPort = InetAddressAndPort.getByNameOverrideDefaults(getString("broadcast_address"), getInt("storage_port"));
            }
            catch (UnknownHostException e)
            {
                throw new IllegalStateException(e);
            }
        }
        return broadcastAddressAndPort;
    }

    private InstanceConfig(int num,
                           String broadcast_address,
                           String listen_address,
                           String broadcast_rpc_address,
                           String rpc_address,
                           String saved_caches_directory,
                           String[] data_file_directories,
                           String commitlog_directory,
                           String hints_directory,
                           String cdc_raw_directory,
                           String initial_token)
    {
        this.num = num;
        this.hostId = java.util.UUID.randomUUID();
        this    .set("broadcast_address", broadcast_address)
                .set("listen_address", listen_address)
                .set("broadcast_rpc_address", broadcast_rpc_address)
                .set("rpc_address", rpc_address)
                .set("saved_caches_directory", saved_caches_directory)
                .set("data_file_directories", data_file_directories)
                .set("commitlog_directory", commitlog_directory)
                .set("hints_directory", hints_directory)
                .set("cdc_raw_directory", cdc_raw_directory)
                .set("initial_token", initial_token)
                .set("partitioner", "org.apache.cassandra.dht.Murmur3Partitioner")
                .set("concurrent_writes", 2)
                .set("concurrent_counter_writes", 2)
                .set("concurrent_materialized_view_writes", 2)
                .set("concurrent_reads", 2)
                .set("memtable_flush_writers", 1)
                .set("concurrent_compactors", 1)
                .set("memtable_heap_space_in_mb", 10)
                .set("commitlog_sync", "batch")
                .set("storage_port", 7010)
                .set("endpoint_snitch", SimpleSnitch.class.getName())
                .set("seed_provider", new ParameterizedClass(SimpleSeedProvider.class.getName(),
                        Collections.singletonMap("seeds", "127.0.0.1:7010")))
                // required settings for dtest functionality
                .set("diagnostic_events_enabled", true)
                // legacy parameters
                .forceSet("commitlog_sync_batch_window_in_ms", 1.0);
                //
    }

    private InstanceConfig(InstanceConfig copy)
    {
        this.num = copy.num;
        this.params.putAll(copy.params);
        this.hostId = copy.hostId;
    }

    public InstanceConfig set(String fieldName, Object value)
    {
        if (value == null)
            value = NULL;

        // test value
        propagate(new Config(), fieldName, value, false);
        params.put(fieldName, value);
        return this;
    }

    private InstanceConfig forceSet(String fieldName, Object value)
    {
        if (value == null)
            value = NULL;

        // test value
        params.put(fieldName, value);
        return this;
    }

    public void propagateIfSet(Object writeToConfig, String fieldName)
    {
        if (params.containsKey(fieldName))
            propagate(writeToConfig, fieldName, params.get(fieldName), true);
    }

    public void propagate(Object writeToConfig)
    {
        for (Map.Entry<String, Object> e : params.entrySet())
            propagate(writeToConfig, e.getKey(), e.getValue(), true);
    }

    private void propagate(Object writeToConfig, String fieldName, Object value, boolean ignoreMissing)
    {
        if (value == NULL)
            value = null;

        Class<?> configClass = writeToConfig.getClass();
        Field valueField;
        try
        {
            valueField = configClass.getDeclaredField(fieldName);
        }
        catch (NoSuchFieldException e)
        {
            if (!ignoreMissing)
                throw new IllegalStateException(e);
            return;
        }

        if (valueField.getType().isEnum() && value instanceof String)
        {
            String test = (String) value;
            value = Arrays.stream(valueField.getType().getEnumConstants())
                    .filter(e -> ((Enum<?>)e).name().equals(test))
                    .findFirst()
                    .get();
        }
        try
        {
            valueField.set(writeToConfig, value);
        }
        catch (IllegalAccessException e)
        {
            throw new IllegalStateException(e);
        }
        catch (IllegalArgumentException e)
        {
            throw new IllegalStateException(e);
        }
    }

    public Object get(String name)
    {
        return params.get(name);
    }

    public int getInt(String name)
    {
        return (Integer)params.get(name);
    }

    public String getString(String name)
    {
        return (String)params.get(name);
    }

    public static InstanceConfig generate(int nodeNum, File root, String token)
    {
        return new InstanceConfig(nodeNum,
                                  "127.0.0." + nodeNum,
                                  "127.0.0." + nodeNum,
                                  "127.0.0." + nodeNum,
                                  "127.0.0." + nodeNum,
                                  String.format("%s/node%d/saved_caches", root, nodeNum),
                                  new String[] { String.format("%s/node%d/data", root, nodeNum) },
                                  String.format("%s/node%d/commitlog", root, nodeNum),
                                  String.format("%s/node%d/hints", root, nodeNum),
                                  String.format("%s/node%d/cdc", root, nodeNum),
                                  token);
    }

    public InstanceConfig forVersion(Versions.Major major)
    {
        switch (major)
        {
            case v4: return this;
            default: return new InstanceConfig(this)
                            .set("seed_provider", new ParameterizedClass(SimpleSeedProvider.class.getName(),
                                                                         Collections.singletonMap("seeds", "127.0.0.1")));
        }
    }

    public String toString()
    {
        return params.toString();
    }
}


text:
Imports System.ComponentModel
Imports LampCommon

Public Class ManageUserControl
    Public Property UsernameReadonly As Boolean
        Get
            Return TboxUsername.ReadOnly
        End Get
        Set(value As Boolean)
            TboxUsername.ReadOnly = value
        End Set
    End Property

    Private _user As New LampUser("", UserPermission.Guest, "", "", "", "")
    <DesignerSerializationVisibilityAttribute(False)>
    Public Property User As LampUser
        Get
            Return _user
        End Get
        Set(value As LampUser)
            _user = value
            UpdateContents()
        End Set
    End Property

    Private _readonly As Boolean
    Public Property [Readonly] As Boolean
        Get
            Return _readonly
        End Get
        Set(value As Boolean)
            _readonly = value
            If _readonly Then
                DisableEdit()
            Else
                EnableEdit()
            End If
        End Set
    End Property

    Private Sub EnableEdit()
        TboxEmail.ReadOnly = False
        TboxName.ReadOnly = False
        DropDownPermission.Enabled = True
        btnResetPassword.Enabled = True
    End Sub

    Friend Sub ValidateAll()
        ValidateEmail()
        ValidateUsername()
        ValidateName()
        ValidatePassword()
    End Sub

    Private Sub DisableEdit()
        TboxEmail.ReadOnly = True
        TboxName.ReadOnly = True
        DropDownPermission.Enabled = False
        btnResetPassword.Enabled = False
    End Sub

    Private Sub UpdateContents()
        TboxUsername.Text = User.Username
        TboxName.Text = User.Name
        Select Case User.PermissionLevel
            Case UserPermission.Standard
                DropDownPermission.SelectedItem = "Standard"
            Case UserPermission.Elevated
                DropDownPermission.SelectedItem = "Elevated"
            Case UserPermission.Admin
                DropDownPermission.SelectedItem = "Admin"
            Case Else
                DropDownPermission.Items.Add("Unknown")
                DropDownPermission.SelectedIndex = "Unknown"

        End Select
        TboxEmail.Text = User.Email
        TboxPassword.Text = User.Password

    End Sub

    Private allowEdit As Boolean = False

    Private Sub btnResetPassword_Click(sender As Object, e As EventArgs) Handles btnResetPassword.Click
        Using input As New LampPasswordBox()
            If input.ShowDialog(Me) = DialogResult.OK Then
                TboxPassword.Text = input.InputText
            End If
        End Using
    End Sub

    Private Const UnknownText = "Unknown"
    Private Sub DropDownPermission_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownPermission.SelectedIndexChanged
        Dim selected As String = DropDownPermission.SelectedItem
        If Not selected = UnknownText Then
            If DropDownPermission.Items.Contains(UnknownText) Then
                DropDownPermission.Items.Remove(UnknownText)
            End If
            Select Case selected
                Case "Standard"
                    User.PermissionLevel = UserPermission.Standard
                Case "Elevated"
                    User.PermissionLevel = UserPermission.Elevated
                Case "Admin"
                    User.PermissionLevel = UserPermission.Admin
                Case Else
#If DEBUG Then
                    Throw New ArgumentOutOfRangeException(NameOf(DropDownPermission.SelectedIndex))
#End If
            End Select
        End If
    End Sub

    Private Sub TextBox3_TextChanged(sender As Object, e As EventArgs) Handles TboxEmail.TextChanged
        ' tOdo email validation
        User.Email = TboxEmail.Text
        ValidateEmail()
    End Sub

    Private Sub TboxName_TextChanged(sender As Object, e As EventArgs) Handles TboxName.TextChanged
        User.Name = TboxName.Text
        ValidateName()
    End Sub

    Public Function ValidateEmail() As Boolean
        If TboxEmail.Text = "" Then
            ErrorProvider1.SetError(TboxEmail, "Email is empty")
            Return False
        ElseIf Not OwO.ValidateEmail(TboxEmail.Text) Then
            ErrorProvider1.SetError(TboxEmail, "Email in invalid format")
            Return False
        Else
            ErrorProvider1.SetError(TboxEmail, "")
        End If
        Return True
    End Function

    Public Function ValidateUsername() As Boolean
        If TboxUsername.Text = "" Then
            ErrorProvider1.SetError(TboxUsername, "Username is empty")
            Return False
        Else
            ErrorProvider1.SetError(TboxUsername, "")
        End If
        Return True
    End Function

    Public Function ValidateName() As Boolean
        If TboxName.Text = "" Then
            ErrorProvider1.SetError(TboxName, "Name is empty")
            Return False
        Else
            ErrorProvider1.SetError(TboxName, "")
        End If
        Return True
    End Function

    Private Sub TboxUsername_TextChanged(sender As Object, e As EventArgs) Handles TboxUsername.TextChanged
        User.Username = TboxUsername.Text
        ValidateUsername()
    End Sub

    Public Function ValidatePassword() As Boolean
        If TboxPassword.Text = "" Then
            ErrorProvider1.SetError(TboxPassword, "Password is empty")
            Return False
        ElseIf TboxPassword.Text.Length < MIN_PASSWORD_LENGTH Then
            ErrorProvider1.SetError(TboxPassword, String.Format("Password must be longer than {0} characters long", MIN_PASSWORD_LENGTH))
            Return False
        Else
            ErrorProvider1.SetError(TboxPassword, "")
        End If

        Return True
    End Function

    Private Sub TboxPassword_TextChanged(sender As Object, e As EventArgs) Handles TboxPassword.TextChanged
        User.Password = TboxPassword.Text
        ValidatePassword()
    End Sub
End Class

Public Class UserDeletedEventArgs
    Inherits EventArgs
    Public Property User As LampUser
    Sub New(user As LampUser)
        MyBase.New
        Me.User = user
    End Sub
End Class

Public Class UserEditedEventArgs
    Inherits EventArgs
    Public Property User As LampUser
    Sub New(user As LampUser)
        MyBase.New()
        Me.User = user

    End Sub
End Class


text:
FROM scratch
ADD rootfs.tar.xz /
CMD ["/bin/bash"]


text:
'use strict';

var gulp      = require('gulp'),
    nodemon   = require('gulp-nodemon'),
    when      = require('gulp-if'),
    shell     = require('gulp-shell');

// the paths to our app files
var paths = {
  // all our client app js files, not including 3rd party js files
  scripts: ['client/app/**/*.js'],
  html: ['client/app/**/*.html', 'client/index.html'],
  styles: ['client/styles/style.css'],
  test: ['specs/**/*.js']
};

// any changes made to your
// client side code will automagically refresh your page
// with the new changes
gulp.task('start', ['serve'],function () {
});

gulp.task('karma', shell.task([
  'karma start'
]));

// start our node server using nodemon
gulp.task('serve', function() {
  nodemon({script: './server/server.js', ignore: 'node_modules/**/*.js'});
});

gulp.task('default', ['start']);


text:
package com.sreemenon.sqlite;

import android.content.Context;
import android.security.KeyPairGeneratorSpec;

import com.sreemenon.crypt.KeyStoreHelper;

import net.sqlcipher.database.SQLiteDatabase;
import net.sqlcipher.database.SQLiteOpenHelper;

import java.io.IOException;
import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.UnrecoverableEntryException;
import java.security.cert.CertificateException;
import java.security.interfaces.RSAPrivateKey;
import java.util.Calendar;

import javax.security.auth.x500.X500Principal;

/**
 * SQLiteOpen Helper implementation
 */
public class SreeSqliteHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "open_sesame";

    private static final int DATABASE_VERSION = 4;

    SQLiteDatabase database;

    /**
     * Constructor
     *
     * @param context context for key pair generation and database initialization
     */
    public SreeSqliteHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);

        SQLiteDatabase.loadLibs(context);

        try {
            KeyStoreHelper keyStoreHelper = new KeyStoreHelper("AndroidKeyStore");
            if(!keyStoreHelper.getKeystore().containsAlias("diamond")) {
                keyStoreHelper.createNewKeyPair("diamond", context);
            }

            String dbPass = String.valueOf(keyStoreHelper.getPrivateKey("diamond").getModulus());
            database = getWritableDatabase(dbPass);

        } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableEntryException | IOException | CertificateException | NoSuchProviderException | InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        }
    }

    /**
     * Getter for Database variable
     * @return
     */
    protected SQLiteDatabase getDb() {
        return database;
    }

    /**
     * Close Database variable
     */
    protected void closeSqlDB(){
        database.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE `gems` (" +
                "`_id` integer PRIMARY KEY," +
                "`website` varchar(400)," +
                "`uname` varchar(400)," +
                "`salt` varchar(400) UNIQUE," +
                "`spl` integer," +
                "`num` integer," +
                "`ucase` integer," +
                "`ticket` varchar(400)," +
                "`genie` varchar(500)" +
                ")");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("Drop table if exists `gems`");

        onCreate(db);
    }
}