text:
/**
 * In-memory proxy. This proxy simply uses a local variable for data storage/retrieval, so its contents are lost on
 * every page refresh.
 *
 * Usually this Proxy isn't used directly, serving instead as a helper to a {@link Ext.data.Store Store} where a reader
 * is required to load data. For example, say we have a Store for a User model and have some inline data we want to
 * load, but this data isn't in quite the right format: we can use a MemoryProxy with a JsonReader to read it into our
 * Store:
 *
 *     //this is the model we will be using in the store
 *     Ext.define('User', {
 *         extend: 'Ext.data.Model',
 *         fields: [
 *             {name: 'id',    type: 'int'},
 *             {name: 'name',  type: 'string'},
 *             {name: 'phone', type: 'string', mapping: 'phoneNumber'}
 *         ]
 *     });
 *
 *     //this data does not line up to our model fields - the phone field is called phoneNumber
 *     var data = {
 *         users: [
 *             {
 *                 id: 1,
 *                 name: 'Ed Spencer',
 *                 phoneNumber: '555 1234'
 *             },
 *             {
 *                 id: 2,
 *                 name: 'Abe Elias',
 *                 phoneNumber: '666 1234'
 *             }
 *         ]
 *     };
 *
 *     //note how we set the 'root' in the reader to match the data structure above
 *     var store = Ext.create('Ext.data.Store', {
 *         autoLoad: true,
 *         model: 'User',
 *         data : data,
 *         proxy: {
 *             type: 'memory',
 *             reader: {
 *                 type: 'json',
 *                 rootProperty: 'users'
 *             }
 *         }
 *     });
 */
Ext.define('Ext.data.proxy.Memory', {
    extend: 'Ext.data.proxy.Client',
    alias: 'proxy.memory',
    alternateClassName: 'Ext.data.MemoryProxy',

    isMemoryProxy: true,

    config: {
        /**
        * @cfg {Boolean} [enablePaging]
        * Configure as `true` to enable this MemoryProxy to honour a read operation's `start` and `limit` options.
        *
        * When `true`, read operations will be able to read *pages* of records from the data object.
        */
       enablePaging: false,

        /**
        * @cfg {Object} data
        * Optional data to pass to configured Reader.
        */
        data: {
            $value: null,
            // Don't deeply clone the data object, just shallow copy the array
            merge: function(newValue, currentValue, target, mixinClass) {
                if (Ext.isArray(newValue)) {
                    return Ext.Array.clone(newValue);
                } else {
                    return Ext.clone(newValue);
                }
            }
        }
    },

    /**
     * @private
     * Fake processing function to commit the records, set the current operation
     * to successful and call the callback if provided. This function is shared
     * by the create, update and destroy methods to perform the bare minimum
     * processing required for the proxy to register a result from the action.
     */
    finishOperation: function(operation) {
        var i = 0,
            recs = operation.getRecords(),
            len = recs.length;

        for (i; i < len; i++) {
            recs[i].commit();
        }
        operation.setSuccessful(true);
    },

    /**
     * Currently this is a hard-coded method that simply commits any records and sets the operation to successful,
     * then calls the callback function, if provided. It is essentially mocking a server call in memory, but since
     * there is no real back end in this case there's not much else to do. This method can be easily overridden to
     * implement more complex logic if needed.
     * @param {Ext.data.operation.Operation} operation The Operation to perform
     * @method
     */
    create: function(operation) {
        this.finishOperation(operation);
    },

    /**
     * Currently this is a hard-coded method that simply commits any records and sets the operation to successful,
     * then calls the callback function, if provided. It is essentially mocking a server call in memory, but since
     * there is no real back end in this case there's not much else to do. This method can be easily overridden to
     * implement more complex logic if needed.
     * @param {Ext.data.operation.Operation} operation The Operation to perform
     * @method
     */
    update: function(operation) {
        this.finishOperation(operation);
    },

    /**
     * Currently this is a hard-coded method that simply commits any records and sets the operation to successful,
     * then calls the callback function, if provided. It is essentially mocking a server call in memory, but since
     * there is no real back end in this case there's not much else to do. This method can be easily overridden to
     * implement more complex logic if needed.
     * @param {Ext.data.operation.Operation} operation The Operation to perform
     * @method
     */
    erase: function(operation) {
        this.finishOperation(operation);
    },

    /**
     * Reads data from the configured {@link #data} object. Uses the Proxy's {@link #reader}, if present.
     * @param {Ext.data.operation.Operation} operation The read Operation
     */
    read: function(operation) {
        var me = this,
            resultSet = me.getReader().read(me.getData()),
            records = resultSet.getRecords(),
            sorters = operation.getSorters(),
            grouper = operation.getGrouper(),
            filters = operation.getFilters(),
            start = operation.getStart(),
            limit = operation.getLimit(),
            meta;

        // Apply filters, sorters, and start/limit options
        if (operation.process(resultSet, null, null, false) !== false) {
            // Filter the resulting array of records
            if (filters && filters.length) {
                // Total will be updated by setting records
                resultSet.setRecords(records = Ext.Array.filter(records, Ext.util.Filter.createFilterFn(filters)));
                resultSet.setTotal(records.length);
            }

            // Remotely, grouper just mean top priority sorters
            if (grouper) {
                // Must concat so as not to mutate passed sorters array which could be the items property of the sorters collection
                sorters = sorters ? sorters.concat(grouper) : sorters;
            }

            // Sort by the specified grouper and sorters
            if (sorters && sorters.length) {
                resultSet.setRecords(records = Ext.Array.sort(records, Ext.util.Sortable.createComparator(sorters)));
            }

            // Reader reads the whole passed data object.
            // If successful and we were given a start and limit, slice the result.
            if (me.getEnablePaging() && start !== undefined && limit !== undefined) {

                // Attempt to read past end of memory dataset - convert to failure
                if (start >= resultSet.getTotal()) {
                    resultSet.setConfig({
                        success: false,
                        records: [],
                        total: 0
                    });
                }
                // Range is valid, slice it up.
                else {
                    resultSet.setRecords(Ext.Array.slice(records, start, start + limit));
                }
            }
            operation.setCompleted();

            // If a JsonReader detected metadata, process it now.
            // This will fire the 'metachange' event which the Store processes to fire its own 'metachange'
            if (meta = resultSet.getMetadata()) {
                me.onMetaChange(meta);
            }
        }
    },

    clear: Ext.emptyFn
});


text:
<!DOCTYPE html>

    <title>Chief Complaint ::  Registration</title>

 Registration

Chief Complaint ::

                                Created By :

                                Last Modified By :

No Chief Complaint found

                                    Chief Complaint:

                                    Present Illness:

                                     Comments:

                                 Add New

                                  Edit

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Rating = System.Tuple<long,double>;

namespace SAD2.Skething{
class MinSketch{
private const double delta = 0.01;

static void Main(string[] args){
	if (args.Length < 2) {
		Console.WriteLine("This program takes 2 parameters: a filename and a value for epsilon");
		return;
	}

	char[] commaSep = new char[] {','};
	double epsilon = double.Parse(args[1]);

	IEnumerable<Rating> ratings = File.ReadLines(args[0])
		.Select(line => {
			string[] l = line.Split(commaSep);
			//(movieId, rating) pair
			return Tuple.Create(long.Parse(l[0]),
					    double.Parse(l[1]));
		});

	IEnumerable<Rating> averages = EstimatedAverages(ratings, epsilon, delta).OrderByDescending(r => r.Item2);
	foreach (Rating r in averages) {
		Console.WriteLine("{0},{1}", r.Item1, r.Item2);
	}
}

private static IEnumerable<Rating> EstimatedAverages(IEnumerable<Rating> ratings, double epsilon, double delta) {
	HashSet<long> seen = new HashSet<long>();
	Sketch sumSketch = new Sketch(epsilon, delta, 99999);
	Sketch frequencySketch = new Sketch(sumSketch);
	ratings.ForEach(r => {
		seen.Add(r.Item1);
		sumSketch.Add(r); //sum of ratings
		frequencySketch.Add(Tuple.Create(r.Item1, 1.0)); //freq of ratings
	});
	List<Rating> avgs = new List<Rating>();
	foreach(long i in seen){
		double sum = sumSketch.Get(i);
		double freq = frequencySketch.Get(i);
			avgs.Add(Tuple.Create(i, sum/freq));
	}
	return avgs;
}
}

static class Extensions {
public static void ForEach<T>(this System.Collections.Generic.IEnumerable<T> l, System.Action<T> f) {
	foreach (T x in l) {
		f(x);
	}
}}}


text:
// @@@ START COPYRIGHT @@@
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//
// @@@ END COPYRIGHT @@@

package org.trafodion.sql.udr;
import java.nio.ByteBuffer;

// TO BE DONE (1) 3 serialize methods and (2) EvaluationCode is stored as an emum and not
// as an int. So it is not a bit flag.

/**
   *  A predicate to be evaluated on a table
   *
   *  These could be different kinds of predicates, like an equals
   *  predicate, a non-equals predicate or more complex cases.
  */

public abstract class PredicateInfo extends TMUDRSerializableObject
{
    /**
     *  Info on whether a table-valued input or output column is used
     *
     *  <p> Note that these are not necessarily exclusive, a predicate might
     *  be evaluated in multiple places, although that should not be
     *  common and is not yet allowed.
     */
    public enum EvaluationCode
    {
        /** Not yet determined where predicate is evaluated. */
        UNKNOWN_EVAL        (0),
        /**  Predicate is evaluated on the UDF result, in Trafodion code. This is the default. */
        EVALUATE_ON_RESULT  (0x1),
        /** Predicate is evaluated inside the code provided by the UDF writer. */
        EVALUATE_IN_UDF     (0x2),
        /** Predicate should be evaluated in a table-valued input before the data reaches the UDF. */
        EVALUATE_IN_CHILD   (0x4);

        private final int code_;

        EvaluationCode(int val) {
            code_ = val;
        }

        public int getEvaluationCode() {
            return code_;
        }

        public static EvaluationCode getEnum(int x) {
          switch (x) {
          case 0:
            return UNKNOWN_EVAL;
          case 0x1:
            return EVALUATE_ON_RESULT;
          case 0x2:
            return EVALUATE_IN_UDF;
          case 0x4:
            return EVALUATE_IN_CHILD;
          default:
            return UNKNOWN_EVAL;
          }
        }
    };

    /** Operator of a relational (comparison) predicate */
    public enum PredOperator
    {
        /** Operator not yet determined */
        UNKNOWN_OP,
        /** Equals predicate (col = val) */
        EQUAL,
        /** Not equals predicate (col <> val) */
        NOT_EQUAL,
        /** Less than predicate (col <) */
        LESS,
        /** Less or equals predicate (col <=) */
        LESS_EQUAL,
        /** Greater than predicate (col >) */
        GREATER,
        /** Greater or equals predicate (col >=) */
        GREATER_EQUAL,
        /** IN predicate (col IN) */
        IN,
        /** NOT IN predicate (col NOT IN) */
        NOT_IN ;

       private static PredOperator[] allValues = values();
       public static PredOperator fromOrdinal(int i) {
         return allValues[i];
       }
    };

    /**
     *  Get evaluation code for a predicate.
     *  @return Evaluation code.
     */
    public EvaluationCode getEvaluationCode() {
        return evalCode_ ;
    }

    /**
     *  Get operator code for a predicate.
     *  @return Operator code.
     */
    public PredOperator getOperator() {
        return operator_ ;
    }

    /**
     *  Check whether this predicate is a comparison predicate.
     *
     *  <p> Use this method to determine  whether it is safe to cast the object
     *  to class ComparisonPredicateInfo.

     *  @return true if predcate i is a comparison predicate, false otherwise.
     */
    public boolean isAComparisonPredicate() {
        switch (operator_)
        {
        case EQUAL:
        case NOT_EQUAL:
        case LESS:
        case LESS_EQUAL:
        case GREATER:
        case GREATER_EQUAL:
            return true;

        default:
            return false;
        }
    }

    // UDR writers can ignore these methods
    public PredicateInfo(TMUDRSerializableObject.TMUDRObjectType t) {
        super(t, getCurrentVersion());
        evalCode_ = EvaluationCode.UNKNOWN_EVAL;
        operator_ = PredOperator.UNKNOWN_OP;
    }

    public void setOperator(PredOperator op) {
        operator_ = op;
    }

    public void setEvaluationCode(EvaluationCode c) {
        evalCode_ = c ;
    }
    public abstract String toString(TableInfo ti) throws UDRException;

    public static short getCurrentVersion() { return 1; }

    @Override
    public int serializedLength() throws UDRException{
      return super.serializedLength() + 2 * serializedLengthOfInt();
    }

    @Override
    public int serialize(ByteBuffer outputBuffer) throws UDRException{

      int origPos = outputBuffer.position();

      super.serialize(outputBuffer);

      serializeInt(evalCode_.getEvaluationCode(),
                   outputBuffer);

      serializeInt(operator_.ordinal(),
                   outputBuffer);

      // validate length in derived classes
      int bytesSerialized = outputBuffer.position() - origPos;

      return bytesSerialized;
    }

    @Override
    public int deserialize(ByteBuffer inputBuffer) throws UDRException {
     int origPos = inputBuffer.position();

      super.deserialize(inputBuffer);

      int op = 0;

      op = deserializeInt(inputBuffer);

      evalCode_ = EvaluationCode.getEnum(op);

      op = deserializeInt(inputBuffer);

      operator_ = PredOperator.fromOrdinal(op);

      // validate operator type and length in derived classes
      int bytesDeserialized = inputBuffer.position() - origPos;

      return bytesDeserialized;
    }

    private EvaluationCode evalCode_;
    private PredOperator operator_;

}


text:
<?php

use yii\bootstrap\ActiveForm;
use kartik\file\FileInput;
use yii\helpers\Url;
use yii\helpers\Html;

?>

<?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'general_image')->widget(FileInput::classname(),[
        'options' => [
            'accept' => 'image/*',
        ],
        'pluginOptions' => [
            'uploadUrl' => Url::to(['file-upload-general']),
            'uploadExtraData' => [
                'advert_id' => $model->idadvert,
            ],
            'allowedFileExtensions' =>  ['jpg', 'png','gif'],
            'initialPreview' => $image,
            'showUpload' => true,
            'showRemove' => false,
            'dropZoneEnabled' => true
        ]
    ]);
    ?>

    <?= Html::label('Images');
    echo FileInput::widget([
        'name' => 'images',
        'options' => [
            'accept' => 'image/*',
            'multiple'=>true
        ],
        'pluginOptions' => [
            'uploadUrl' => Url::to(['file-upload-images']),
            'uploadExtraData' => [
                'advert_id' => $model->idadvert,
            ],
            'overwriteInitial' => false,
            'allowedFileExtensions' =>  ['jpg', 'png','gif'],
            'initialPreview' => $images_add,
            'showUpload' => true,
            'showRemove' => true,
            'dropZoneEnabled' => true
        ]
    ]);
    ?>

    <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

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


text:
"""Unittests for the arac.pybrainbridge module."""

__author__ = 'Justin S Bayer, bayer.justin@googlemail.com'

import unittest
import scipy

import arac.cppbridge
from arac.tests.common import TestCase

class TestStructure(TestCase):

    def testFullConnection(self):
        params = scipy.array((1, 2, 3, 4), dtype='float64')
        derivs = scipy.zeros(4, dtype='float64')
        l1 = arac.cppbridge.LinearLayer(2)
        l2 = arac.cppbridge.LinearLayer(2)
        c = arac.cppbridge.FullConnection(l1, l2, params, derivs, 0, 2, 0, 2)

        self.assertEqual(c.get_incomingstart(), 0)
        self.assertEqual(c.get_incomingstop(), 2)
        self.assertEqual(c.get_outgoingstart(), 0)
        self.assertEqual(c.get_outgoingstop(), 2)

        self.assert_(c.this is not None)

    def testNetwork(self):
        l1 = arac.cppbridge.LinearLayer(2)
        l2 = arac.cppbridge.LinearLayer(2)

        params = scipy.array((1, 2, 3, 4), dtype='float64')
        derivs = scipy.zeros(4)
        con = arac.cppbridge.FullConnection(l1, l2, params, derivs, 0, 2, 0, 2)
        # con = arac.cppbridge.IdentityConnection(l1, l2, 0, 2, 0, 2)

        net = arac.cppbridge.Network()
        net.add_module(l1, arac.cppbridge.Network.InputModule)
        net.add_module(l2, arac.cppbridge.Network.OutputModule)
        net.add_connection(con)
        inpt = scipy.array((3., 4.))
        result = scipy.zeros(2)
        net.activate(inpt, result)
        self.assertArrayNear(result, scipy.array((11, 25)))

    def testNetworkClear(self):
        net = arac.cppbridge.Network()
        l = arac.cppbridge.LinearLayer(1)
        net.add_module(l, arac.cppbridge.Network.InputOutputModule)
        inputbuffer = scipy.ones((1, 1))
        outputbuffer = scipy.ones((1, 1))
        inputerror = scipy.ones((1, 1))
        outputerror = scipy.ones((1, 1))
        net.init_input(inputbuffer)
        net.init_output(outputbuffer)
        net.init_inerror(inputerror)
        net.init_outerror(outputerror)
        net.clear()
        self.assert_((inputbuffer == 0).all())
        self.assert_((outputbuffer == 0).all())
        self.assert_((inputerror == 0).all())
        self.assert_((outputerror == 0).all())

    def testCreateHugeModule(self):
        s = 1000
        l = arac.cppbridge.LinearLayer(s)
        self.assertEqual(l.insize(), s)
        self.assertEqual(l.outsize(), s)
        l = arac.cppbridge.MdlstmLayer(1, s)
        self.assertEqual(l.insize(), 5 * s)
        self.assertEqual(l.outsize(), 2 * s)

if __name__ == "__main__":
    unittest.main()


text:
============================
django-theroomofcode-project
============================

A project template for Django 1.7.

To use this project follow these steps:

#. Create your working environment
#. Install Django
#. Create the new project using the django-cuble template
#. Install additional dependencies
#. Use the Django admin to create the project

*note: these instructions show creation of a project called "potato". You
should replace this name with the actual name of your project.*

Working Environment
===================

You have several options in setting up your working environment. We recommend
using virtualenv to separate the dependencies of your project from your system's
python environment. If on Linux or Mac OS X, you can also use virtualenvwrapper to help manage multiple virtualenvs across different projects.

Virtualenv Only
---------------

First, make sure you are using virtualenv (http://www.virtualenv.org). Once
that's installed, create your virtualenv::

    $ virtualenv --distribute potato

You will also need to ensure that the virtualenv has the project directory
added to the path. Adding the project directory will allow `django-admin.py` to
be able to change settings using the `--settings` flag.

Virtualenv with virtualenvwrapper
---------------------------------

In Linux and Mac OSX, you can install virtualenvwrapper (http://virtualenvwrapper.readthedocs.org/en/latest/),
which will take care of managing your virtual environments and adding the
project path to the `site-directory` for you::

    $ mkdir potato
    $ mkvirtualenv -a potato potato-dev
    $ cd potato && add2virtualenv `pwd`

Using virtualenvwrapper with Windows
------------------------------------

There is a special version of virtualenvwrapper for use with Windows (https://pypi.python.org/pypi/virtualenvwrapper-win).::

    > mkdir potato
    > mkvirtualenv potato-dev
    > add2virtualenv potato

Installing Django
=================

To install Django in the new virtual environment, run the following command::

    $ pip install django

Creating your project
=====================

To create a new Django project called '**potato**' using
django-cuble-project, run the following command::

    $ django-admin.py startproject --template=https://github.com/theroomofcode/django-theroomofcode-project/archive/master.zip --extension=py,rst,html,less,coffee potato_project

Installation of Dependencies
============================

Depending on where you are installing dependencies:

In development::

    $ pip install -r requirements/local.txt

For production::

    $ pip install -r requirements.txt

*note: We install production requirements this way because many Platforms as a
Services expect a requirements.txt file in the root of projects.*


text:
import click
import cv2
import math
import numpy as np

@click.group()
@click.option('--out', '-o', default=None)
@click.pass_context
def cli(ctx, out):
    ctx.obj['out'] = out

@click.pass_context
def save(ctx, img):
    if ctx.obj.get('out') is not None:
        click.echo('output to {}'.format(ctx.obj.get('out')))
        cv2.imwrite(ctx.obj.get('out'), img)
    else:
        cv2.imshow('image', img)
        cv2.waitKey(0)
        cv2.destroyAllWindows()

@cli.command()
@click.argument('image', type=click.Path(exists=True), required=True)
def grayscale(image):
    im = cv2.imread(image)
    im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    save(im)

@cli.command()
@click.argument('base_image', type=click.Path(exists=True), required=True)
@click.argument('correlate_image', type=click.Path(exists=True), required=True)
def correlate(base_image, correlate_image):
    base_im_gray = cv2.imread(base_image, 0)
    save(base_im_gray)
    correlate_im_gray = cv2.imread(correlate_image, 0)
    (dx, dy), _ = cv2.phaseCorrelate(np.float32(correlate_im_gray), np.float32(base_im_gray))
    M = np.float32([[1, 0, dx], [0, 1, dy]])
    rows, cols = base_im_gray.shape
    im_moved = cv2.warpAffine(cv2.imread(correlate_image, 1), M, (cols, rows))

    # fill outline with dummy color
    mask = np.full(base_im_gray.shape, 255, dtype=np.uint8)
    mask[math.ceil(abs(dy)):rows, math.ceil(abs(dx)):cols] = 0
    if dx < 0:
        mask = mask.T[::-1].T
    if dy < 0:
        mask = mask[::-1]
    im_moved = cv2.inpaint(im_moved, mask, 3, cv2.INPAINT_TELEA)
    save(im_moved)

@cli.group()
def create():
    pass

def get_gradation_2d(start, stop, width, height, is_horizontal=False):
    if is_horizontal:
        return np.tile(np.linspace(start, stop, height), (width, 1))
    else:
        return np.tile(np.linspace(start, stop, width), (height, 1)).T

@create.command()
@click.option('--start', '-s', type=int, required=False, default=0)
@click.option('--end', '-e', type=int, required=False, default=255)
@click.option('--width', '-w', type=int, required=False, default=100)
@click.option('--height', '-h', type=int, required=False, default=100)
@click.option('--is_horizontal', is_flag=True, default=False)
def gradation_2d(start, end, width, height, is_horizontal):
    start = start / 255
    end = end / 255
    image = get_gradation_2d(start, end, width, height, is_horizontal)
    save(image)

@create.command()
@click.option('--start', '-s', type=click.Tuple([int, int, int]), required=False, default=(192, 0, 0))
@click.option('--end', '-e', type=click.Tuple([int, int, int]), required=False, default=(64, 255, 255))
@click.option('--width', '-w', type=int, required=False, default=100)
@click.option('--height', '-h', type=int, required=False, default=100)
@click.option('--is_horizontal', type=click.Tuple([bool, bool, bool]), default=(False, False, True))
def gradation_3d(start, end, width, height, is_horizontal):
    image = np.zeros((width, height, len(start)), dtype=np.float)
    start = (x / 255 for x in start)
    end = (x / 255 for x in end)
    for i, (st, en, is_h) in enumerate(zip(start, end, is_horizontal)):
        grad = get_gradation_2d(st, en, width, height, is_h)
        image[:, :, i] = grad
    save(image)

@cli.group()
def filter():
    pass

@filter.command()
@click.argument('image', type=click.Path(exists=True), required=True)
@click.option('--ksize', '-k', nargs=2, type=click.Tuple([int, int]), default=(3, 3))
def blur(image, ksize):
    im = cv2.imread(image)
    im = cv2.blur(im, ksize=ksize)
    save(im)

@filter.command()
@click.argument('image', type=click.Path(exists=True), required=True)
@click.option('--pillow_kernel', '-p', is_flag=True, default=False)
def sharpen(image, pillow_kernel):
    if pillow_kernel is False:
        # https://en.wikipedia.org/wiki/Kernel_(image_processing)
        kernel = np.array([
            [0, -1, 0],
            [-1, 5, -1],
            [0, -1, 0],
        ])
    else:
        # pillow's sharpen kernel
        kernel = np.array([
            [-2, -2, -2],
            [-2, 32, -2],
            [-2, -2, -2],
        ]) / 16
    im = cv2.imread(image)
    im = cv2.filter2D(
        im,
        -1,
        kernel
    )
    save(im)

@filter.command()
@click.argument('image', type=click.Path(exists=True), required=True)
@click.option('--neiborhood', '-n', type=click.Choice([4, 8]), default=4)
def erosion(image, neiborhood):
    im = cv2.imread(image, 0)
    if neiborhood == 4:
        kernel = np.array([
            [0, 1, 0],
            [1, 1, 1],
            [0, 1, 0],
        ], np.uint8)
    else:
        kernel = np.ones((5, 5), np.uint8)
    im = cv2.erode(im, kernel, iterations=1)
    save(im)

def main():
    cli(obj={})

if __name__ == '__main__':
    main()


text:
Textfields

Basic

				<input class="textfield-input" type="text" placeholder="placeholder" />
				Textfield label

				<input class="textfield-input" type="text" value="disabled input" disabled />
				Textfield label

Sizes

Small

				<input class="textfield-input" type="text" placeholder="placeholder" />
				Textfield label

				<input class="textfield-input" type="text" value="disabled input" disabled />
				Textfield label

Smaller

				<input class="textfield-input" type="text" placeholder="placeholder" />
				Textfield label

				<input class="textfield-input" type="text" value="disabled input" disabled />
				Textfield label

mod-material

					<input class="textfield-input" type="text" placeholder="placeholder" />
					Textfield label

					<input class="textfield-input is-filled" type="text" value="disabled input" disabled />
					Textfield label

mod-compact

					<input class="textfield-input" type="text" placeholder="placeholder" />
					Textfield label

					<input class="textfield-input" type="text" value="disabled input" disabled />
					Textfield label

mod-outlined

					<input class="textfield-input" type="text" placeholder="placeholder" />
					Textfield label

					<input class="textfield-input is-filled" type="text" value="disabled input" disabled />
					Textfield label

					<input class="textfield-input" type="text" placeholder="placeholder" />
					Textfield label

					<input class="textfield-input is-filled" type="text" value="disabled input" disabled />
					Textfield label

					<input class="textfield-input is-error is-filled" type="text" placeholder="placeholder..." />
					Textfield label

					<input class="textfield-input is-error is-filled" type="text" value="input" />
					Textfield label

mod-block

					<input class="textfield-input" type="text" placeholder="placeholder" />
					Textfield label

					<input class="textfield-input is-filled" type="text" value="disabled input" disabled />
					Textfield label

mod-password

					<input class="textfield-input" type="password" placeholder="placeholder" value="azerty12345#@!%;" />
					Password label

							Show password

					<input class="textfield-input" type="text" placeholder="placeholder" value="azerty12345#@!%;" />
					Password label

							Show password

	Tip: Use <label class="textfield mod-block"> for a 100% width input.

	Tip: Use <input class="textfield-input is-filled"> to let the label on the upper state
		with mod-material.

	Tip: You can use placeholder="…" on textfield-input.

Helper / Warning / Error / Success

					<input class="textfield-input" type="text" placeholder="placeholder" />
					Textfield label

						Few tips about the input

					<input class="textfield-input is-warning" type="text" placeholder="placeholder" />
					Textfield label

						Humm, there is a warning…

					<input class="textfield-input is-error" type="text" placeholder="placeholder" />
					Textfield label

						Oops, there is an error!

					<input class="textfield-input is-success" type="text" placeholder="placeholder" />
					Textfield label

						It's a win!

					<input class="textfield-input" type="text" placeholder="placeholder" />
					Textfield label

						Few tips about the input

					<input class="textfield-input is-warning" type="text" placeholder="placeholder" />
					Textfield label

						Humm, there is a warning…

					<input class="textfield-input is-error" type="text" placeholder="placeholder" />
					Textfield label

						Oops, there is an error!

					<input class="textfield-input is-success" type="text" placeholder="placeholder" />
					Textfield label

						It's a win!

				<input class="textfield-input" type="text" placeholder="placeholder" />
				Textfield label

					Few tips about the input

				<input class="textfield-input is-warning" type="text" placeholder="placeholder" />
				Textfield label

					Humm, there is a warning…

				<input class="textfield-input is-error" type="text" placeholder="placeholder" />
				Textfield label

					Oops, there is an error!

				<input class="textfield-input is-success" type="text" placeholder="placeholder" />
				Textfield label

					It's a win!

Palettes

					<input class="textfield-input" type="text" placeholder="placeholder" />
					Textfield label primary

					<input class="textfield-input" type="text" placeholder="placeholder" />
					Textfield label secondary

					<input class="textfield-input" type="text" placeholder="placeholder" />
					Textfield label gray

					<input class="textfield-input" type="text" placeholder="placeholder" />
					Textfield label success

					<input class="textfield-input" type="text" placeholder="placeholder" />
					Textfield label warning

					<input class="textfield-input" type="text" placeholder="placeholder" />
					Textfield label error

Inline validation

	You can add a is-loading and a is-valid or is-invalid class
	on <label class="textfield"> for your inline validation.

				<input class="textfield-input" type="text" placeholder="Focus / Unfocus me" onblur="validationFocus(this)" />
				Loading > valid

				<input class="textfield-input" type="text" placeholder="Focus / Unfocus me" onblur="unvalidationFocus(this)" />
				Loading > invalid

Suffix

You can use a class mod-withSuffix to support a suffix on your input.

					<input class="textfield-input" type="text" />
					Textfield label
					€

					<input class="textfield-input" type="text" />
					Textfield label
					€

					<input class="textfield-input" type="text" />
					Textfield label
					€

	Tip: If you are using a classic textfield without label, you'll need to add a
		mod-noLabel class.

Inline

Inline textfields works well with mod-material, but you can also use it with standard style.

		<input class="textfield-input" type="text" />
		Textfield label

		<input class="textfield-input" type="text" />
		Textfield label

		<input class="textfield-input" type="text" />
		Textfield label

		<input class="textfield-input" type="text" />
		Textfield label

		<input class="textfield-input" type="text" />
		Textfield label

		<input class="textfield-input" type="text" />
		Textfield label

		<input class="textfield-input" type="text" />
		Textfield label

	Tip: You can change the input lenght with mod-longest,mod-longer,mod-long, mod-short,mod-shorter or
		mod-shortest.

	Tip: You can use inline input inside standard text:

		Hello I'm

			<input class="textfield-input" type="text" placeholder="ex. Janis" />
			name

		from

			<input class="textfield-input" type="text" placeholder="ex. Port Arthur" />
			city

Search

				<input class="textfield-input" type="search" placeholder="e.g. Clark Kent" />
				Search

				<input class="textfield-input" type="search" placeholder="e.g. Clark Kent" />
				Search

				<input class="textfield-input" type="search" placeholder="e.g. Clark Kent" />
				Search

	Tip: You can change the input style using mod-material &
		mod-compact

Clearable

				<input class="textfield-input" type="text" placeholder="e.g. Clark Kent" />
				Search

					thin_cross
					Clear

				<input class="textfield-input" type="text" placeholder="e.g. Clark Kent" />
				Search

					thin_cross
					Clear

				<input class="textfield-input" type="text" placeholder="e.g. Clark Kent" />
				Search

					thin_cross
					Clear

				<input class="textfield-input" type="text" />
				Textfield label

					thin_cross
					Clear

Required

		<input class="textfield-input" type="text" placeholder="placeholder" />
		Required textfield

White

			<input class="textfield-input" type="text" placeholder="placeholder" />
			Textfield label

Inverted

			<input class="textfield-input" type="text" placeholder="placeholder" />
			Textfield label

Multilines

						<textarea class="textfield-input"></textarea>
						Textarea label

						<textarea class="textfield-input is-filled" disabled>
Disabled textarea ø Disabled textarea ø Disabled textarea ø Disabled textarea ø</textarea
						>
						Textarea label

						<textarea class="textfield-input"></textarea>
						Textarea label

						<textarea class="textfield-input is-filled" disabled>
Disabled textarea ø Disabled textarea ø Disabled textarea ø Disabled textarea ø</textarea
						>
						Textarea label

						<textarea class="textfield-input"></textarea>
						Textarea label

						<textarea class="textfield-input is-filled" disabled>
Disabled textarea ø Disabled textarea ø Disabled textarea ø Disabled textarea ø</textarea
						>
						Textarea label

	Tip: Use <label class="textfield mod-block"> for a 100% width textarea.

	Tip: Use <label class="textfield-input is-filled"> to let the label on the upper state
		with mod-material.

Radio label

		<input class="radio-input" type="radio" name="radioListID" checked />
		Option

			<input class="radio-input" type="radio" name="radioListID" />
			or

			<input class="textfield-input" type="text" />
			textfield label

Filters

			<input class="textfield-input" type="text" value="Filter" />
			Textfield label


text:
// Vaca - Visual Application Components Abstraction
// Copyright (c) 2005-2010 David Capello
//
// This file is distributed under the terms of the MIT license,
// please read LICENSE.txt for more information.

#ifndef VACA_LISTCOLUMN_H
#define VACA_LISTCOLUMN_H

#include "vaca/base.h"
#include "vaca/Component.h"

namespace vaca {

/**
   A column in a ListView.
*/
class VACA_DLL ListColumn : public Component
{
  friend class ListView;

  int		m_index;
  String	m_text;
  TextAlign	m_textAlign;
  int		m_width;
  ListView*	m_owner;

public:

  ListColumn(const String& text, TextAlign textAlign = TextAlign::Left);
  virtual ~ListColumn();

  ListView* getListView();

  String getText() const;
  void setText(const String& text);

  TextAlign getTextAlign() const;
  void setTextAlign(TextAlign textAlign);

  int getWidth() const;
  void setWidth(int width);
  void setPreferredWidth(bool useHeader = true);

  Rect getBounds() const;

  // int getIndex() const;
  // static ListColumn* fromIndex(HWND hwnd, int index);

private:
  void addToListView(ListView* listView);
  void removeFromListView();

};

} // namespace vaca

#endif // VACA_LISTCOLUMN_H


text:
//
// Copyright 2016, Mahbub Alam (mahbub002@gmail.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Common;
using Mark.DotNet.Data.ModelConfiguration;

namespace Mark.DotNet.Data
{
    /// <summary>
    /// Represents command context interface for ADO.NET style storage context.
    /// </summary>
    public interface IDbCommandContext : IDisposable
    {
        /// <summary>
        /// Set command parameters for each entity in the given entity collection.
        /// </summary>
        /// <param name="setAction">Action that will execute for each entity in the collection.</param>
        /// <param name="idPropertyConfig">Optional property configuration for
        /// entity id property (database generated) that will be populated.</param>
        void SetParametersForEach<TEntity>(Action<IDbParameterCollection, TEntity> setAction,
            PropertyConfiguration idPropertyConfig = null)
            where TEntity : IEntity;

        /// <summary>
        /// Get the underlying command.
        /// </summary>
        DbCommand Command
        {
            get;
        }

        /// <summary>
        /// Get command parameter collection.
        /// </summary>
        IDbParameterCollection Parameters
        {
            get;
        }

        /// <summary>
        /// Execute the command.
        /// </summary>
        /// <returns>Returns the number of rows affected.</returns>
        int Execute();

        /// <summary>
        /// Execute the command and returns a data reader.
        /// </summary>
        /// <returns>Returns a data reader.</returns>
        DbDataReader ExecuteReader();
    }
}


text:
require 'spec_helper'

RSpec.feature "Disabled booleans", type: :feature do
  scenario "Selecting all", js: true do
    project = Project.create name: 'P1', finished: true
    visit collection_edit_projects_path(ids: [project.id])

    toggle = find('.optional-attribute-container.finished .optional-boolean-toggle')
    toggle['class'].should include 'active'
    toggle.click
    find('[name="commit"]').click

    project.reload

    # Should not be changed by the click
    project.finished.should be true
  end

end


text:
#ifndef LGNCG_UTILS_H_INCLUDED
#define LGNCG_UTILS_H_INCLUDED

#include "../../legion_runtime/legion.h"

namespace lgncg {

/**
 * convenience routine to get a task's ID
 */
static inline int
getTaskID(const LegionRuntime::HighLevel::Task *task)
{
    return task->index_point.point_data[0];
}

/**
 * courtesy of some other legion code.
 */
template <unsigned DIM, typename T>
static inline bool
offsetsAreDense(const Rect<DIM> &bounds,
                const LegionRuntime::Accessor::ByteOffset *offset)
{
#ifdef LGNCG_CHECK_OFF_R_DENSE
    off_t exp_offset = sizeof(T);
    for (unsigned i = 0; i < DIM; i++) {
        bool found = false;
        for (unsigned j = 0; j < DIM; j++)
            if (offset[j].offset == exp_offset) {
                found = true;
                exp_offset *= (bounds.hi[j] - bounds.lo[j] + 1);
                break;
            }
        if (!found) return false;
    }
    return true;
#else
    (void)bounds;
    (void)offset;
    return true;
#endif
}

/**
 * courtesy of some other legion code.
 */
static inline bool
offsetMismatch(int i,
               const LegionRuntime::Accessor::ByteOffset *off1,
               const LegionRuntime::Accessor::ByteOffset *off2)
{
    while (i-- > 0) {
        if ((off1++)->offset != (off2++)->offset) return true;
    }
    return false;
}

} // end lgncg namespace

#endif


text:
       {{item.title}}

         {{subItem.title}}


text:
var assert = require('assert');
var fs = require('fs');

var Database = require('../lib/database');

try {
    fs.unlinkSync('test_db.sqlite');
} catch (e) {
}

describe('Database', function () {
    var db;

    beforeEach(function (done) {
        db = new Database({
            client: 'sqlite3',
            connection: { filename: 'test_db.sqlite' },
            pasteIdLength: 4
        });

        db.on('ready', done);
    });

    afterEach(function (done) {
        db = null;
        try {
            fs.unlinkSync('test_db.sqlite');
        } catch (e) {
        }
        done();
    });

    describe('#addPaste', function () {
        it('should add a paste', function (done) {
            var content = 'This is a test';

            db.addPaste(content, '127.0.0.1').then(function (paste) {
                assert.equal(paste.get('content'), content);
                assert.equal(paste.get('uploader_ip'), '127.0.0.1');
                done();
            });
        });
    });
});


text:
using System.IO;
using System.Text;
using NServiceBus.Persistence.Sql.ScriptBuilder;
using NUnit.Framework;
using Particular.Approvals;

[TestFixture]
public class TimeoutScriptBuilderTest
{
    [Test]
    [TestCase(BuildSqlDialect.MsSqlServer)]
    [TestCase(BuildSqlDialect.MySql)]
    [TestCase(BuildSqlDialect.Oracle)]
    [TestCase(BuildSqlDialect.PostgreSql)]
    public void BuildCreateScript(BuildSqlDialect sqlDialect)
    {
        var builder = new StringBuilder();
        using (var writer = new StringWriter(builder))
        {
            TimeoutScriptBuilder.BuildCreateScript(writer, sqlDialect);
        }
        var script = builder.ToString();
        if (sqlDialect == BuildSqlDialect.MsSqlServer)
        {
            SqlValidator.Validate(script);
        }

        Approver.Verify(script, scenario: "ForScenario." + sqlDialect);
    }

    [Test]
    [TestCase(BuildSqlDialect.MsSqlServer)]
    [TestCase(BuildSqlDialect.MySql)]
    [TestCase(BuildSqlDialect.Oracle)]
    [TestCase(BuildSqlDialect.PostgreSql)]
    public void BuildDropScript(BuildSqlDialect sqlDialect)
    {
        var builder = new StringBuilder();
        using (var writer = new StringWriter(builder))
        {
            TimeoutScriptBuilder.BuildDropScript(writer, sqlDialect);
        }
        var script = builder.ToString();
        if (sqlDialect == BuildSqlDialect.MsSqlServer)
        {
            SqlValidator.Validate(script);
        }

        Approver.Verify(script, scenario: "ForScenario." + sqlDialect);
    }
}


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <winpr/ntlm.h>

#include <winpr/crt.h>
#include <winpr/crypto.h>

/**
 * Define NTOWFv1(Password, User, Domain) as
 * 	MD4(UNICODE(Password))
 * EndDefine
 */

BOOL NTOWFv1W(LPWSTR Password, UINT32 PasswordLength, BYTE* NtHash)
{
	if (!Password || !NtHash)
		return FALSE;

	if (!winpr_Digest(WINPR_MD_MD4, (BYTE*) Password, (size_t) PasswordLength, NtHash,
	                  WINPR_MD4_DIGEST_LENGTH))
		return FALSE;

	return TRUE;
}

BOOL NTOWFv1A(LPSTR Password, UINT32 PasswordLength, BYTE* NtHash)
{
	LPWSTR PasswordW = NULL;
	BOOL result = FALSE;

	if (!NtHash)
		return FALSE;

	if (!(PasswordW = (LPWSTR) calloc(PasswordLength, 2)))
		return FALSE;

	MultiByteToWideChar(CP_ACP, 0, Password, PasswordLength, PasswordW, PasswordLength);

	if (!NTOWFv1W(PasswordW, PasswordLength * 2, NtHash))
		goto out_fail;

	result = TRUE;
out_fail:
	free(PasswordW);
	return result;
}

/**
 * Define NTOWFv2(Password, User, Domain) as
 * 	HMAC_MD5(MD4(UNICODE(Password)),
 * 		UNICODE(ConcatenationOf(UpperCase(User), Domain)))
 * EndDefine
 */

BOOL NTOWFv2W(LPWSTR Password, UINT32 PasswordLength, LPWSTR User,
              UINT32 UserLength, LPWSTR Domain, UINT32 DomainLength, BYTE* NtHash)
{
	BYTE* buffer;
	BYTE NtHashV1[16];
	BOOL result = FALSE;

	if ((!User) || (!Password) || (!NtHash))
		return FALSE;

	if (!NTOWFv1W(Password, PasswordLength, NtHashV1))
		return FALSE;

	if (!(buffer = (BYTE*) malloc(UserLength + DomainLength)))
		return FALSE;

	/* Concatenate(UpperCase(User), Domain) */
	CopyMemory(buffer, User, UserLength);
	CharUpperBuffW((LPWSTR) buffer, UserLength / 2);
	CopyMemory(&buffer[UserLength], Domain, DomainLength);

	/* Compute the HMAC-MD5 hash of the above value using the NTLMv1 hash as the key, the result is the NTLMv2 hash */
	if (!winpr_HMAC(WINPR_MD_MD5, NtHashV1, 16, buffer, UserLength + DomainLength, NtHash,
	                WINPR_MD4_DIGEST_LENGTH))
		goto out_fail;

	result = TRUE;
out_fail:
	free(buffer);
	return result;
}

BOOL NTOWFv2A(LPSTR Password, UINT32 PasswordLength, LPSTR User,
              UINT32 UserLength, LPSTR Domain, UINT32 DomainLength, BYTE* NtHash)
{
	LPWSTR UserW = NULL;
	LPWSTR DomainW = NULL;
	LPWSTR PasswordW = NULL;
	BOOL result = FALSE;

	if (!NtHash)
		return FALSE;

	UserW = (LPWSTR) calloc(UserLength, 2);
	DomainW = (LPWSTR) calloc(DomainLength, 2);
	PasswordW = (LPWSTR) calloc(PasswordLength, 2);

	if (!UserW || !DomainW || !PasswordW)
		goto out_fail;

	MultiByteToWideChar(CP_ACP, 0, User, UserLength, UserW, UserLength);
	MultiByteToWideChar(CP_ACP, 0, Domain, DomainLength, DomainW, DomainLength);
	MultiByteToWideChar(CP_ACP, 0, Password, PasswordLength, PasswordW, PasswordLength);

	if (!NTOWFv2W(PasswordW, PasswordLength * 2, UserW, UserLength * 2, DomainW, DomainLength * 2,
	              NtHash))
		goto out_fail;

	result = TRUE;
out_fail:
	free(UserW);
	free(DomainW);
	free(PasswordW);
	return result;
}

BOOL NTOWFv2FromHashW(BYTE* NtHashV1, LPWSTR User, UINT32 UserLength, LPWSTR Domain,
                      UINT32 DomainLength, BYTE* NtHash)
{
	BYTE* buffer;
	BYTE result = FALSE;

	if (!User || !NtHash)
		return FALSE;

	if (!(buffer = (BYTE*) malloc(UserLength + DomainLength)))
		return FALSE;

	/* Concatenate(UpperCase(User), Domain) */
	CopyMemory(buffer, User, UserLength);
	CharUpperBuffW((LPWSTR) buffer, UserLength / 2);

	if (DomainLength > 0)
	{
		CopyMemory(&buffer[UserLength], Domain, DomainLength);
	}

	/* Compute the HMAC-MD5 hash of the above value using the NTLMv1 hash as the key, the result is the NTLMv2 hash */
	if (!winpr_HMAC(WINPR_MD_MD5, NtHashV1, 16, buffer, UserLength + DomainLength, NtHash,
	                WINPR_MD4_DIGEST_LENGTH))
		goto out_fail;

	result = TRUE;
out_fail:
	free(buffer);
	return result;
}

BOOL NTOWFv2FromHashA(BYTE* NtHashV1, LPSTR User, UINT32 UserLength, LPSTR Domain,
                      UINT32 DomainLength, BYTE* NtHash)
{
	LPWSTR UserW = NULL;
	LPWSTR DomainW = NULL;
	BOOL result = FALSE;

	if (!NtHash)
		return FALSE;

	UserW = (LPWSTR) calloc(UserLength, 2);
	DomainW = (LPWSTR) calloc(DomainLength, 2);

	if (!UserW || !DomainW)
		goto out_fail;

	MultiByteToWideChar(CP_ACP, 0, User, UserLength, UserW, UserLength);
	MultiByteToWideChar(CP_ACP, 0, Domain, DomainLength, DomainW, DomainLength);

	if (!NTOWFv2FromHashW(NtHashV1, UserW, UserLength * 2, DomainW, DomainLength * 2, NtHash))
		goto out_fail;

	result = TRUE;
out_fail:
	free(UserW);
	free(DomainW);
	return result;
}


text:
module MiniSequel.Adapter.MySQL.Log
where
  import qualified MiniSequel.Adapter.MySQL as Adapter

  -- exec con query = do
  --   print query
  --   Adapter.exec con query
  --
  -- takeModel con model = do
  --   print model
  --   Adapter.takeModel con model


text:
'use strict'

var Atomic = require('./atomic')

// attrs:
//   - value
//   - disabled
function Datepicker (data) {
  Atomic.call(this, data)
}

Datepicker.prototype = Object.create(Atomic.prototype)

Datepicker.prototype.create = function () {
  var node = document.createElement('input')
  var uuid = Math.floor(10000000000000 * Math.random()) + Date.now()
  this.className = 'weex-ipt-' + uuid
  this.styleId = 'weex-style-' + uuid
  node.classList.add(this.className)
  node.setAttribute('type', 'date')
  node.type = 'date'
  // For the consistency of input component's width.
  // The date and time type of input will have a bigger width
  // when the 'box-sizing' is not set to 'border-box'
  node.classList.add('weex-element')
  return node
}

Datepicker.prototype.attr = {
  disabled: function (val) {
    this.node.disabled = val && val !== 'false'
                    ? true
                    : false
  }
}

module.exports = Datepicker


text:
import React from 'react';
import { TextArea as SemanticTextArea } from 'semantic-ui-react';
import type { FieldProps } from 'redux-form';
import { INPUT_TYPES } from '../constants';

type Props = {
  placeholder?: string
} & FieldProps;

const TextArea = ({
  input,
  placeholder,
  ...rest
}: Props) => (
  <SemanticTextArea
    {...input}
    {...rest}
    placeholder={placeholder}
    onChange={(e, data) => {
      input.onChange(data.value);
      if (rest.onChange) {
        rest.onChange(e, data);
      }
    }}
  />
);

TextArea.fieldType = INPUT_TYPES.TEXTAREA;

export default TextArea;


text:
define(["storymaps/utils/Helper"],
	function (Helper) {
		return function SettingsPopupTabHeader(titleContainer, contentContainer, defaultLogoURL)
		{
			var _logoInput = $(contentContainer).find("#logoInput");
			var _logoTargetInput = $(contentContainer).find("#logoTargetInput");

			var _badLogo = false;

			$(_logoInput).keydown(onLogoInputEnter);
			$(_logoInput).focusout(loadCustomLogo);
			$(_logoTargetInput).keydown(onTargetInputEnter);

			$("input[type=radio]", contentContainer).click(onLogoRadioClick);
			$("#imgLogo", contentContainer).error(onLogoLoadError);
			$("#imgLogo", contentContainer).load(onLogoLoadComplete);

			this.init = function(settings)
			{
				var logoURL = settings.logoURL;

				_logoInput.attr("disabled", "true");
				_logoTargetInput.attr("disabled", "true");

				$("input[name='optionsLogo']", $(contentContainer)).change(function () {
					var logoOption = $("input[name='optionsLogo']:checked", $(contentContainer)).val();
					if (logoOption == "none" || logoOption == "esri" ) {
						_logoInput.attr("disabled", "true");
						_logoTargetInput.attr("disabled", "true");
					}
					else {
						_logoInput.removeAttr("disabled");
						_logoTargetInput.removeAttr("disabled");
					}
				});

				$("#headerSimulator", contentContainer).css("background-color", settings.colors[0]);
				if (logoURL == null) {
					$('input[name=optionsLogo]:eq(1)', contentContainer).attr('checked', 'checked');
					_logoInput.val("");
					_logoTargetInput.val("");
				}
				else if (logoURL == defaultLogoURL) {
					$('input[name=optionsLogo]:eq(0)', contentContainer).attr('checked', 'checked');
					$("#imgLogo", contentContainer).show();
					_logoInput.val("");
					_logoTargetInput.val("");
				}
				else {
					$('input[name=optionsLogo]:eq(2)', contentContainer).attr('checked', 'checked');
					$("#imgLogo", contentContainer).attr("src", logoURL);
					$("#imgLogo", contentContainer).show();
					$("#logoInput", contentContainer).val(logoURL);
					_logoTargetInput.val(settings.logoTarget);
					_logoInput.removeAttr("disabled");
					_logoTargetInput.removeAttr("disabled");
				}

				$("#selectSocialText", contentContainer).val(settings.linkText);
				$("#selectSocialLink", contentContainer).val(settings.linkURL);

				// iPad keyboard workaround
				$("#selectSocialText", contentContainer).blur(function(){ $(window).scrollTop(0); });
				$("#selectSocialLink", contentContainer).blur(function(){ $(window).scrollTop(0); });
				$("#logoInput", contentContainer).blur(function(){ $(window).scrollTop(0); });
				_logoTargetInput.blur(function(){ $(window).scrollTop(0); });

				// Social sharing
				if ( ! APPCFG.HEADER_SOCIAL.facebook )
					$(".enableFB", contentContainer)
						.attr("disabled", "disabled")
						.parent()
						.addClass("disabled")
						.attr("title", i18n.viewer.builderHTML.settingsLogoSocialDisabled);
				else if ( ! settings.social || settings.social.facebook )
					$(".enableFB", contentContainer).prop('checked', true);

				if ( ! APPCFG.HEADER_SOCIAL.twitter )
					$(".enableTwitter", contentContainer)
						.attr("disabled", "disabled")
						.parent()
						.addClass("disabled")
						.attr("title", i18n.viewer.builderHTML.settingsLogoSocialDisabled);
				else if ( ! settings.social || settings.social.twitter )
					$(".enableTwitter", contentContainer).prop('checked', true);

				if( ! APPCFG.HEADER_SOCIAL.bitly || ! APPCFG.HEADER_SOCIAL.bitly.enable || ! APPCFG.HEADER_SOCIAL.bitly.login || ! APPCFG.HEADER_SOCIAL.bitly.key )
					$(".enableBitly", contentContainer)
						.attr("disabled", "disabled")
						.parent()
						.addClass("disabled")
						.attr("title", i18n.viewer.builderHTML.settingsLogoSocialDisabled);
				else if ( ! settings.social || settings.social.bitly )
					$(".enableBitly", contentContainer).prop('checked', true);

				updateForm();
			};

			this.show = function()
			{
				//
			};

			this.save = function()
			{
				var logoOption = $("input[name=optionsLogo]:checked", contentContainer).val();
				var logoURL;
				var logoTarget;

				if (logoOption == "none") {
					logoURL = null;
					logoTarget = "";
				}
				else if (logoOption == "esri") {
					logoURL = defaultLogoURL;
					logoTarget = "";
				}
				else {
					logoURL = _badLogo ? defaultLogoURL : $("#imgLogo",contentContainer).attr("src");
					logoTarget = _logoTargetInput.val();
				}

				// Basic XSS check
				var linkText = $("#selectSocialText", contentContainer).val() || '';
				linkText = linkText.replace(/<\/?script>/g,'');

				var linkURL = $("#selectSocialLink", contentContainer).val() || '';
				linkURL = linkURL.replace(/<\/?script>/g,'');

				return {
					logoURL: logoURL,
					logoTarget: Helper.prependURLHTTP(logoTarget),
					linkText: linkText,
					linkURL: Helper.prependURLHTTP(linkURL),
					social: {
						facebook: $(".enableFB").prop('checked'),
						twitter: $(".enableTwitter").prop('checked'),
						bitly: $(".enableBitly").prop('checked')
					}
				};
			};

			function onLogoRadioClick()
			{
				updateForm();
			}

			function onLogoLoadComplete()
			{
			}

			function onLogoLoadError()
			{
				_badLogo = true;
				$("#imgLogo", contentContainer).hide();
			}

			function onLogoInputEnter(event)
			{
				if (event.keyCode == 13) {
					_badLogo = false;
					loadCustomLogo();
					return false;
				}
				// Fix for webkit browser - if the text exceeded the input size, after hitting backspace the modal shifted
				// Focusing the field after backspace the field is the only fix found
				else if (event.keyCode == 8 ) {
					$("#logoTargetInput").focus();
					$("#logoInput").focus();
				}
			}

			function loadCustomLogo()
			{
				var logoUrl = $.trim($("#logoInput", contentContainer).val());
				if ( logoUrl ) {
					$("#imgLogo", contentContainer).attr("src", logoUrl);
					$("#imgLogo", contentContainer).show();
				}
			}

			function onTargetInputEnter(event)
			{
				// Fix for webkit browser - if the text exceeded the input size, after hitting backspace the modal shifted
				// Focusing the field after backspace the field is the only fix found
				if (event.keyCode == 8 ) {
					$("#logoInput").focus();
					$("#logoTargetInput").focus();
				}
			}

			function updateForm()
			{
				var logoOption = $("input[name=optionsLogo]:checked", contentContainer).val();

				$("#imgLogo", contentContainer).hide();

				if (logoOption == "custom") {
					loadCustomLogo();
				}
				else if (logoOption == "esri") {
					$("#imgLogo", contentContainer).attr("src", defaultLogoURL);
					$("#imgLogo", contentContainer).show();
				}
			}

			this.initLocalization = function()
			{
				$(titleContainer).html(i18n.viewer.builderHTML.settingsTabLogo);

				$(contentContainer).find('p').eq(0).html(i18n.viewer.builderHTML.settingsLogoExplain);
				$(contentContainer).find('.logoText').eq(0).html(i18n.viewer.builderHTML.settingsLogoEsri);
				$(contentContainer).find('.logoText').eq(1).html(i18n.viewer.builderHTML.settingsLogoNone);
				$(contentContainer).find('.logoText').eq(2).html(i18n.viewer.builderHTML.settingsLogoCustom);
				$(contentContainer).find('#logoInput').attr("placeholder", i18n.viewer.builderHTML.settingsLogoCustomPlaceholder);
				$(contentContainer).find('#logoTargetInput').attr("placeholder", i18n.viewer.builderHTML.settingsLogoCustomTargetPlaceholder);
				$(contentContainer).find('p').eq(1).html(i18n.viewer.builderHTML.settingsLogoSocialExplain);
				$(contentContainer).find('.control-label[for=selectSocialText]').html(i18n.viewer.builderHTML.settingsLogoSocialText + ":");
				$(contentContainer).find('.control-label[for=selectSocialLink]').html(i18n.viewer.builderHTML.settingsLogoSocialLink + ":");
			};
		};
	}
);


text:
package org.elasticsearch.search.aggregations.bucket.histogram;

import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.search.ScoreMode;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CollectionUtil;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Rounding;
import org.elasticsearch.common.lease.Releasables;
import org.elasticsearch.common.util.LongHash;
import org.elasticsearch.index.fielddata.SortedBinaryDocValues;
import org.elasticsearch.index.mapper.RangeFieldMapper;
import org.elasticsearch.index.mapper.RangeType;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.aggregations.Aggregator;
import org.elasticsearch.search.aggregations.AggregatorFactories;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.InternalOrder;
import org.elasticsearch.search.aggregations.LeafBucketCollector;
import org.elasticsearch.search.aggregations.LeafBucketCollectorBase;
import org.elasticsearch.search.aggregations.bucket.BucketsAggregator;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator;
import org.elasticsearch.search.aggregations.support.ValuesSource;
import org.elasticsearch.search.internal.SearchContext;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * An aggregator for date values. Every date is rounded down using a configured
 * {@link Rounding}.
 *
 * @see Rounding
 */
class DateRangeHistogramAggregator extends BucketsAggregator {

    private final ValuesSource.Range valuesSource;
    private final DocValueFormat formatter;
    private final Rounding rounding;
    private final Rounding shardRounding;
    private final BucketOrder order;
    private final boolean keyed;

    private final long minDocCount;
    private final ExtendedBounds extendedBounds;

    private final LongHash bucketOrds;
    private long offset;

    DateRangeHistogramAggregator(String name, AggregatorFactories factories, Rounding rounding, Rounding shardRounding,
                                 long offset, BucketOrder order, boolean keyed,
                                 long minDocCount, @Nullable ExtendedBounds extendedBounds, @Nullable ValuesSource.Range valuesSource,
                                 DocValueFormat formatter, SearchContext aggregationContext,
                                 Aggregator parent, List<PipelineAggregator> pipelineAggregators,
                                 Map<String, Object> metaData) throws IOException {

        super(name, factories, aggregationContext, parent, pipelineAggregators, metaData);
        this.rounding = rounding;
        this.shardRounding = shardRounding;
        this.offset = offset;
        this.order = InternalOrder.validate(order, this);
        this.keyed = keyed;
        this.minDocCount = minDocCount;
        this.extendedBounds = extendedBounds;
        this.valuesSource = valuesSource;
        this.formatter = formatter;

        bucketOrds = new LongHash(1, aggregationContext.bigArrays());
    }

    @Override
    public ScoreMode scoreMode() {
        if (valuesSource != null && valuesSource.needsScores()) {
            return ScoreMode.COMPLETE;
        }
        return super.scoreMode();
    }

    @Override
    public LeafBucketCollector getLeafCollector(LeafReaderContext ctx,
            final LeafBucketCollector sub) throws IOException {
        if (valuesSource == null) {
            return LeafBucketCollector.NO_OP_COLLECTOR;
        }
        final SortedBinaryDocValues values = valuesSource.bytesValues(ctx);
        final RangeType rangeType = valuesSource.rangeType();
        return new LeafBucketCollectorBase(sub, values) {
            @Override
            public void collect(int doc, long bucket) throws IOException {
                assert bucket == 0;
                if (values.advanceExact(doc)) {
                    // Is it possible for valuesCount to be > 1 here? Multiple ranges are encoded into the same BytesRef in the binary doc
                    // values, so it isn't clear what we'd be iterating over.
                    final int valuesCount = values.docValueCount();
                    assert valuesCount == 1 : "Value count for ranges should always be 1";
                    long previousKey = Long.MIN_VALUE;

                    for (int i = 0; i < valuesCount; i++) {
                        BytesRef encodedRanges = values.nextValue();
                        List<RangeFieldMapper.Range> ranges = rangeType.decodeRanges(encodedRanges);
                        long previousFrom = Long.MIN_VALUE;
                        for (RangeFieldMapper.Range range : ranges) {
                            final Long from = (Long) range.getFrom();
                            // The encoding should ensure that this assert is always true.
                            assert from >= previousFrom : "Start of range not >= previous start";
                            final Long to = (Long) range.getTo();
                            final long startKey = offsetAwareRounding(shardRounding, from, offset);
                            final long endKey = offsetAwareRounding(shardRounding, to, offset);
                            for (long  key = startKey > previousKey ? startKey : previousKey; key <= endKey;
                                 key = shardRounding.nextRoundingValue(key)) {
                                if (key == previousKey) {
                                    continue;
                                }
                                // Bucket collection identical to NumericHistogramAggregator, could be refactored
                                long bucketOrd = bucketOrds.add(key);
                                if (bucketOrd < 0) { // already seen
                                    bucketOrd = -1 - bucketOrd;
                                    collectExistingBucket(sub, doc, bucketOrd);
                                } else {
                                    collectBucket(sub, doc, bucketOrd);
                                }
                            }
                            if (endKey > previousKey) {
                                previousKey = endKey;
                            }
                        }

                    }
                }
            }
        };
    }

    private long offsetAwareRounding(Rounding rounding, long value, long offset) {
        return rounding.round(value - offset) + offset;
    }

    @Override
    public InternalAggregation buildAggregation(long owningBucketOrdinal) throws IOException {
        assert owningBucketOrdinal == 0;
        consumeBucketsAndMaybeBreak((int) bucketOrds.size());

        List<InternalDateHistogram.Bucket> buckets = new ArrayList<>((int) bucketOrds.size());
        for (long i = 0; i < bucketOrds.size(); i++) {
            buckets.add(new InternalDateHistogram.Bucket(bucketOrds.get(i), bucketDocCount(i), keyed, formatter, bucketAggregations(i)));
        }

        // the contract of the histogram aggregation is that shards must return buckets ordered by key in ascending order
        CollectionUtil.introSort(buckets, BucketOrder.key(true).comparator(this));

        // value source will be null for unmapped fields
        // Important: use `rounding` here, not `shardRounding`
        InternalDateHistogram.EmptyBucketInfo emptyBucketInfo = minDocCount == 0
                ? new InternalDateHistogram.EmptyBucketInfo(rounding, buildEmptySubAggregations(), extendedBounds)
                : null;
        return new InternalDateHistogram(name, buckets, order, minDocCount, offset, emptyBucketInfo, formatter, keyed,
                pipelineAggregators(), metaData());
    }

    @Override
    public InternalAggregation buildEmptyAggregation() {
        InternalDateHistogram.EmptyBucketInfo emptyBucketInfo = minDocCount == 0
                ? new InternalDateHistogram.EmptyBucketInfo(rounding, buildEmptySubAggregations(), extendedBounds)
                : null;
        return new InternalDateHistogram(name, Collections.emptyList(), order, minDocCount, offset, emptyBucketInfo, formatter, keyed,
                pipelineAggregators(), metaData());
    }

    @Override
    public void doClose() {
        Releasables.close(bucketOrds);
    }
}


text:
module Mongoid
  module Contextual
    module Aggregable
      # Contains behaviour for aggregating values in Mongo.
      module Mongo

        # Get all the aggregate values for the provided field.
        #
        # @example Get all the aggregate values.
        #   aggregable.aggregates(:likes)
        #
        # @param [ String, Symbol ] field The field name.
        #
        # @return [ Hash ] The aggregate values in the form:
        #   {
        #     "count" => 2.0,
        #     "max" => 1000.0,
        #     "min" => 500.0,
        #     "sum" => 1500.0,
        #     "avg" => 750.0
        #   }
        #
        # @since 3.0.0
        def aggregates(field)
          if query.count > 0
            map_reduce(mapper(field), reducer).
              out(inline: 1).finalize(finalizer).first["value"]
          else
            { "count" => 0 }
          end
        end

        # Get the average value of the provided field.
        #
        # @example Get the average of a single field.
        #   aggregable.avg(:likes)
        #
        # @param [ Symbol ] field The field to average.
        #
        # @return [ Float ] The average.
        #
        # @since 3.0.0
        def avg(field)
          aggregates(field)["avg"]
        end

        # Get the max value of the provided field. If provided a block, will
        # return the Document with the greatest value for the field, in
        # accordance with Ruby's enumerable API.
        #
        # @example Get the max of a single field.
        #   aggregable.max(:likes)
        #
        # @example Get the document with the max value.
        #   aggregable.max do |a, b|
        #     a.likes <=> b.likes
        #   end
        #
        # @param [ Symbol ] field The field to max.
        #
        # @return [ Float, Document ] The max value or document with the max
        #   value.
        #
        # @since 3.0.0
        def max(field = nil)
          block_given? ? super() : aggregates(field)["max"]
        end

        # Get the min value of the provided field. If provided a block, will
        # return the Document with the smallest value for the field, in
        # accordance with Ruby's enumerable API.
        #
        # @example Get the min of a single field.
        #   aggregable.min(:likes)
        #
        # @example Get the document with the min value.
        #   aggregable.min do |a, b|
        #     a.likes <=> b.likes
        #   end
        #
        # @param [ Symbol ] field The field to min.
        #
        # @return [ Float, Document ] The min value or document with the min
        #   value.
        #
        # @since 3.0.0
        def min(field = nil)
          block_given? ? super() : aggregates(field)["min"]
        end

        # Get the sum value of the provided field. If provided a block, will
        # return the sum in accordance with Ruby's enumerable API.
        #
        # @example Get the sum of a single field.
        #   aggregable.sum(:likes)
        #
        # @example Get the sum for the provided block.
        #   aggregable.sum(&:likes)
        #
        # @param [ Symbol ] field The field to sum.
        #
        # @return [ Float ] The sum value.
        #
        # @since 3.0.0
        def sum(field = nil)
          block_given? ? super() : aggregates(field)["sum"] || 0
        end

        private

        # Get the finalize function.
        #
        # @api private
        #
        # @example Get the finalize function.
        #   aggregable.finalizer
        #
        # @return [ String ] The finalize JS function.
        #
        # @since 3.0.0
        def finalizer
          %Q{
          function(key, agg) {
            agg.avg = agg.sum / agg.count;
            return agg;
          }}
        end

        # Get the map function for the provided field.
        #
        # @api private
        #
        # @example Get the map function.
        #   aggregable.mapper(:likes)
        #
        # @param [ String, Symbol ] field The name of the field.
        #
        # @return [ String ] The map JS function.
        #
        # @since 3.0.0
        def mapper(field)
          %Q{
          function() {
            var agg = {
              count: 1,
              max: this.#{field},
              min: this.#{field},
              sum: this.#{field}
            };
            emit("#{field}", agg);
          }}
        end

        # Get the reduce function for the provided field.
        #
        # @api private
        #
        # @example Get the reduce function.
        #   aggregable.reducer(:likes)
        #
        # @return [ String ] The reduce JS function.
        #
        # @since 3.0.0
        def reducer
          %Q{
          function(key, values) {
            var agg = { count: 0, max: null, min: null, sum: 0 };
            values.forEach(function(val) {
              if (val.max !== null) {
                if (agg.max == null || val.max > agg.max) agg.max = val.max;
                if (agg.min == null || val.max < agg.min) agg.min = val.max;
                agg.sum += val.sum;
              }
              agg.count += val.count;
            });
            return agg;
          }}
        end
      end
    end
  end
end


text:
<marquee> <blink>TOKEN</blink> RUN FOR THE <blink>WORLD</blink></marquee>
<marquee>  TOKEN <blink>RUN</blink> FOR <blink>THE</blink> WORLD</marquee>
<marquee>   TOKEN RUN <blink>FOR</blink> THE WORLD</marquee>
<marquee>    TOKEN <blink>RUN</blink> FOR <blink>THE</blink> WORLD</marquee>
<marquee>     <blink>TOKEN</blink> RUN FOR THE <blink>WORLD</blink></marquee>


text:
package skype.utils;

import java.util.LinkedList;

import com.skype.ChatMessage;

//The Class Producer. This class is here only for completeness to producer-consumer
// design. It is useless for the current bot design but future iteration may use it.
/**
 * @author Thanasis Argyroudis
 * @since 1.0
 */
public class Producer extends Thread {

	/** The producer fills that list-buffer. */
	private final LinkedList<Pair<ChatMessage, Long>> buffer;

	public Producer(LinkedList<Pair<ChatMessage, Long>> buffer) {
		setName("Producer");
		this.buffer = buffer;
	}

	public void addMessageAndNotifyConsumer(ChatMessage msg) {
		Pair<ChatMessage, Long> pair = new Pair<ChatMessage, Long>(msg, System.currentTimeMillis());
		buffer.add(pair);
		synchronized (buffer) {
			buffer.notify();
		}
	}

}


text:
package server

import (
	"fmt"
	"net"
)

func SetTcpMD5SigSockopts(l *net.TCPListener, address string, key string) error {
	return fmt.Errorf("md5 not supported")
}

func SetTcpTTLSockopts(conn *net.TCPConn, ttl int) error {
	return fmt.Errorf("setting ttl is not supported")
}

func DialTCPTimeoutWithMD5Sig(host string, port int, localAddr, key string, msec int) (*net.TCPConn, error) {
	return nil, fmt.Errorf("md5 active connection unsupported")
}


text:
<?php

// Build the Jetpack admin menu as a whole
class Jetpack_Admin {

	/**
	 * @var Jetpack_Admin
	 **/
	private static $instance = null;

	/**
	 * @var Jetpack
	 **/
	private $jetpack;

	static function init() {
		if ( is_null( self::$instance ) ) {
			self::$instance = new Jetpack_Admin;
		}
		return self::$instance;
	}

	private function __construct() {
		$this->jetpack = Jetpack::init();

		jetpack_require_lib( 'admin-pages/class.jetpack-landing-page' );
		$this->landing_page = new Jetpack_Landing_Page;

		jetpack_require_lib( 'admin-pages/class.jetpack-settings-page' );
		$this->settings_page = new Jetpack_Settings_Page;

		jetpack_require_lib( 'admin-pages/class.jetpack-my-jetpack-page' );
		$this->my_jetpack_page = new Jetpack_My_Jetpack_Page;

		if ( isset( $_POST['jetpack-set-master-user'] ) ) {
			add_action( 'init', array( $this->my_jetpack_page, 'jetpack_my_jetpack_change_user' ) );
		}

		// Add hooks for admin menus
		add_action( 'admin_menu',                    array( $this->landing_page, 'add_actions' ), 998 );
		add_action( 'jetpack_admin_menu',            array( $this, 'admin_menu_debugger' ) );
		add_action( 'jetpack_admin_menu',            array( $this->settings_page, 'add_actions' ) );
		add_action( 'jetpack_admin_menu',            array( $this->my_jetpack_page, 'add_actions' ) );

		// Add redirect to current page for activation/deactivation of modules
		add_action( 'jetpack_pre_activate_module',   array( $this, 'fix_redirect' ), 10, 2 );
		add_action( 'jetpack_pre_deactivate_module', array( $this, 'fix_redirect' ) );

		// Add module bulk actions handler
		add_action( 'jetpack_unrecognized_action',   array( $this, 'handle_unrecognized_action' ) );
	}

	static function sort_requires_connection_last( $module1, $module2 ) {
		if ( $module1['requires_connection'] == $module2['requires_connection'] ) {
			return 0;
		} elseif ( $module1['requires_connection'] ) {
			return 1;
		} elseif ( $module2['requires_connection'] ) {
			return -1;
		}

		return 0;
	}

	// Produce JS understandable objects of modules containing information for
	// presentation like description, name, configuration url, etc.
	function get_modules() {
		include_once( JETPACK__PLUGIN_DIR . 'modules/module-info.php' );
		$available_modules = $this->jetpack->get_available_modules();
		$active_modules    = $this->jetpack->get_active_modules();
		$modules           = array();
		$jetpack_active = Jetpack::is_active() || Jetpack::is_development_mode();
		foreach ( $available_modules as $module ) {
			if ( $module_array = $this->jetpack->get_module( $module ) ) {
				/**
				 * Filters each module's short description.
				 *
				 * @since 3.0.0
				 *
				 * @param string $module_array['description'] Module description.
				 * @param string $module Module slug.
				 */
				$short_desc = apply_filters( 'jetpack_short_module_description', $module_array['description'], $module );
				// Fix: correct multibyte strings truncate with checking for mbstring extension
				$short_desc_trunc = ( function_exists( 'mb_strlen' ) )
							? ( ( mb_strlen( $short_desc ) > 143 )
								? mb_substr( $short_desc, 0, 140 ) . '...'
								: $short_desc )
							: ( ( strlen( $short_desc ) > 143 )
								? substr( $short_desc, 0, 140 ) . '...'
								: $short_desc );

				$module_array['module']            = $module;
				$module_array['activated']         = ( $jetpack_active ? in_array( $module, $active_modules ) : false );
				$module_array['deactivate_nonce']  = wp_create_nonce( 'jetpack_deactivate-' . $module );
				$module_array['activate_nonce']    = wp_create_nonce( 'jetpack_activate-' . $module );
				$module_array['available']         = self::is_module_available( $module_array );
				$module_array['short_description'] = $short_desc_trunc;
				$module_array['configure_url']     = Jetpack::module_configuration_url( $module );

				ob_start();
				/**
				 * Allow the display of a "Learn More" button.
				 * The dynamic part of the action, $module, is the module slug.
				 *
				 * @since 3.0.0
				 */
				do_action( 'jetpack_learn_more_button_' . $module );
				$module_array['learn_more_button'] = ob_get_clean();

				ob_start();
				/**
				 * Allow the display of information text when Jetpack is connected to WordPress.com.
				 * The dynamic part of the action, $module, is the module slug.
				 *
				 * @since 3.0.0
				 */
				do_action( 'jetpack_module_more_info_' . $module );

				/**
				* Filter the long description of a module.
	 			*
	 			* @since 3.5.0
	 			*
	 			* @param string ob_get_clean() The module long description.
				* @param string $module The module name.
	 			*/
				$module_array['long_description'] = apply_filters( 'jetpack_long_module_description', ob_get_clean(), $module );

				ob_start();
				/**
				 * Filter the search terms for a module
				 *
				 * Search terms are typically added to the module headers, under "Additional Search Queries".
				 *
				 * Use syntax:
				 * function jetpack_$module_search_terms( $terms ) {
				 *  $terms = _x( 'term 1, term 2', 'search terms', 'jetpack' );
				 *  return $terms;
				 * }
				 * add_filter( 'jetpack_search_terms_$module', 'jetpack_$module_search_terms' );
				 *
				 * @since 3.5.0
				 *
				 * @param string The search terms (comma separated).
				 */
				echo apply_filters( 'jetpack_search_terms_' . $module, $module_array['additional_search_queries'] );
				$module_array['search_terms'] = ob_get_clean();

				$module_array['configurable'] = false;
				if (
					current_user_can( 'manage_options' ) &&
					/**
					 * Allow the display of a configuration link in the Jetpack Settings screen.
					 *
					 * @since 3.0.0
					 *
					 * @param string $module Module name.
					 * @param bool false Should the Configure module link be displayed? Default to false.
					 */
					apply_filters( 'jetpack_module_configurable_' . $module, false )
				) {
					$module_array['configurable'] = sprintf( '%2$s', esc_url( Jetpack::module_configuration_url( $module ) ), __( 'Configure', 'jetpack' ) );
				}

				$modules[ $module ] = $module_array;
			}
		}

		uasort( $modules, array( $this->jetpack, 'sort_modules' ) );

		if ( ! Jetpack::is_active() ) {
			uasort( $modules, array( __CLASS__, 'sort_requires_connection_last' ) );
		}

		return $modules;
	}

	static function is_module_available( $module ) {
		if ( ! is_array( $module ) || empty( $module ) )
			return false;

		/**
		 * We never want to show VaultPress as activatable through Jetpack.
		 */
		if ( 'vaultpress' === $module['module'] ) {
			return false;
		}

		if ( Jetpack::is_development_mode() ) {
			return ! ( $module['requires_connection'] );
		} else {
			return Jetpack::is_active();
		}
	}

	function handle_unrecognized_action( $action ) {
		switch( $action ) {
			case 'bulk-activate' :
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
					break;
				}

				$modules = (array) $_GET['modules'];
				$modules = array_map( 'sanitize_key', $modules );
				check_admin_referer( 'bulk-jetpack_page_jetpack_modules' );
				foreach( $modules as $module ) {
					Jetpack::log( 'activate', $module );
					Jetpack::activate_module( $module, false );
				}
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
				wp_safe_redirect( wp_get_referer() );
				exit;
			case 'bulk-deactivate' :
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
					break;
				}

				$modules = (array) $_GET['modules'];
				$modules = array_map( 'sanitize_key', $modules );
				check_admin_referer( 'bulk-jetpack_page_jetpack_modules' );
				foreach ( $modules as $module ) {
					Jetpack::log( 'deactivate', $module );
					Jetpack::deactivate_module( $module );
					Jetpack::state( 'message', 'module_deactivated' );
				}
				Jetpack::state( 'module', $modules );
				wp_safe_redirect( wp_get_referer() );
				exit;
			default:
				return;
		}
	}

	function fix_redirect( $module, $redirect = true ) {
		if ( ! $redirect ) {
			return;
		}
		if ( wp_get_referer() ) {
			add_filter( 'wp_redirect', 'wp_get_referer' );
		}
	}

	function admin_menu_debugger() {
		$debugger_hook = add_submenu_page( null, __( 'Jetpack Debugging Center', 'jetpack' ), '', 'manage_options', 'jetpack-debugger', array( $this, 'debugger_page' ) );
		add_action( "admin_head-$debugger_hook", array( 'Jetpack_Debugger', 'jetpack_debug_admin_head' ) );
	}

	function debugger_page() {
		nocache_headers();
		if ( ! current_user_can( 'manage_options' ) ) {
			die( '-1' );
		}
		Jetpack_Debugger::jetpack_debug_display_handler();
	}
}
Jetpack_Admin::init();


text:
<Alloy>
	<NavigationGroup id="nav" platform="ios">
    	<Window id="win2" title="SHOP LIST">
		    <View id="view1" backgroundColor="#ffffff" >
				<ActivityIndicator id="activityIndicator" message="Loading ..."/>
				<TableView id="table" onClick="openPage">
				</TableView>
		    </View>
		</Window>
	</NavigationGroup>
	<View id="view1" backgroundColor="#ffffff" platform="android" >
		<ActivityIndicator id="activityIndicator" message="Loading ..."/>
		<TableView id="table" onClick="openPage">
		</TableView>
	</View>
</Alloy>


text: export { default } from './SlackOriginalWordmark'


text:
package com.thecoffeine.virtuoso.music.model.repository;

import com.thecoffeine.virtuoso.music.model.entity.Collection;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * Repository for Song Collection.
 *
 * @version 1.0
 */
public interface CollectionRepository extends JpaRepository<Collection, Long> {

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.symboltable</title>
<meta name="date" content="2014-08-31">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package org.symboltable

Class Summary

Class
Description

AdjacencyList

An adjacency list of strings, implemented with a linked list.

BFSearcher

Runs Breadth First Search (BFS) algorithm from source sourceVertex on
 a graph graph.

Edge

Java class containing methods to draw edges between two nodes.

Graph

Undirected graph data type implemented using a symbol table of vertices,
 where each vertex contains a list of its neighbors.

MetroStation

Java class to construct details of Metro stations.

MetroSystem

Java class to create a model of the DC Metro System.

Node

Java class for nodes in a simple polygon.

Queue

A queue, implemented using a linked list.

SymbolTable

Symbol table implementation using Java's HashMap library.

Track

Stations along a rail track in the Washington DC Metro.

Vector

Java class to construct two-dimensional vectors.

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
using UnityEditor;
using UnityEngine;
using System.Collections;
#if UNITY_5
public class GUIHierarchy : BaseHierarchySort
{
	//public override bool ShouldDisplay(GameObject obj) { return obj.layer == LayerMask.NameToLayer("UI"); }
}
#endif


text:
layout: story
---

{{ page.title }}

<time datetime="{{ page.date | date_to_xmlschema }}" itemprop="datePublished">{{ page.date | date: "%b %-d, %Y" }}</time>{% if page.author %} • {{ page.author }}{% endif %}

    {{ content }}


text:
<!DOCTYPE HTML>

	    <title>Example of a simple Facebook integration with Spring Security</title>
	    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

	    <meta name="_csrf" th:content="${_csrf.token}" />
		<meta name="_csrf_header" th:content="${_csrf.headerName}"/>

Spring security example

This illustrates, in the most basic way, how to attach a simple facebook login to your spring security application.

You can read more at my blog.

You are currently not logged in.

You just logged in, . Great job!

	    <form id="facebook-login"  action="/connect/facebook" method="POST" sec:authorize="isAnonymous()">
			<input type="hidden" name="scope" value="public_profile,email" />
			<input type="hidden" name="_csrf" th:value="${_csrf.token}" />
			<button type="submit">Log me in with facebook</button>
		</form>

		 <form id="facebook-logout" action="/userlogout" method="POST" sec:authorize="isAuthenticated()">
			<input type="hidden" name="_csrf" th:value="${_csrf.token}" />
			<button type="submit">Log me out</button>
		</form>


text:
package com.alwalker.mllp_server.unit_tests.helper_classes;

import com.alwalker.mllp_server.ModifyServerListener;
import com.alwalker.mllp_server.ServerConfig;

public class TestModifyServerListener implements ModifyServerListener {

    private boolean wasCalled = false;

    public boolean getWasCalled() {
        return this.wasCalled;
    }

    public void onModify(ServerConfig config) {
        wasCalled = true;
    }
}


text:
package aot.storage;

/**
 * @author Dmitry Kotlyarov
 * @since 1.0
 */
public class ListStorageException extends StorageException {
    private static final long serialVersionUID = 1L;

    public ListStorageException(String url) {
        super(url);
    }

    public ListStorageException(String url, String message) {
        super(url, message);
    }

    public ListStorageException(String url, String message, Throwable cause) {
        super(url, message, cause);
    }

    public ListStorageException(String url, Throwable cause) {
        super(url, cause);
    }

    public ListStorageException(String url, String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(url, message, cause, enableSuppression, writableStackTrace);
    }
}


text:
<?php

/**
 * This is the model class for table "{{city}}".
 *
 * The followings are the available columns in table '{{city}}':
 * @property integer $id
 * @property string $name
 * @property integer $country_id
 */
class City extends yupe\models\YModel
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'city';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('name, country_id,latitude, longitude', 'required'),
			array('country_id,status', 'numerical', 'integerOnly'=>true),
                        array('lang', 'length', 'max' => 2),
                        array('lang', 'default', 'value' => Yii::app()->sourceLanguage),
                        array('lang', 'in', 'range' => array_keys(Yii::app()->getModule('yupe')->getLanguagesList())),
			array('id, name, country_id, lang, status,latitude, longitude,created_time, updated_time', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
                    'country' => array(self::BELONGS_TO, 'Country', 'country_id')
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'name' => 'Название',
			'country_id' => 'Страна',
                        'alias'             => 'Алиас',
                        'lang'          => 'Язык',
                        'status'    =>'Статус',
                        'latitude' => 'Широта',
                        'longitude' => 'Долгота'
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('country_id',$this->country_id);
                $criteria->compare('alias',$this->alias,true);
                $criteria->compare('lang',$this->lang,true);
                $criteria->compare('longitude',$this->longitude,true);
                $criteria->compare('latitude',$this->latitude,true);
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return City the static model class
	 */

        public function language($lang)
    {
        $this->getDbCriteria()->mergeWith(array(
            'condition' => 'lang = :lang',
            'params'    => array(':lang' => $lang),
        ));
        return $this;
    }

    public function beforeValidate()
    {
        if (!$this->alias) {
            $this->alias = yupe\helpers\YText::translit($this->name);
        }

        if(!$this->lang) {
            $this->lang = Yii::app()->language;
        }

        if ($this->isNewRecord):
            $this->created_time = date("Y-m-d H:i:s");
        endif;

        $this->updated_time = date("Y-m-d H:i:s");

        return parent::beforeValidate();
    }

    public function getFlag()
    {
        return yupe\helpers\YText::langToflag($this->lang);
    }

	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

        public function getCountriesList($lang=null){
            if (!trim($lang)):
                $lang = 'ru';
            endif;
            return Chtml::listData(Country::model()->findAll("status = '1' and lang = :lang",array(':lang'=>$lang)),'id', 'name');

        }

        public function getCitiesList($country){
            return  CHtml::listData(City::model()->findAll('country_id = :country',[':country'=>$country]),'id','name');
        }

           public function getCitiesByCountry(){
            $categories = Country::model()->findAll();
            $main_cats = [];
            foreach ($categories as $category):
                $childs = City::model()->findAll("country_id = :parent",[':parent'=>$category->id]);
                if ($childs):
                    $child_cats = [];
                    foreach ($childs as $child):
                        $child_cats[$child->id] = $child->name;
                    endforeach;
                    $main_cats[$category->name] = $child_cats;
                endif;
            endforeach;

            return $main_cats;
        }
}


text:
<?xml version="1.0" encoding="UTF-8"?><module codename="org.netbeans.modules.lexer/2">
    <module_version install_time="1370463189545" last="true" origin="installer" specification_version="1.49.3.1">
        <file crc="3425354387" name="config/Modules/org-netbeans-modules-lexer.xml"/>
        <file crc="1375543283" name="modules/locale/org-netbeans-modules-lexer_ja.jar"/>
        <file crc="3409272780" name="modules/locale/org-netbeans-modules-lexer_pt_BR.jar"/>
        <file crc="3987708646" name="modules/locale/org-netbeans-modules-lexer_ru.jar"/>
        <file crc="3221434885" name="modules/locale/org-netbeans-modules-lexer_zh_CN.jar"/>
        <file crc="667571989" name="modules/org-netbeans-modules-lexer.jar"/>
    </module_version>
</module>


text:
/* $Id: Matching.cpp $ */
/** @file
 *
 * Definition of template classes that provide simple API to
 * do matching between values and value filters constructed from strings.
 */

/*
 * Copyright (C) 2006-2011 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 */

#include "Matching.h"

#include "Logging.h"

#include <stdlib.h>

#include <iprt/err.h>

namespace matching
{

// static
void ParsedIntervalFilter_base::parse (const char *aFilter,
                                       ParsedIntervalFilter_base *that)
{
    // initially null and valid
    that->mNull = true;
    that->mValid = true;
    that->mErrorPosition = 0;

    if (!aFilter || strncmp(aFilter, RT_STR_TUPLE("int:")) != 0)
        return;

    that->mNull = false;

    size_t len = strlen (aFilter);

    Mode mode = Single; // what's expected next
    size_t start = 4, end = 4;
    size_t err = 0; // less than 4 indicates success

    do
    {
        end = strcspn(aFilter + start, ",-");
        end += start;

        char delim = aFilter[end];

        if (delim == '-')
        {
            if (mode == End)
            {
                err = end;
                break;
            }
            else
                mode = Start;
        }

        // skip spaces around numbers
        size_t s = start;
        while (s < end && aFilter[s] == ' ') ++s;
        size_t e = end - 1;
        while (e > s && aFilter[e] == ' ') --e;
        ++e;

        that->parseValue(aFilter, s, e, mode);
        if (!that->mValid)
            return;

        if (mode == Start)
            mode = End;
        else if (mode == End)
            mode = Single;

        start = end + 1;
    }
    while (start <= len);

    if (err >= 4)
    {
        that->mValid = false;
        that->mErrorPosition = err;
    }
}

// static
size_t ParsedIntervalFilter_base::parseValue (
    const char *aFilter, size_t aStart, size_t aEnd,
    bool aIsSigned, const Limits &aLimits,
    Widest &val)
{
    char *endptr = NULL;

    int vrc = 0;
    if (aIsSigned)
        vrc = RTStrToInt64Ex(aFilter + aStart, &endptr, 0, &val.ll);
    else
        vrc = RTStrToUInt64Ex(aFilter + aStart, &endptr, 0, &val.ull);

    AssertReturn(endptr, 0);

    size_t parsed = endptr - aFilter;

    // return parsed if not able to parse to the end
    if (parsed != aEnd)
        return parsed;

    // return aStart if out if range
    if (vrc == VWRN_NUMBER_TOO_BIG ||
        (aIsSigned &&
         (val.ll < aLimits.min.ll ||
          val.ll > aLimits.max.ll)) ||
        (!aIsSigned &&
         (val.ull < aLimits.min.ull ||
          val.ull > aLimits.max.ull)))
        return aStart;

    return parsed;
}

void ParsedBoolFilter::parse (const Bstr &aFilter)
{
    mNull = false;
    mValid = true;
    mErrorPosition = 0;

    if (aFilter.isEmpty())
    {
        mValueAny = true;
        mValue = false;
    }
    else
    {
        mValueAny = false;
        if (aFilter == L"true" || aFilter == L"yes" || aFilter == L"1")
            mValue = true;
        else
        if (aFilter == L"false" || aFilter == L"no" || aFilter == L"0")
            mValue = false;
        else
            mValid = false;
    }
}

void ParsedRegexpFilter_base::parse (const Bstr &aFilter)
{
    /// @todo (dmik) parse "rx:<regexp>" string
    //  note, that min/max checks must not be done, when the string
    //  begins with "rx:". These limits are for exact matching only!

    // empty or null string means any match (see #isMatch() below),
    // so we don't apply Min/Max restrictions in this case

    if (!aFilter.isEmpty())
    {
        size_t len = aFilter.length();

        if (mMinLen > 0 && len < mMinLen)
        {
            mNull = mValid = false;
            mErrorPosition = len;
            return;
        }

        if (mMaxLen > 0 && len > mMaxLen)
        {
            mNull = mValid = false;
            mErrorPosition = mMaxLen;
            return;
        }
    }

    mSimple = aFilter;
    mNull = false;
    mValid = true;
    mErrorPosition = 0;
}

bool ParsedRegexpFilter_base::isMatch (const Bstr &aValue) const
{
    /// @todo (dmik) do regexp matching

    // empty or null mSimple matches any match
    return     mSimple.isEmpty()
            || (mIgnoreCase && mSimple.compare(aValue, Bstr::CaseInsensitive) == 0)
            || (!mIgnoreCase && mSimple.compare(aValue) == 0);
}

} /* namespace matching */
/* vi: set tabstop=4 shiftwidth=4 expandtab: */