text:
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace SP2013Access.Extensions
{
    internal static class TreeViewExtensions
    {
        public static readonly DependencyProperty SelectItemOnRightClickProperty = DependencyProperty.RegisterAttached(
            "SelectItemOnRightClick",
            typeof (bool),
            typeof (TreeViewExtensions),
            new UIPropertyMetadata(false, OnSelectItemOnRightClickChanged));

        public static bool GetSelectItemOnRightClick(DependencyObject d)
        {
            return (bool) d.GetValue(SelectItemOnRightClickProperty);
        }

        public static void SetSelectItemOnRightClick(DependencyObject d, bool value)
        {
            d.SetValue(SelectItemOnRightClickProperty, value);
        }

        private static void OnSelectItemOnRightClickChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var selectItemOnRightClick = (bool) e.NewValue;

            var treeView = d as TreeView;
            if (treeView != null)
            {
                if (selectItemOnRightClick)
                    treeView.PreviewMouseRightButtonDown += OnPreviewMouseRightButtonDown;
                else
                    treeView.PreviewMouseRightButtonDown -= OnPreviewMouseRightButtonDown;
            }
        }

        private static void OnPreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            var treeViewItem = VisualUpwardSearch(e.OriginalSource as DependencyObject);

            if (treeViewItem != null)
            {
                treeViewItem.Focus();
                e.Handled = true;
            }
        }

        public static TreeViewItem VisualUpwardSearch(DependencyObject source)
        {
            while (source != null && !(source is TreeViewItem))
                source = VisualTreeHelper.GetParent(source);
            return source as TreeViewItem;
        }

        public static void ExpandCollapseAll<T>(this TreeViewItem treeViewItem, bool expand = true,
            Func<T, bool> selector = null)
        {
            if (treeViewItem == null)
            {
                return;
            }
            var items =
                (selector != null ? treeViewItem.Items.Cast<T>().Where(selector) : treeViewItem.Items.Cast<T>()).ToArray
                    ();
            foreach (var current in items)
            {
                var tvi = treeViewItem.ItemContainerGenerator.ContainerFromItem(current) as TreeViewItem;

                if (tvi != null)
                {
                    ExpandCollapseAll(tvi, expand, selector);
                }
            }
            treeViewItem.IsExpanded = expand;
        }

        public static void ExpandCollapseAll<T>(this TreeView treeView, bool expand = true,
            Func<T, bool> selector = null)
        {
            var items = selector != null ? treeView.Items.Cast<T>().Where(selector) : treeView.Items.Cast<T>();

            foreach (var current in items.ToArray())
            {
                var treeViewItem = treeView.ItemContainerGenerator.ContainerFromItem(current) as TreeViewItem;

                if (treeViewItem != null)
                {
                    ExpandCollapseAll(treeViewItem, expand, selector);
                }
            }
        }

        public static TreeViewItem GetTreeViewItemFromChild(this TreeView treeView, DependencyObject child)
        {
            if (child == null)
            {
                return null;
            }
            if (child is TreeViewItem)
            {
                return (TreeViewItem) child;
            }
            if (child is TreeView)
            {
                return null;
            }
            return treeView.GetTreeViewItemFromChild(VisualTreeHelper.GetParent(child));
        }

        public static void ClearTreeViewSelection(this TreeView treeView)
        {
            treeView?.Items.ClearTreeViewItemsControlSelection(treeView.ItemContainerGenerator);
        }

        private static void ClearTreeViewItemsControlSelection(this ItemCollection ic, ItemContainerGenerator icg)
        {
            if (ic != null && icg != null)
            {
                for (var i = 0; i < ic.Count; i++)
                {
                    var treeViewItem = icg.ContainerFromIndex(i) as TreeViewItem;

                    if (treeViewItem != null)
                    {
                        treeViewItem.Items.ClearTreeViewItemsControlSelection(treeViewItem.ItemContainerGenerator);
                        treeViewItem.IsSelected = false;
                    }
                }
            }
        }

        /// <summary>
        ///     Tries its best to return the specified element's parent. It will
        ///     try to find, in this order, the VisualParent, LogicalParent, LogicalTemplatedParent.
        ///     It only works for Visual, FrameworkElement or FrameworkContentElement.
        /// </summary>
        /// <param name="element">
        ///     The element to which to return the parent. It will only
        ///     work if element is a Visual, a FrameworkElement or a FrameworkContentElement.
        /// </param>
        /// <remarks>
        ///     If the logical parent is not found (Parent), we check the TemplatedParent
        ///     (see FrameworkElement.Parent documentation). But, we never actually witnessed
        ///     this situation.
        /// </remarks>
        public static DependencyObject GetParent(DependencyObject element)
        {
            var visual = element as Visual;
            var parent = (visual == null) ? null : VisualTreeHelper.GetParent(visual);
            if (parent == null)
            {
                // No Visual parent. Check in the logical tree.
                var fe = element as FrameworkElement;
                if (fe != null)
                {
                    parent = fe.Parent ?? fe.TemplatedParent;
                }
                else
                {
                    var fce = element as FrameworkContentElement;
                    if (fce != null)
                    {
                        parent = fce.Parent ?? fce.TemplatedParent;
                    }
                }
            }
            return parent;
        }

        /// <summary>
        ///     This will search for a parent of the specified type.
        /// </summary>
        /// <typeparam name="T">The type of the element to find</typeparam>
        /// <param name="startingObject">The node where the search begins. This element is not checked.</param>
        /// <returns>Returns the found element. Null if nothing is found.</returns>
        public static T FindParent<T>(DependencyObject startingObject) where T : DependencyObject
        {
            return FindParent<T>(startingObject, false, null);
        }

        /// <summary>
        ///     This will search for a parent of the specified type.
        /// </summary>
        /// <typeparam name="T">The type of the element to find</typeparam>
        /// <param name="startingObject">The node where the search begins.</param>
        /// <param name="checkStartingObject">Should the specified startingObject be checked first.</param>
        /// <returns>Returns the found element. Null if nothing is found.</returns>
        public static T FindParent<T>(DependencyObject startingObject, bool checkStartingObject)
            where T : DependencyObject
        {
            return FindParent<T>(startingObject, checkStartingObject, null);
        }

        /// <summary>
        ///     This will search for a parent of the specified type.
        /// </summary>
        /// <typeparam name="T">The type of the element to find</typeparam>
        /// <param name="startingObject">The node where the search begins.</param>
        /// <param name="checkStartingObject">Should the specified startingObject be checked first.</param>
        /// <param name="additionalCheck">
        ///     Provide a callback to check additional properties
        ///     of the found elements. Can be left Null if no additional criteria are needed.
        /// </param>
        /// <returns>Returns the found element. Null if nothing is found.</returns>
        /// <example>Button button = TreeHelper.FindParent<Button>( this, foundChild => foundChild.Focusable );</example>
        public static T FindParent<T>(DependencyObject startingObject, bool checkStartingObject,
            Func<T, bool> additionalCheck) where T : DependencyObject
        {
            var parent = (checkStartingObject ? startingObject : GetParent(startingObject));
            while (parent != null)
            {
                var foundElement = parent as T;
                if (foundElement != null)
                {
                    if (additionalCheck == null)
                    {
                        return foundElement;
                    }
                    if (additionalCheck(foundElement))
                    {
                        return foundElement;
                    }
                }

                parent = GetParent(parent);
            }
            return null;
        }

        /// <summary>
        ///     This will search for a child of the specified type. The search is performed
        ///     hierarchically, breadth first (as opposed to depth first).
        /// </summary>
        /// <typeparam name="T">The type of the element to find</typeparam>
        /// <param name="parent">The root of the tree to search for. This element itself is not checked.</param>
        /// <returns>Returns the found element. Null if nothing is found.</returns>
        public static T FindChild<T>(DependencyObject parent) where T : DependencyObject
        {
            return FindChild<T>(parent, null);
        }

        /// <summary>
        ///     This will search for a child of the specified type. The search is performed
        ///     hierarchically, breadth first (as opposed to depth first).
        /// </summary>
        /// <typeparam name="T">The type of the element to find</typeparam>
        /// <param name="parent">The root of the tree to search for. This element itself is not checked.</param>
        /// <param name="additionalCheck">
        ///     Provide a callback to check additional properties
        ///     of the found elements. Can be left Null if no additional criteria are needed.
        /// </param>
        /// <returns>Returns the found element. Null if nothing is found.</returns>
        /// <example>Button button = TreeHelper.FindChild<Button>( this, foundChild => foundChild.Focusable );</example>
        public static T FindChild<T>(DependencyObject parent, Func<T, bool> additionalCheck) where T : DependencyObject
        {
            var childrenCount = VisualTreeHelper.GetChildrenCount(parent);
            T child;

            for (var index = 0; index < childrenCount; index++)
            {
                child = VisualTreeHelper.GetChild(parent, index) as T;

                if (child != null)
                {
                    if (additionalCheck == null)
                    {
                        return child;
                    }
                    if (additionalCheck(child))
                    {
                        return child;
                    }
                }
            }

            for (var index = 0; index < childrenCount; index++)
            {
                child = FindChild(VisualTreeHelper.GetChild(parent, index), additionalCheck);

                if (child != null)
                    return child;
            }

            return null;
        }

        /// <summary>
        ///     Returns true if the specified element is a child of parent somewhere in the visual
        ///     tree. This method will work for Visual, FrameworkElement and FrameworkContentElement.
        /// </summary>
        /// <param name="element">The element that is potentially a child of the specified parent.</param>
        /// <param name="parent">The element that is potentially a parent of the specified element.</param>
        public static bool IsDescendantOf(DependencyObject element, DependencyObject parent)
        {
            while (element != null)
            {
                if (Equals(element, parent))
                {
                    return true;
                }
                element = GetParent(element);
            }
            return false;
        }
    }
}


text:
from __future__ import absolute_import, division, print_function
from jaspyx.ast_util import ast_call
from jaspyx.visitor import BaseVisitor

class FuncNew(BaseVisitor):
    def func_new(self, type_, *args):
        self.output('(new ')
        self.visit(ast_call(type_, *args))
        self.output(')')

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">

    <title>Sentence Suggester</title>


text:
package dts

//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// SynchronousObject is a nested struct in dts response
type SynchronousObject struct {
	WholeDatabase string                           `json:"WholeDatabase" xml:"WholeDatabase"`
	DatabaseName  string                           `json:"DatabaseName" xml:"DatabaseName"`
	TableList     TableListInDescribeMigrationJobs `json:"TableList" xml:"TableList"`
}


text:
import { errors } from 'arsenal';
import assert from 'assert';

import bucketPut from '../../../lib/api/bucketPut';
import bucketPutACL from '../../../lib/api/bucketPutACL';
import constants from '../../../constants';
import { cleanup, DummyRequestLogger, makeAuthInfo } from '../helpers';
import objectPut from '../../../lib/api/objectPut';
import objectDelete from '../../../lib/api/objectDelete';
import objectGet from '../../../lib/api/objectGet';
import DummyRequest from '../DummyRequest';

const log = new DummyRequestLogger();
const canonicalID = 'accessKey1';
const authInfo = makeAuthInfo(canonicalID);
const namespace = 'default';
const bucketName = 'bucketname';
const postBody = Buffer.from('I am a body', 'utf8');
const objectKey = 'objectName';
const locationConstraint = 'us-west-1';

function testAuth(bucketOwner, authUser, bucketPutReq, objPutReq, objDelReq,
    log, cb) {
    bucketPut(bucketOwner, bucketPutReq, locationConstraint, log, () => {
        bucketPutACL(bucketOwner, bucketPutReq, log, err => {
            assert.strictEqual(err, undefined);
            objectPut(bucketOwner, objPutReq, undefined, log, err => {
                assert.strictEqual(err, null);
                objectDelete(authUser, objDelReq, log, err => {
                    assert.strictEqual(err, null);
                    cb();
                });
            });
        });
    });
}

describe('objectDelete API', () => {
    let testPutObjectRequest;

    beforeEach(() => {
        cleanup();
        testPutObjectRequest = new DummyRequest({
            bucketName,
            namespace,
            objectKey,
            headers: {},
            url: `/${bucketName}/${objectKey}`,
        }, postBody);
    });

    const testBucketPutRequest = new DummyRequest({
        bucketName,
        namespace,
        headers: {},
        url: `/${bucketName}`,
    });
    const testGetObjectRequest = new DummyRequest({
        bucketName,
        namespace,
        objectKey,
        headers: {},
        url: `/${bucketName}/${objectKey}`,
    });
    const testDeleteRequest = new DummyRequest({
        bucketName,
        namespace,
        objectKey,
        headers: {},
        url: `/${bucketName}/${objectKey}`,
    });

    it.skip('should set delete markers when versioning enabled', () => {
        // TODO
    });

    it('should delete an object', done => {
        bucketPut(authInfo, testBucketPutRequest, locationConstraint,
            log, () => {
                objectPut(authInfo, testPutObjectRequest,
                    undefined, log, () => {
                        objectDelete(authInfo, testDeleteRequest, log, err => {
                            assert.strictEqual(err, null);
                            objectGet(authInfo, testGetObjectRequest,
                                log, err => {
                                    assert.deepStrictEqual(err,
                                        errors.NoSuchKey);
                                    done();
                                });
                        });
                    });
            });
    });

    it('should delete a 0 bytes object', done => {
        const testPutObjectRequest = new DummyRequest({
            bucketName,
            namespace,
            objectKey,
            headers: {},
            url: `/${bucketName}/${objectKey}`,
        }, '');
        bucketPut(authInfo, testBucketPutRequest, locationConstraint,
            log, () => {
                objectPut(authInfo, testPutObjectRequest,
                    undefined, log, () => {
                        objectDelete(authInfo, testDeleteRequest, log, err => {
                            assert.strictEqual(err, null);
                            objectGet(authInfo, testGetObjectRequest,
                                log, err => {
                                    const expected =
                                    Object.assign({}, errors.NoSuchKey);
                                    const received = Object.assign({}, err);
                                    assert.deepStrictEqual(received, expected);
                                    done();
                                });
                        });
                    });
            });
    });

    it('should prevent anonymous user deleteObject API access', done => {
        const publicAuthInfo = makeAuthInfo(constants.publicId);
        objectDelete(publicAuthInfo, testDeleteRequest, log, err => {
            assert.deepStrictEqual(err, errors.AccessDenied);
            done();
        });
    });

    it('should del object if user has FULL_CONTROL grant on bucket', done => {
        const bucketOwner = makeAuthInfo('accessKey2');
        const authUser = makeAuthInfo('accessKey3');
        testBucketPutRequest.headers['x-amz-grant-full-control'] =
            `id=${authUser.getCanonicalID()}`;
        testAuth(bucketOwner, authUser, testBucketPutRequest,
            testPutObjectRequest, testDeleteRequest, log, done);
    });

    it('should del object if user has WRITE grant on bucket', done => {
        const bucketOwner = makeAuthInfo('accessKey2');
        const authUser = makeAuthInfo('accessKey3');
        testBucketPutRequest.headers['x-amz-grant-write'] =
            `id=${authUser.getCanonicalID()}`;
        testAuth(bucketOwner, authUser, testBucketPutRequest,
            testPutObjectRequest, testDeleteRequest, log, done);
    });

    it('should del object in bucket with public-read-write acl', done => {
        const bucketOwner = makeAuthInfo('accessKey2');
        const authUser = makeAuthInfo('accessKey3');
        testBucketPutRequest.headers['x-amz-acl'] = 'public-read-write';
        testAuth(bucketOwner, authUser, testBucketPutRequest,
            testPutObjectRequest, testDeleteRequest, log, done);
    });
});


text:
<?php

namespace Scrutinizer\Tests\PhpAnalyzer\DataFlow\TypeInference\FunctionInterpreter;

use Scrutinizer\PhpAnalyzer\PhpParser\Type\PhpType;
use Scrutinizer\PhpAnalyzer\PhpParser\Type\TypeRegistry;
use Scrutinizer\PhpAnalyzer\DataFlow\TypeInference\FunctionInterpreter\CoreFunctionInterpreter;
use Scrutinizer\PhpAnalyzer\Model\GlobalFunction;

class CoreFunctionInterpreterTest extends \PHPUnit_Framework_TestCase
{
    /** @var TypeRegistry */
    private $registry;

    /** @var CoreFunctionInterpreter */
    private $interpreter;

    public function testReturnsNullForUnknownFunction()
    {
        $this->assertNull($this->interpreter->getPreciserFunctionReturnTypeKnowingArguments(
                new GlobalFunction('fofoofofofodkfjkdfkdjfkd'), array(), array()));
    }

    public function testUnserialize()
    {
        $this->assertTypeEquals('unknown', $this->interpreter->getPreciserFunctionReturnTypeKnowingArguments(
            new GlobalFunction('unserialize'), array(), array()));
    }

    /**
     * @dataProvider getMinMaxTests
     */
    public function testMinMax(array $passedTypes, $expectedType)
    {
        $resolvedTypes = array_map(array($this->registry, 'resolveType'), $passedTypes);

        $max = new GlobalFunction('max');
        $restrictedType = $this->interpreter->getPreciserFunctionReturnTypeKnowingArguments($max, array(), $resolvedTypes);
        $this->assertTypeEquals($expectedType, $restrictedType);

        $min = new GlobalFunction('min');
        $restrictedType = $this->interpreter->getPreciserFunctionReturnTypeKnowingArguments($min, array(), $resolvedTypes);
        $this->assertTypeEquals($expectedType, $restrictedType);
    }

    public function getMinMaxTests()
    {
        $tests = array();

        // If a single array is passed, the highest/lowest value in that array is returned.
        $tests[] = array(array('array'), 'unknown');
        $tests[] = array(array('array<integer>'), 'integer');
        $tests[] = array(array('array<object<Foo>>'), 'object<Foo>');
        $tests[] = array(array('string'), null);

        // If multiple values are passed, one of these values will be returned. So,
        // we need to built a union over these types.
        $tests[] = array(array('integer', 'string'), 'integer|string');
        $tests[] = array(array('array', 'string'), 'array|string'); // Technically, this will always return an array.
                                                                    // As an array is always greater than a string. We should
                                                                    // cover this at some point.
        $tests[] = array(array('boolean', 'integer'), 'boolean|integer');

        return $tests;
    }

    public function testVersionCompare()
    {
        $f = new GlobalFunction('version_compare');

        $restrictedType = $this->interpreter->getPreciserFunctionReturnTypeKnowingArguments($f, array(), array());
        $this->assertTypeEquals('integer|boolean', $restrictedType);

        $restrictedType = $this->interpreter->getPreciserFunctionReturnTypeKnowingArguments($f, array(), array(null));
        $this->assertTypeEquals('integer|boolean', $restrictedType);

        $restrictedType = $this->interpreter->getPreciserFunctionReturnTypeKnowingArguments($f, array(), array(null, null));
        $this->assertTypeEquals('integer', $restrictedType);

        $restrictedType = $this->interpreter->getPreciserFunctionReturnTypeKnowingArguments($f, array(), array(null, null, null));
        $this->assertTypeEquals('boolean', $restrictedType);

        $restrictedType = $this->interpreter->getPreciserFunctionReturnTypeKnowingArguments($f, array(), array(null, null, null, null));
        $this->assertTypeEquals('integer|boolean', $restrictedType);
    }

    public function testVarExport()
    {
        $f = new GlobalFunction('var_export');
        $restrictedType = $this->interpreter->getPreciserFunctionReturnTypeKnowingArguments(
            $f,
            array(null, new \PHPParser_Node_Expr_ConstFetch(new \PHPParser_Node_Name(array('true')))),
            array('all', 'boolean')
        );
        $this->assertTypeEquals('string', $restrictedType);

        $this->assertTypeEquals(null, $this->interpreter->getPreciserFunctionReturnTypeKnowingArguments($f, array(), array()));
    }

    /**
     * @dataProvider getPregMatchAliases
     */
    public function testPregMatchAndAliases($name)
    {
        $function = new GlobalFunction($name);

        $restrictedType = $this->interpreter->getPreciserFunctionReturnTypeKnowingArguments($function,
                array(), array(null, null, $this->registry->getNativeType('string')));
        $this->assertNotNull($restrictedType);
        $this->assertTrue($this->registry->getNativeType('string')->equals($restrictedType));

        $restrictedType = $this->interpreter->getPreciserFunctionReturnTypeKnowingArguments($function,
                array(), array(null, null, $this->registry->getNativeType('all')));
        $this->assertNull($restrictedType);

        $restrictedType = $this->interpreter->getPreciserFunctionReturnTypeKnowingArguments($function,
                array(), array(null, null, $this->registry->resolveType('string|integer')));
        $this->assertNotNull($restrictedType);
        $this->assertTrue($this->registry->getNativeType('string')->equals($restrictedType));

        $restrictedType = $this->interpreter->getPreciserFunctionReturnTypeKnowingArguments($function,
                array(), array(null, null, $this->registry->getNativeType('array')));
        $this->assertNotNull($restrictedType);
        $this->assertTrue($this->registry->resolveType('array<string>')->equals($restrictedType));

        $restrictedType = $this->interpreter->getPreciserFunctionReturnTypeKnowingArguments($function,
                array(), array(null, null, $this->registry->getNativeType('unknown')));
        $this->assertNotNull($restrictedType);
        $this->assertTrue($this->registry->resolveType('unknown')->equals($restrictedType));
    }

    public function getPregMatchAliases()
    {
        return array(
            array('preg_filter'),
            array('preg_replace'),
            array('preg_replace_callback'),
            array('str_replace'),
        );
    }

    protected function setUp()
    {
        $this->registry = new TypeRegistry();
        $this->interpreter = new CoreFunctionInterpreter($this->registry);
    }

    private function assertTypeEquals($expectedType, PhpType $restrictedType = null)
    {
        if (null === $expectedType) {
            $this->assertNull($restrictedType);
        } else {
            $resolvedExpectedType = $this->registry->resolveType($expectedType);

            $this->assertNotNull($restrictedType);
            $this->assertTrue($resolvedExpectedType->equals($restrictedType), sprintf('Failed to assert that expected type "%s" equals the actual type "%s".', $resolvedExpectedType, $restrictedType));
        }
    }
}


text:
// This module monitors the total number of requests server and the memory used
// if memory usage or requests served are beyond the specified limits, it kills itself.
// Exits with code 30

// Best used in cluster mode - where each worker process could be monitoredand shut down
// Master process would bring back the worker process up.

var EventEmitter = require('events').EventEmitter,
    util = require('util');

var memCont = null,
    reqCounter = null; //singleton

function MemoryController(maxRequests, maxMemory, reqCounter) {
    var that = this;
    this._state = 0;
    this._maxRequests = maxRequests;
    this._maxMemory = maxMemory;
    this._requestCount = 0;
    this._connections = 0;
    this._requests = 0;
    this._reqCounter = reqCounter;

    // register event functions
    reqCounter.on('connection', function () {
        that.onConnection.apply(that, arguments);
    });
    reqCounter.on('conn_closed', function () {
        that.onConnectionClosed.apply(that, arguments);
    });
    reqCounter.on('request', function () {
        that.onRequest.apply(that, arguments);
    });
    reqCounter.on('req_end', function () {
        that.onRequestEnd.apply(that, arguments);
    });
}

module.exports.__MemoryController = MemoryController;

MemoryController.prototype.onConnection = function (cons, reqs) {
    this._connections = cons;
    this._requests = reqs;

    if (this.checkState()) {
        this.throttle();
    }
};

MemoryController.prototype.onConnectionClosed = function (cons, reqs) {
    this._connections = cons;
    this._requests = reqs;
    if (cons === 0 || reqs === 0) {
        this.throttleDone();
    }
};

MemoryController.prototype.onRequest = function (cons, reqs, resp) {
    var origWriteHead = resp.writeHead,
        that = this;

    this._requests = reqs;
    this._connections = cons;

    if (typeof that._maxRequests === 'number' && that._maxRequests > 0) {
        // increase total number of served requests
        that._requestCount++;
    }

    resp.writeHead = function (status, reason, headers) {
        var realHeaders = headers,
            foundCon = false;
        // if reason is the actual headers
        if (typeof reason !== 'string') {
            if (!reason) {
                reason = {};
            }
            realHeaders = reason;
        } else {
            if (!headers) {
                realHeaders = headers = {};
            }
        }

        if (realHeaders instanceof Array) {
            realHeaders.forEach(function (l) {
                if (l instanceof Array && l.length >= 2 && l[0] === 'Connection') {
                    foundCon = true;
                    l[1] = 'close';
                }
            });
            if (!foundCon) {
                realHeaders.push(['Connection', 'close']);
            }
        } else {
            realHeaders.Connection = 'close';
        }
        // call the original function
        origWriteHead.call(resp, status, reason, headers);
    };
    if (that.checkState()) {
        that.throttle();
    }
};

MemoryController.prototype.onRequestEnd = function (cons, reqs, req) {
    var that = this;

    this._requests = reqs;
    this._connections = cons;

    if (that._throttle) {
        req.connection.end();
        req.connection.destroy();
    }
    if (that._requests === 0 || that._connections === 0) {
        that.throttleDone();
    }
};

MemoryController.prototype.throttleDone = function () {
    if (!this._throttle) {
        return;
    }

    // Sends an event before exit
    if (this.restartEvent) {
        process.emit(this.restartEvent, {});
    }

    // in this version - just kill the procs,
    // since another one has been respawned asynchronously.
    process.exit(30);
};

MemoryController.prototype.throttle = function () {
    var that = this;

    if (this._throttle || this._throttleRequested) {
        return;
    }

    // set throttle was requested and will
    // start after a timeout required for other process to be restarted.
    this._throttleRequested = true;
    // requet throttling delayed now
    setTimeout(function () {
        that._throttle = true;
        that._reqCounter._servers.forEach(function (l) {
            // stop accepting other connections
            l.close();
        });
        if (that._connections === 0 && that._requests === 0) {
            that.throttleDone();
        } else {
            that._timer = setTimeout(function () {
                that.throttleDone();
            }, 30000);
        }
    }, 200);
};

MemoryController.prototype.checkState = function () {
    if (this._maxMemory && process.memoryUsage().vsize > this._maxMemory) {
        this.restartEvent = 'memory-restart';
        return 1;
    }

    if (this._maxRequests && this._requestCount >= this._maxRequests) {
        this.restartEvent = 'count-restart';
        return 2;
    }
    if (this._timer) {
        clearTimeout(this._timer);
        this._timer = 0;
    }
    return false;
};

function ReqCounter() {
    this._requests = 0;
    this._totalRequests = 0;
    this._servers = [];
    this._connections = 0;
    this._transfered = 0;
}

util.inherits(ReqCounter, EventEmitter);

ReqCounter.prototype.addServer = function (server) {
    var found = false;
    this._servers.forEach(function (l) {
        if (l === server) {
            found = true;
        }
    });
    if (!found) {
        this._servers.push(server);
        this.registerEvents(server);
    }
};

ReqCounter.prototype.registerEvents = function (server) {
    var that = this,
        origEmit = server.emit,
        stream,
        req,
        resp,
        origEnd,
        origWrite;

    server.emit = function () {
        var args = arguments;
        if (args[0] !== 'connection' && args[0] !== 'request') {
            origEmit.apply(server, arguments);
            return;
        }

        if (args[0] === 'connection') {
            stream = args[1];
            origWrite = stream.write;

            // Add connection into the pool
            that._connections++;

            // get the number of bytes transferred
            stream.write = function (data) {
                if (data && data.length) {
                    that._transfered += data.length;
                }
                origWrite.apply(this, arguments);
            };

            stream.on('close', function () {
                that._connections--;
                if (that._connections < 0) {
                    that._connections = 0;
                }
                that.emit('conn_closed', that._connections, that._requests);
            });

            that.emit('connection', that._connections, that._requests);

            // in the case of http server
        } else if (args[0] === 'request') {

            req = args[1];
            resp = args[2];
            origEnd = resp.end;

            that._requests++;
            that._totalRequests++;
            that.emit('request', that._connections, that._requests, resp);

            resp.end = function () {
                that._requests--;
                if (that._requests < 0) {
                    that._requests = 0;
                }
                origEnd.apply(this, arguments);

                that.emit('req_end', that._connections, that._requests, req);
            };
        }
        origEmit.apply(this, arguments);
    };
};

// Instantiate the request counter
function setupReqCounter() {

    if (!reqCounter) {
        reqCounter = new ReqCounter();
    }

    if (!process.throttle) {
        process.throttle = {};
    }

    process.throttle.getRequestCount = function () {
        return reqCounter._requests;
    };

    process.throttle.getTotalRequestCount = function () {
        return reqCounter._totalRequests;
    };

    process.throttle.getTransferred = function () {
        return reqCounter._transfered;
    };

    process.throttle.getOpenConnections = function () {
        return reqCounter._connections;
    };
}

// Instantiate the MemoryController
function setupMemControl(config) {

    if (!config) {
        return;
    }
    var maxRequests = config.max_requests,
        maxMemory = config.max_memory;

    if (memCont) {
        // If object is already created
        // do not create again
        return;
    }

    if (maxRequests || maxMemory) {
        //else create a new instance
        memCont = new MemoryController(maxRequests, maxMemory, reqCounter);
    }
}

var Throttler = function (config) {
    // Initializations
    setupReqCounter();
    setupMemControl(config);
};

/*
 * All the servers need to be registered to compute the total number of requests
 * served by the application
 */
Throttler.prototype.addServer = function (server) {
    if (reqCounter) {
        reqCounter.addServer(server);
    }
};

/*
 * This allows the process to be started with just monitoring, and at a later point
 * application could decide to ask the process to be killed
 * upon reaching limits
 */
Throttler.prototype.setConfig = function (config) {
    if (!memCont) {
        setupMemControl(config);
        return;
    }
    if (config.max_requests) {
        memCont._maxRequests = config.max_requests;
    }
    if (config.max_memory) {
        memCont._maxMemory = config.max_memory;
    }
};

module.exports = Throttler;


text:
package pl.dawidgdanski.bakery;

import com.squareup.otto.Bus;

import org.robolectric.RuntimeEnvironment;

import pl.dawidgdanski.bakery.database.DatabaseHelper;
import pl.dawidgdanski.bakery.inject.module.ApiModule;
import pl.dawidgdanski.bakery.inject.module.ApplicationModule;
import pl.dawidgdanski.bakery.inject.module.BusModule;
import pl.dawidgdanski.bakery.inject.module.CloudModule;
import pl.dawidgdanski.bakery.inject.module.DatabaseModule;
import pl.dawidgdanski.bakery.inject.module.TestApplicationModule;
import pl.dawidgdanski.bakery.inject.module.TestBusModule;
import pl.dawidgdanski.bakery.inject.module.TestCloudModule;
import pl.dawidgdanski.bakery.inject.module.TestDatabaseModule;
import pl.dawidgdanski.bakery.library.cloud.GodtCloud;

public class TestApp extends App {

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public ApiModule getApiModule(App app) {
        return new ApiModule();
    }

    @Override
    public ApplicationModule getApplicationModule(App app) {
        return new TestApplicationModule(app);
    }

    @Override
    public BusModule getBusModule(App app) {
        return new TestBusModule();
    }

    @Override
    public CloudModule getCloudModule(App app) {
        return new TestCloudModule();
    }

    @Override
    public DatabaseModule getDatabaseModule(App app) {
        return new TestDatabaseModule();
    }

    public static TestApp get() {
        return  (TestApp)RuntimeEnvironment.application;
    }

    public Bus geInjectedBus() {
        return bus;
    }

    public DatabaseHelper getInjectedDatabaseHelper() {
        return databaseHelper;
    }

    public GodtCloud getInjectedGodtCloud() {
        return godtCloud;
    }
}


text:
//-----------------------------------------------------------------------
// <copyright file="LocalConcurrencySpec.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com>
//     Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System.Collections.Immutable;
using Akka.Actor;
using Akka.Configuration;
using Xunit;
using Xunit.Abstractions;

namespace Akka.DistributedData.Tests
{
    [Collection("DistributedDataSpec")]
    public class LocalConcurrencySpec : Akka.TestKit.Xunit2.TestKit
    {
        public sealed class Updater : ReceiveActor, IWithUnboundedStash
        {
            public static readonly ORSetKey<string> Key = new ORSetKey<string>("key");
            public Updater()
            {
                var cluster = Cluster.Cluster.Get(Context.System);
                var replicator = DistributedData.Get(Context.System).Replicator;

                Receive<string>(s =>
                {
                    var update = Dsl.Update(Key, ORSet<string>.Empty, WriteLocal.Instance, old => old.Add(cluster.SelfUniqueAddress, s));
                    replicator.Tell(update);
                });
            }

            public IStash Stash { get; set; }
        }

        private readonly IActorRef _replicator;

        public LocalConcurrencySpec(ITestOutputHelper output)
            : base(ConfigurationFactory.ParseString(@"
              akka.actor.provider = ""Akka.Cluster.ClusterActorRefProvider, Akka.Cluster""
              akka.remote.helios.tcp.port = 0"),
            "LocalConcurrencySpec", output)
        {
            _replicator = DistributedData.Get(Sys).Replicator;
        }

        [Fact]
        public void Updates_from_same_node_should_be_possible_to_do_from_two_actors()
        {
            var updater1 = ActorOf(Props.Create<Updater>(), "updater1");
            var updater2 = ActorOf(Props.Create<Updater>(), "updater2");

            var b = ImmutableHashSet<string>.Empty.ToBuilder();
            for (int i = 1; i <= 100; i++)
            {
                var m1 = "a" + 1;
                var m2 = "b" + 1;
                updater1.Tell(m1);
                updater2.Tell(m2);

                b.Add(m1);
                b.Add(m2);
            }

            var expected = b.ToImmutable();
            AwaitAssert(() =>
            {
                _replicator.Tell(Dsl.Get(Updater.Key, ReadLocal.Instance));
                var msg = ExpectMsg<Replicator.GetSuccess>();
                var elements = msg.Get(Updater.Key).Elements;
                Assert.Equal(expected, elements);
            });
        }
    }
}


text:
```
$ ssh -Q cipher
$ ssh -Q cipher-auth
$ ssh -Q mac
$ ssh -Q kex
$ ssh -Q key
```

#### More
[1] https://wiki.mozilla.org/Security/Guidelines/OpenSSH


text:
require 'rubygems'
require "rubeus"
Rubeus::Swing.irb

@conn = Rubeus::Jdbc::DriverManager.
  connect("jdbc:derby:test_db;create = true")
tables = @conn.meta_data.tables(:schema => "APP")

JFrame.new("Rubeus Swing Example 01") do |frame|
  frame.layout = BoxLayout.new(:X_AXIS)
  JSplitPane.new(JSplitPane::HORIZONTAL_SPLIT) do
    JScrollPane.new(:preferred_size => [150, 250]) do |pane|
      @list = JList.new(tables.map(&:name).to_java) do |event|
        table_name = @list.selected_value.inspect
        @conn.query("select * from #{table_name}") do |rs|
          @table.model = rs.map{|row| row.to_a}
        end
      end
    end
    JScrollPane.new{|pane| @table = JTable.new}
  end
  frame.visible = true
end


text:
import java.util.concurrent._

object ExampleApp extends App {

    println("Hello, World")

}


text:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils;

namespace Grpc.Core
{
    ///
    /// Represents a gRPC channel. Channels are an abstraction of long-lived connections to remote servers.
    /// More client objects can reuse the same channel. Creating a channel is an expensive operation compared to invoking
    /// a remote call so in general you should reuse a single channel for as many calls as possible.
    ///
    public class Channel
    {
        static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<Channel>();

        readonly object myLock = new object();
        readonly AtomicCounter activeCallCounter = new AtomicCounter();
        readonly CancellationTokenSource shutdownTokenSource = new CancellationTokenSource();

        readonly string target;
        readonly GrpcEnvironment environment;
        readonly CompletionQueueSafeHandle completionQueue;
        readonly ChannelSafeHandle handle;
        readonly Dictionary<string, ChannelOption> options;

        readonly Task connectivityWatcherTask;

        bool shutdownRequested;

        ///
        /// Creates a channel that connects to a specific host.
        /// Port will default to 80 for an unsecure channel and to 443 for a secure channel.
        ///
        /// <param name="target">Target of the channel.</param>
        /// <param name="credentials">Credentials to secure the channel.</param>
        public Channel(string target, ChannelCredentials credentials) :
            this(target, credentials, null)
        {
        }

        ///
        /// Creates a channel that connects to a specific host.
        /// Port will default to 80 for an unsecure channel and to 443 for a secure channel.
        ///
        /// <param name="target">Target of the channel.</param>
        /// <param name="credentials">Credentials to secure the channel.</param>
        /// <param name="options">Channel options.</param>
        public Channel(string target, ChannelCredentials credentials, IEnumerable<ChannelOption> options)
        {
            this.target = GrpcPreconditions.CheckNotNull(target, "target");
            this.options = CreateOptionsDictionary(options);
            EnsureUserAgentChannelOption(this.options);
            this.environment = GrpcEnvironment.AddRef();

            this.completionQueue = this.environment.PickCompletionQueue();
            using (var nativeCredentials = credentials.ToNativeCredentials())
            using (var nativeChannelArgs = ChannelOptions.CreateChannelArgs(this.options.Values))
            {
                if (nativeCredentials != null)
                {
                    this.handle = ChannelSafeHandle.CreateSecure(nativeCredentials, target, nativeChannelArgs);
                }
                else
                {
                    this.handle = ChannelSafeHandle.CreateInsecure(target, nativeChannelArgs);
                }
            }
            // TODO(jtattermusch): Workaround for https://github.com/GoogleCloudPlatform/google-cloud-dotnet/issues/822.
            // Remove once retries are supported in C core
            this.connectivityWatcherTask = RunConnectivityWatcherAsync();
            GrpcEnvironment.RegisterChannel(this);
        }

        ///
        /// Creates a channel that connects to a specific host and port.
        ///
        /// <param name="host">The name or IP address of the host.</param>
        /// <param name="port">The port.</param>
        /// <param name="credentials">Credentials to secure the channel.</param>
        public Channel(string host, int port, ChannelCredentials credentials) :
            this(host, port, credentials, null)
        {
        }

        ///
        /// Creates a channel that connects to a specific host and port.
        ///
        /// <param name="host">The name or IP address of the host.</param>
        /// <param name="port">The port.</param>
        /// <param name="credentials">Credentials to secure the channel.</param>
        /// <param name="options">Channel options.</param>
        public Channel(string host, int port, ChannelCredentials credentials, IEnumerable<ChannelOption> options) :
            this(string.Format("{0}:{1}", host, port), credentials, options)
        {
        }

        ///
        /// Gets current connectivity state of this channel.
        /// After channel is has been shutdown, <c>ChannelState.Shutdown</c> will be returned.
        ///
        public ChannelState State
        {
            get
            {
                return GetConnectivityState(false);
            }
        }

        ///
        /// Returned tasks completes once channel state has become different from
        /// given lastObservedState.
        /// If deadline is reached or and error occurs, returned task is cancelled.
        ///
        public Task WaitForStateChangedAsync(ChannelState lastObservedState, DateTime? deadline = null)
        {
            GrpcPreconditions.CheckArgument(lastObservedState != ChannelState.Shutdown,
                "Shutdown is a terminal state. No further state changes can occur.");
            var tcs = new TaskCompletionSource<object>();
            var deadlineTimespec = deadline.HasValue ? Timespec.FromDateTime(deadline.Value) : Timespec.InfFuture;
            var handler = new BatchCompletionDelegate((success, ctx) =>
            {
                if (success)
                {
                    tcs.SetResult(null);
                }
                else
                {
                    tcs.SetCanceled();
                }
            });
            handle.WatchConnectivityState(lastObservedState, deadlineTimespec, completionQueue, handler);
            return tcs.Task;
        }

        /// Resolved address of the remote endpoint in URI format.
        public string ResolvedTarget
        {
            get
            {
                return handle.GetTarget();
            }
        }

        /// The original target used to create the channel.
        public string Target
        {
            get
            {
                return this.target;
            }
        }

        ///
        /// Returns a token that gets cancelled once <c>ShutdownAsync</c> is invoked.
        ///
        public CancellationToken ShutdownToken
        {
            get
            {
                return this.shutdownTokenSource.Token;
            }
        }

        ///
        /// Allows explicitly requesting channel to connect without starting an RPC.
        /// Returned task completes once state Ready was seen. If the deadline is reached,
        /// or channel enters the Shutdown state, the task is cancelled.
        /// There is no need to call this explicitly unless your use case requires that.
        /// Starting an RPC on a new channel will request connection implicitly.
        ///
        /// <param name="deadline">The deadline. <c>null</c> indicates no deadline.</param>
        public async Task ConnectAsync(DateTime? deadline = null)
        {
            var currentState = GetConnectivityState(true);
            while (currentState != ChannelState.Ready)
            {
                if (currentState == ChannelState.Shutdown)
                {
                    throw new OperationCanceledException("Channel has reached Shutdown state.");
                }
                await WaitForStateChangedAsync(currentState, deadline).ConfigureAwait(false);
                currentState = GetConnectivityState(false);
            }
        }

        ///
        /// Shuts down the channel cleanly. It is strongly recommended to shutdown
        /// all previously created channels before exiting from the process.
        ///
        /// <remarks>
        /// This method doesn't wait for all calls on this channel to finish (nor does
        /// it explicitly cancel all outstanding calls). It is user's responsibility to make sure
        /// all the calls on this channel have finished (successfully or with an error)
        /// before shutting down the channel to ensure channel shutdown won't impact
        /// the outcome of those remote calls.
        /// </remarks>
        public async Task ShutdownAsync()
        {
            lock (myLock)
            {
                GrpcPreconditions.CheckState(!shutdownRequested);
                shutdownRequested = true;
            }
            GrpcEnvironment.UnregisterChannel(this);

            shutdownTokenSource.Cancel();

            var activeCallCount = activeCallCounter.Count;
            if (activeCallCount > 0)
            {
                Logger.Warning("Channel shutdown was called but there are still {0} active calls for that channel.", activeCallCount);
            }

            handle.Dispose();

            await Task.WhenAll(GrpcEnvironment.ReleaseAsync(), connectivityWatcherTask).ConfigureAwait(false);
        }

        internal ChannelSafeHandle Handle
        {
            get
            {
                return this.handle;
            }
        }

        internal GrpcEnvironment Environment
        {
            get
            {
                return this.environment;
            }
        }

        internal CompletionQueueSafeHandle CompletionQueue
        {
            get
            {
                return this.completionQueue;
            }
        }

        internal void AddCallReference(object call)
        {
            activeCallCounter.Increment();

            bool success = false;
            handle.DangerousAddRef(ref success);
            GrpcPreconditions.CheckState(success);
        }

        internal void RemoveCallReference(object call)
        {
            handle.DangerousRelease();

            activeCallCounter.Decrement();
        }

        private ChannelState GetConnectivityState(bool tryToConnect)
        {
            try
            {
                return handle.CheckConnectivityState(tryToConnect);
            }
            catch (ObjectDisposedException)
            {
                return ChannelState.Shutdown;
            }
        }

        ///
        /// Constantly Watches channel connectivity status to work around https://github.com/GoogleCloudPlatform/google-cloud-dotnet/issues/822
        ///
        private async Task RunConnectivityWatcherAsync()
        {
            try
            {
                var lastState = State;
                while (lastState != ChannelState.Shutdown)
                {
                    lock (myLock)
                    {
                        if (shutdownRequested)
                        {
                            break;
                        }
                    }

                    try
                    {
                        await WaitForStateChangedAsync(lastState, DateTime.UtcNow.AddSeconds(1)).ConfigureAwait(false);
                    }
                    catch (TaskCanceledException)
                    {
                        // ignore timeout
                    }
                    lastState = State;
                }
            }
            catch (ObjectDisposedException) {
                // during shutdown, channel is going to be disposed.
            }
        }

        private static void EnsureUserAgentChannelOption(Dictionary<string, ChannelOption> options)
        {
            var key = ChannelOptions.PrimaryUserAgentString;
            var userAgentString = "";

            ChannelOption option;
            if (options.TryGetValue(key, out option))
            {
                // user-provided userAgentString needs to be at the beginning
                userAgentString = option.StringValue + " ";
            };

            // TODO(jtattermusch): it would be useful to also provide .NET/mono version.
            userAgentString += string.Format("grpc-csharp/{0}", VersionInfo.CurrentVersion);

            options[ChannelOptions.PrimaryUserAgentString] = new ChannelOption(key, userAgentString);
        }

        private static Dictionary<string, ChannelOption> CreateOptionsDictionary(IEnumerable<ChannelOption> options)
        {
            var dict = new Dictionary<string, ChannelOption>();
            if (options == null)
            {
                return dict;
            }
            foreach (var option in options)
            {
                dict.Add(option.Name, option);
            }
            return dict;
        }
    }
}


text:
using System.Runtime.Serialization;

namespace PushNotify.Core.Services.Pushover.Responses
{
    [DataContract]
    public sealed class MessageListResponse : PushoverResponse
    {
        [DataMember(Name = "messages")]
        public PushoverMessage[] Messages { get; set; }
    }
}


text:
using System.ComponentModel;

namespace IdSharp.Tagging.ID3v2.Frames.Items
{
    /// <summary>
    /// Event timing item.  See <see cref="IEventTiming"/>.
    /// </summary>
    public interface IEventTimingItem : INotifyPropertyChanged
    {
        /// <summary>
        /// Gets or sets the type of the event.
        /// </summary>
        /// <value>The type of the event.</value>
        MusicEvent EventType { get; set; }

        /// <summary>
        /// Gets or sets the timestamp in milliseconds or frames according to <see cref="IEventTiming.TimestampFormat"/>.
        /// </summary>
        /// <value>The timestamp in milliseconds or frames according to <see cref="IEventTiming.TimestampFormat"/>.</value>
        int Timestamp { get; set; }
    }
}


text: dynamic layout generator with React future routes


text:
<?php

$db_handle=mysql_connect("localhost","phpmyadmin","Testing1@");

$db_found = mysql_select_db("sfp_staging",$db_handle);

?>


text:
Project Generation Options
==========================

project_name [Project Name]:
    Your Human Readable project name, including any capitalization or spaces.

project_slug [project_slug]:
    The slug of your project, without dashes or spaces. Used to name your repo
    and in other places where a Python-importable version of your project name
    is needed.

author_name [Your Name]:
    You! This goes into places like the LICENSE file.

email [Your email]:
    Your email address.

description [A short description of the project.]
    Used in the generated README.rst and other places.

domain_name [example.com]
    Whatever domain name you plan to use for your project when it goes live.

version [0.1.0]
    The starting version number for your project.

timezone [UTC]
    Used in the common settings file for the `TIME_ZONE` value.

windows [n]
    Whether you'll be developing on Windows.

use_python3 [y]
    By default, the Python code generated will be for Python 3.x. But if you
    answer `n` here, it will be legacy Python 2.7 code.

open_source_license [1]
    Select a software license for the project. The choices are:

    1. MIT_
    2. BSD_
    3. GPLv3_
    4. `Apache Software License 2.0`_
    5. Not open source

.. _MIT: https://opensource.org/licenses/MIT
.. _BSD: https://opensource.org/licenses/BSD-3-Clause
.. _GPLv3: https://www.gnu.org/licenses/gpl.html
.. _Apache Software License 2.0: http://www.apache.org/licenses/LICENSE-2.0


text:
(function () {
    var draw = function (domId, options) {
        var myCanvas = document.createElement('canvas'),
            wrapper = document.getElementById(domId)
            ;

        myCanvas.style.width = getComputedStyle(wrapper).width;
        myCanvas.style.height = getComputedStyle(wrapper).height;

        this.canvas = myCanvas;
        this.canvas.width = parseInt(myCanvas.style.width);
        this.canvas.height = parseInt(myCanvas.style.height);

        this.context = this.canvas.getContext('2d');

        this.line = [
            {
                x: 0,
                y: 0
            }
        ]

        this.color = options.color || 'red';

        wrapper.appendChild(myCanvas);
    };

    draw.prototype.drawLine = function (xV, yV) {
        var len = this.line.length - 1;

        //解决clearRect失效的问题 http://stackoverflow.com/questions/9743027/clearrect-not-working
        this.context.beginPath();

        //old point.
        this.context.moveTo(this.line[len].x, this.line[len].y);

        //new point.
        this.context.lineTo(xV, yV);
        this.context.lineWidth = 1;
        this.context.strokeStyle = this.color;
        this.context.stroke();

        this.line.push({
            x: xV,
            y: yV
        });
    };

    //画成组的线.
    draw.prototype.drawLines = function (points) {

        this.context.lineWidth = 1;
        this.context.strokeStyle = this.color;

        for (var i = 0, len = points.length; i < len - 1; i++) {
            this.context.moveTo(points[i].x, points[i].y);
            this.context.lineTo(points[i + 1].x, points[i + 1].y);
            this.context.stroke();
        }
    };

    draw.prototype.size = function () {
        return {
            width: this.canvas.width,
            height: this.canvas.height
        }
    };

    draw.prototype.reset = function () {

        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
        this.line = [
            {
                x: 0,
                y: 0
            }
        ]
    }

    window.Draw = draw;
})();


text:
namespace chromeos {

namespace {

class ShillProfileClientImpl : public ShillProfileClient {
 public:
  ShillProfileClientImpl();

  virtual void AddPropertyChangedObserver(
      const dbus::ObjectPath& profile_path,
      ShillPropertyChangedObserver* observer) OVERRIDE {
    GetHelper(profile_path)->AddPropertyChangedObserver(observer);
  }

  virtual void RemovePropertyChangedObserver(
      const dbus::ObjectPath& profile_path,
      ShillPropertyChangedObserver* observer) OVERRIDE {
    GetHelper(profile_path)->RemovePropertyChangedObserver(observer);
  }

  virtual void GetProperties(
      const dbus::ObjectPath& profile_path,
      const DictionaryValueCallbackWithoutStatus& callback,
      const ErrorCallback& error_callback) OVERRIDE;
  virtual void GetEntry(const dbus::ObjectPath& profile_path,
                        const std::string& entry_path,
                        const DictionaryValueCallbackWithoutStatus& callback,
                        const ErrorCallback& error_callback) OVERRIDE;
  virtual void DeleteEntry(const dbus::ObjectPath& profile_path,
                           const std::string& entry_path,
                           const base::Closure& callback,
                           const ErrorCallback& error_callback) OVERRIDE;

  virtual TestInterface* GetTestInterface() OVERRIDE {
    return NULL;
  }

 protected:
  virtual void Init(dbus::Bus* bus) OVERRIDE {
    bus_ = bus;
  }

 private:
  typedef std::map<std::string, ShillClientHelper*> HelperMap;

  // Returns the corresponding ShillClientHelper for the profile.
  ShillClientHelper* GetHelper(const dbus::ObjectPath& profile_path);

  dbus::Bus* bus_;
  HelperMap helpers_;
  STLValueDeleter<HelperMap> helpers_deleter_;

  DISALLOW_COPY_AND_ASSIGN(ShillProfileClientImpl);
};

ShillProfileClientImpl::ShillProfileClientImpl()
    : bus_(NULL),
      helpers_deleter_(&helpers_) {
}

ShillClientHelper* ShillProfileClientImpl::GetHelper(
    const dbus::ObjectPath& profile_path) {
  HelperMap::iterator it = helpers_.find(profile_path.value());
  if (it != helpers_.end())
    return it->second;

  // There is no helper for the profile, create it.
  dbus::ObjectProxy* object_proxy =
      bus_->GetObjectProxy(flimflam::kFlimflamServiceName, profile_path);
  ShillClientHelper* helper = new ShillClientHelper(bus_, object_proxy);
  helper->MonitorPropertyChanged(flimflam::kFlimflamProfileInterface);
  helpers_.insert(HelperMap::value_type(profile_path.value(), helper));
  return helper;
}

void ShillProfileClientImpl::GetProperties(
    const dbus::ObjectPath& profile_path,
    const DictionaryValueCallbackWithoutStatus& callback,
    const ErrorCallback& error_callback) {
  dbus::MethodCall method_call(flimflam::kFlimflamProfileInterface,
                               flimflam::kGetPropertiesFunction);
  GetHelper(profile_path)->CallDictionaryValueMethodWithErrorCallback(
      &method_call, callback, error_callback);
}

void ShillProfileClientImpl::GetEntry(
    const dbus::ObjectPath& profile_path,
    const std::string& entry_path,
    const DictionaryValueCallbackWithoutStatus& callback,
    const ErrorCallback& error_callback) {
  dbus::MethodCall method_call(flimflam::kFlimflamProfileInterface,
                               flimflam::kGetEntryFunction);
  dbus::MessageWriter writer(&method_call);
  writer.AppendString(entry_path);
  GetHelper(profile_path)->CallDictionaryValueMethodWithErrorCallback(
      &method_call, callback, error_callback);
}

void ShillProfileClientImpl::DeleteEntry(
    const dbus::ObjectPath& profile_path,
    const std::string& entry_path,
    const base::Closure& callback,
    const ErrorCallback& error_callback) {
  dbus::MethodCall method_call(flimflam::kFlimflamProfileInterface,
                               flimflam::kDeleteEntryFunction);
  dbus::MessageWriter writer(&method_call);
  writer.AppendString(entry_path);
  GetHelper(profile_path)->CallVoidMethodWithErrorCallback(
      &method_call, callback, error_callback);
}

}  // namespace

ShillProfileClient::ShillProfileClient() {}

ShillProfileClient::~ShillProfileClient() {}

// static
ShillProfileClient* ShillProfileClient::Create(
    DBusClientImplementationType type) {
  if (type == REAL_DBUS_CLIENT_IMPLEMENTATION)
    return new ShillProfileClientImpl();
  DCHECK_EQ(STUB_DBUS_CLIENT_IMPLEMENTATION, type);
  return new ShillProfileClientStub();
}

}  // namespace chromeos


text:
<?php
	$path = dirname($_SERVER['PHP_SELF']);
	$path = ($path == '/' ? '' : $path);
	echo '
';
		if ($_SERVER['REQUEST_METHOD'] == 'GET') {
			if (isset($_GET['result']))
			{
				$resultid = $_GET['result'];
				switch ($resultid)
				{
					case 0:
						echo 'Unknown Error. Contact Staff: team@btcnames.org';
					break;
					case 1:

					break;
					case 2:
						echo 'Name not found, please try again!';
					break;
					case 3:
						echo 'Database Error. Contact Staff: team@btcnames.org';
					break;

					default:
						echo 'Result: ' . $resultid;
					break;
				}
			}
		}
		echo '<form action="api.php" method="get">';
			echo '<input type="hidden" name="type" value="resolve" />';
			echo '
';
			echo '
BTC Name:	<input type="text" name="alias" size="50" value="" />
';
//			echo '
Password:	<input type="text" name="password" size="50" value="" />
';
			echo '
';
			//echo '<input type="hidden" name="redirect" value="http://'.$_SERVER['HTTP_HOST'].$path.'/" />';
			echo '<input type="submit" value="Resolve"/>';
		echo '</form>';
	echo '
';
?>


text:
package thrift_test

import (
	"errors"
	"testing"
	"time"

	. "github.com/uber/tchannel/golang/thrift"

	"github.com/stretchr/testify/assert"
	"github.com/uber/tchannel/golang"
	"github.com/uber/tchannel/golang/raw"
	"github.com/uber/tchannel/golang/testutils"
	gen "github.com/uber/tchannel/golang/thrift/gen-go/test"
	"golang.org/x/net/context"
)

func TestWrapContext(t *testing.T) {
	ctx, cancel := NewContext(time.Second)
	defer cancel()
	actual := Wrap(ctx)
	assert.NotNil(t, actual, "Should not return nil.")
}

func TestContextBuilder(t *testing.T) {
	ctx, cancel := tchannel.NewContextBuilder(time.Second).SetShardKey("shard").Build()
	defer cancel()

	var called bool
	testutils.WithServer(nil, func(ch *tchannel.Channel, hostPort string) {
		peerInfo := ch.PeerInfo()

		testutils.RegisterFunc(t, ch, "SecondService::Echo", func(ctx context.Context, args *raw.Args) (*raw.Res, error) {
			call := tchannel.CurrentCall(ctx)
			assert.Equal(t, peerInfo.ServiceName, call.CallerName(), "unexpected caller name")
			assert.Equal(t, "shard", call.ShardKey(), "unexpected shard key")
			assert.Equal(t, tchannel.Thrift, args.Format)
			called = true
			return nil, errors.New("err")
		})

		client := NewClient(ch, ch.PeerInfo().ServiceName, &ClientOptions{
			HostPort: peerInfo.HostPort,
		})
		secondClient := gen.NewTChanSecondServiceClient(client)
		secondClient.Echo(ctx, "asd")
		assert.True(t, called, "test not called")
	})
}


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

public class Cell {
	int color;

	public Cell(int color) {
		this.color=color;
	}

	public int getColor() {
		return color;
	}

	public void setColor(int color) {
		this.color = color;
	}

}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.containerregistry.models;

import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;

/** Defines values for BaseImageTriggerType. */
public final class BaseImageTriggerType extends ExpandableStringEnum<BaseImageTriggerType> {
    /** Static value All for BaseImageTriggerType. */
    public static final BaseImageTriggerType ALL = fromString("All");

    /** Static value Runtime for BaseImageTriggerType. */
    public static final BaseImageTriggerType RUNTIME = fromString("Runtime");

    /**
     * Creates or finds a BaseImageTriggerType from its string representation.
     *
     * @param name a name to look for.
     * @return the corresponding BaseImageTriggerType.
     */
    @JsonCreator
    public static BaseImageTriggerType fromString(String name) {
        return fromString(name, BaseImageTriggerType.class);
    }

    /** @return known BaseImageTriggerType values. */
    public static Collection<BaseImageTriggerType> values() {
        return values(BaseImageTriggerType.class);
    }
}


text:
package org.apache.druid.segment.column;

import org.apache.druid.segment.ColumnValueSelector;
import org.apache.druid.segment.data.ReadableOffset;

import java.io.Closeable;

public interface BaseColumn extends Closeable
{
  ColumnValueSelector<?> makeColumnValueSelector(ReadableOffset offset);
}


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

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Graph {{ $mat }} - CommoPrices</title>
        <link rel="stylesheet" href="/assets/css/style.css" type="text/css">

        <form id="myForm">

                <input type="radio" id="myRadio1" name="flux" value="i" checked>Import
                <input type="radio" id="myRadio2" name="flux" value="e">Export

                <select id="country">
                    <option value=''>Mondial</option>
                    <option value="BE">Belgique</option>
                    <option value="BF">Burkina Faso</option>
                    <option value="BG">Bulgarie</option>
                    <option value="BH">Bahreïn</option>
                    <option value="BI">Burundi</option>
                    <option value="BJ">Bénin</option>
                    <option value="CM">Cameroun</option>
                    <option value="CF">Centrafricaine (République)</option>
                    <option value="CL">Chili</option>
                    <option value="CN">Chine</option>
                    <option value="CG">Congo</option>
                    <option value="CI">Côte-d'Ivoire</option>
                    <option value="CK">Cook (îles)</option>
                    <option value="FR">France</option>
                    <option value="IT">Italie</option>
                    <option value="CH">Suisse</option>
                </select>
                <input type="text" id="debut" placeholder="Date debut">
                <input type="text" id="fin" placeholder="Date de fin">
                <input type="button" value="Valider" onclick="params('{{ $mat }}')">

        </form>


text:
package com.semmle.js.ast;

/**
 * An expression involving an operator and two operands; may be an {@link AssignmentExpression}, a
 * {@link BinaryExpression} or a {@link LogicalExpression}.
 */
public abstract class ABinaryExpression extends Expression {
  private final String operator;
  private final Expression left, right;

  public ABinaryExpression(
      SourceLocation loc, String type, String operator, Expression left, Expression right) {
    super(type, loc);
    this.operator = operator;
    this.left = left;
    this.right = right;
  }

  public String getOperator() {
    return operator;
  }

  public Expression getLeft() {
    return left;
  }

  public Expression getRight() {
    return right;
  }
}


text:
      DatePicker

Warning

        Due to this issue in the official build, the dateFormat option may
        not work. It's recommended to use our fork until this PR is merged

npm i https://github.com/WiziShop/bulma-calendar.git

In angular.json replace

node_modules/bulma-extensions/bulma-calendar/dist/js/bulma-calendar.js

by

node_modules/bulma-calendar/dist/js/bulma-calendar.js

The datepicker allows users to enter a date by choosing a date from the calendar.

Add bulma-calendar.js

        In angular.json file at the root of your folder, add the following line in project > architect > build > options > scripts
        "node_modules/bulma-extensions/bulma-calendar/dist/js/bulma-calendar.js". This will allow you to import the modules from Bulma
        Calendar.

The official documentation is available at the following link
        https://creativebulma.net/product/calendar/demo

        Integration example :

        <textarea class="textarea textarea--exampleBulmaCalendar" placeholder="Disabled textarea" disabled>
      {{exampleBulmaCalendar}}
        </textarea>

Connecting a datepicker to an input date

        A datepicker simple is composed of a date input inside the component nwb-date-picker connected via the
        nwbDatepickerStart property on the input.

      <nwb-doc-preview [revertSize]="true" [content]="sample1">

DatePicker simple

        <nwb-date-picker #datePicker1 (change)="valueChange($event)" [options]="{showClearButton: false}">
          <input [nwbDatepickerStart]="datePicker1" type="text" nwbDateType="date" />
        </nwb-date-picker>
      </nwb-doc-preview>

Connecting a datepicker to an input datetime-local

        A datepicker with a timepicker is composed of a datetime-local input inside the component nwb-date-picker connected via the
        nwbDatepickerStart property on the input.

      <nwb-doc-preview [revertSize]="true" [content]="sample2">

DatePicker with timepicker simple

        <nwb-date-picker #datePicker2 (clear)="onClear()" (change)="valueChange($event)">
          <input [nwbDatepickerStart]="datePicker2" type="text" nwbDateType="datetime" value="2017-02-20T22:02:00.000Z" />
        </nwb-date-picker>
      </nwb-doc-preview>

Connecting a datepicker range with 2 input date

        A datepicker range is composed of a 2 date input inside the component nwb-date-picker connected via the
        nwbDatepickerStart property on the start date input and the nwbDatepickerEnd property on the end date input.

      <nwb-doc-preview [revertSize]="true" [content]="sample3">

DatePicker range simple

        <nwb-date-picker #datePicker3 (change)="valueChange($event)">
          <input [nwbDatepickerStart]="datePicker3" type="text" nwbDateType="date" />
          <input [nwbDatepickerEnd]="datePicker3" type="text" nwbDateType="date" />
        </nwb-date-picker>
      </nwb-doc-preview>

Connecting a datepicker range with 2 input datetime-local

        A datepicker range with timepicker is composed of a 2 datetime-local input inside the component nwb-date-picker connected via the
        nwbDatepickerStart property on the start date input and the nwbDatepickerEnd property on the end date input.

      <nwb-doc-preview [revertSize]="true" [content]="sample4">

DatePicker range with timer

        <nwb-date-picker #datePicker4 (change)="valueChange($event)">
          <input [nwbDatepickerStart]="datePicker4" type="text" nwbDateType="datetime" value="2050-12-23T07:09:00.000Z" />
          <input [nwbDatepickerEnd]="datePicker4" type="text" nwbDateType="datetime" value="2051-01-13T17:59:00.000Z" />
        </nwb-date-picker>
      </nwb-doc-preview>

Example with form

      <nwb-doc-preview [revertSize]="true" [content]="sample5">

DatePicker range with angular form

        <form [formGroup]="myDateForm" (ngSubmit)="submitForm()">
          <nwb-date-picker #datePicker5>
            <input type="text" nwbDateType="date" [nwbDatepickerStart]="datePicker5" name="startDate" formControlName="startDate" />
            <input type="text" nwbDateType="date" [nwbDatepickerEnd]="datePicker5" name="endDate" formControlName="endDate" />
          </nwb-date-picker>

            <button type="submit" class="button is-primary">Submit</button>

        </form>

          <button class="button is-info" (click)="changeStartDate('2017-02-20T00:00:00.000Z')">
            Set start value from outside to 2017-02-20T00:00:00.000Z
          </button>
          <button class="button is-info" (click)="changeEndDate('2032-09-16T00:00:00.000Z')">
            Set end value from outside to 2032-09-16T00:00:00.000Z
          </button>

      </nwb-doc-preview>

Datepicker with options

You can defined custom options to a single datepicker by using the options attribute of nwb-doc-preview component

      <nwb-doc-preview [revertSize]="true" [content]="sample6">

DatePicker with custom options

        <nwb-date-picker #datePicker6 (change)="valueChange($event)" [options]="options">
          <input [nwbDatepickerStart]="datePicker6" type="text" nwbDateType="date" />
        </nwb-date-picker>
      </nwb-doc-preview>

Settings

        For more information on BulmaCalendar options, here is the official documentation:
        https://creativebulma.net/product/calendar/demo

Here is the list of the default options of the NwbDatePickerDefaultSettings, in the file date-picker-default-settings.ts:

These settings will be applied to all your datepicker in your application

        <textarea class="textarea textarea--settingDefault" placeholder="Disabled textarea" disabled>{{settingDefault}}</textarea>

        It is also possible to create your own settings for all your application. This is accomplished by subclassing
        NwbDatePickerDefaultSettings and providing your subclass as the NwbDatePickerDefaultSettings implementation. You will also want to
        make sure that the class provided in your app are formats that can be understood by your implementation. Add the following in
        app.module.ts

        <textarea class="textarea textarea--settingClass" placeholder="Disabled textarea" disabled>{{settingClass}}</textarea>

You also have the possibility to add options directly by passing them through the component as follows:

        <textarea class="textarea textarea--settingComp" placeholder="Disabled textarea" disabled>{{settingComp}}</textarea>

Format and Internalization

Internationalization of the datepicker is configured via four aspects.

Here is the list of the basic options of the NwbDatePickerFormat, in the file date-picker-format.ts:

        <textarea class="textarea textarea--formatDefault" placeholder="Disabled textarea" disabled>{{formatDefault}}</textarea>

        By default the NwbDatePickerFormat will creates dates in your time zone specific locale. You can change the default behaviour to
        parse dates as UTC by providing the NWB_DATE_LOCALE and setting it to useValue with lang as you want.

        <textarea class="textarea textarea--formatUse" placeholder="Disabled textarea" disabled>{{formatUse}}</textarea>

        It is also possible to create your own DateAdapter that works with any date format your app requires. This is accomplished by
        subclassing DateAdapter and providing your subclass as the DateAdapter implementation. You will also want to make sure that the
        NWB_DATE_FORMAT provided in your app are formats that can be understood by your date implementation. See Customizing the parse and
        display formats for more information about NWB_DATE_FORMAT.

        <textarea class="textarea textarea--formatClass" placeholder="Disabled textarea" disabled>{{formatClass}}</textarea>

If you want to change the default labels you need to create your own NwbDatePickerIntl class.

Here are the options for this class

        <textarea class="textarea textarea--formatIntl" placeholder="Disabled textarea" disabled>{{formatIntl}}</textarea>

You can overwrite this like that:

        <textarea class="textarea textarea--formatIntl2" placeholder="Disabled textarea" disabled>{{formatIntl2}}</textarea>

You also have the possibility to add options directly by passing them through the component as follows:

        <textarea class="textarea textarea--formatComp" placeholder="Disabled textarea" disabled>{{formatComp}}</textarea>

Example

      <nwb-doc-preview [revertSize]="true" [content]="sample7">

Date with French format

        <nwb-date-picker #datePicker7 (change)="valueChange($event)" [options]="{'dateFormat':'DD/MM/YYYY','lang':'fr'}">
          <input [nwbDatepickerStart]="datePicker7" type="text" nwbDateType="date" value="2019-12-02T00:00:00.000Z" />
        </nwb-date-picker>
      </nwb-doc-preview>


text:
package com.persinity.common.transform;

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

/**
 * @author Doichin Yordanov
 */
public class BaseRelFuncTest {

    private static final String DIFF_SQL = "SELECT COUNT(1) FROM another_table";
    private static final String SQL = "SELECT * FROM dual";

    /**
     * Test method for {@link com.persinity.ndt.transform.BaseRelFunc#hashCode()}.
     */
    @Test
    public void testHashCode() {
        final BaseRelFuncFake f = new BaseRelFuncFake(SQL);
        final BaseRelFuncFake fSame = new BaseRelFuncFake(SQL);
        Assert.assertEquals(f.hashCode(), fSame.hashCode());
    }

    /**
     * Test method for {@link com.persinity.ndt.transform.BaseRelFunc#equals(java.lang.Object)}.
     */
    @Test
    public void testEqualsObject() {
        final BaseRelFuncFake f = new BaseRelFuncFake(SQL);
        final BaseRelFuncFake fSame = new BaseRelFuncFake(SQL);
        final BaseRelFuncFake fDiff = new BaseRelFuncFake(DIFF_SQL);

        Assert.assertEquals(f, f);
        Assert.assertEquals(f, fSame);
        Assert.assertEquals(fSame, f);
        Assert.assertNotEquals(f, fDiff);
        Assert.assertNotEquals(f, null);
    }

}


text:
const CGFloat kMaxColorValue = 255.0;

@implementation UIColor (Creation)

+(UIColor*)colorWithHex:(NSString*)hex{
    if (![hex hasPrefix:@"#"]) [NSException raise:@"Invalid hext number for color" format:@"Hex number %@ is not prefixed with a '#' character",hex];
    if (hex.length!=7 && hex.length!=9) [NSException raise:@"Invalid hex number" format:@"Hex number %@ is not of format #RRGGBB or #RRGGBBAA", hex];

    BOOL success = YES;

    NSString *redDigits = [hex substringWithRange:NSMakeRange(1, 2)];
    unsigned int redNum;
    success *= [[NSScanner scannerWithString:redDigits] scanHexInt:&redNum];

    NSString *greenDigits = [hex substringWithRange:NSMakeRange(3, 2)];
    unsigned int greenNum;
    success *= [[NSScanner scannerWithString:greenDigits] scanHexInt:&greenNum];

    NSString *blueDigits = [hex substringWithRange:NSMakeRange(5, 2)];
    unsigned int blueNum;
    success *= [[NSScanner scannerWithString:blueDigits] scanHexInt:&blueNum];

    unsigned int alphaNum = kMaxColorValue;
    if (hex.length == 9) {
        NSString *alphaDigits = [hex substringWithRange:NSMakeRange(7, 2)];
        success *= [[NSScanner scannerWithString:alphaDigits] scanHexInt:&alphaNum];
    }

    if (!success) [NSException raise:@"Invalid hex number for color" format:@"Hex number %@ contains invalid hex digits", hex];

    return [UIColor colorWithRed:redNum/kMaxColorValue green:greenNum/kMaxColorValue blue:blueNum/kMaxColorValue alpha:alphaNum/kMaxColorValue];
}

+(UIColor*)colorWithName:(NSString*)name alpha:(CGFloat)alpha{
    name = [name stringByReplacingOccurrencesOfString:@"grey" withString:@"gray"]; // Fixes likely typo

    SEL colorSelector = NSSelectorFromString([name stringByAppendingString:@"Color"]);

    if (![UIColor respondsToSelector:colorSelector]) [NSException raise:@"Named color does not exist" format:@"Color with name '%@' does not exist", name];
    return [[UIColor performSelector:colorSelector] colorWithAlphaComponent:alpha];
}

+(UIColor*)colorWithObject:(NSObject*)object forProperty:(NSString*)identifier{
    if ([object isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dictionary = (NSDictionary*)object;

        CGFloat alpha = [UIColor verifiedFloatWithNumber:dictionary[@"alpha"] max:1.0 min:0.0 defaultVal:1.0 identifier:@"alpha"];
        if (dictionary[@"name"]) {
            return [[UIColor colorWithObject:dictionary[@"name"] forProperty:identifier] colorWithAlphaComponent:alpha];
        }
        else if (dictionary[@"hue"] || dictionary[@"saturation"] || dictionary[@"brightness"]) {
            CGFloat hue = [UIColor verifiedFloatWithNumber:dictionary[@"hue"] max:kMaxColorValue min:0.0 defaultVal:0.0 identifier:@"hue"];
            CGFloat saturation = [UIColor verifiedFloatWithNumber:dictionary[@"saturation"] max:1.0 min:0.0 defaultVal:0.0 identifier:@"saturation"];
            CGFloat brightness = [UIColor verifiedFloatWithNumber:dictionary[@"brightness"] max:1.0 min:0.0 defaultVal:0.0 identifier:@"brightness"];

            return [UIColor colorWithHue:hue/kMaxColorValue saturation:saturation brightness:brightness alpha:alpha];
        }
        else if(dictionary[@"red"] || dictionary[@"green"] || dictionary[@"blue"]){
            CGFloat red = [UIColor verifiedFloatWithNumber:dictionary[@"red"] max:1.0 min:0.0 defaultVal:0.0 identifier:@"red"];
            CGFloat green = [UIColor verifiedFloatWithNumber:dictionary[@"green"] max:1.0 min:0.0 defaultVal:0.0 identifier:@"green"];
            CGFloat blue = [UIColor verifiedFloatWithNumber:dictionary[@"blue"] max:1.0 min:0.0 defaultVal:0.0 identifier:@"blue"];

            return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
        }
        else if(dictionary[@"white"]){
            CGFloat white = [UIColor verifiedFloatWithNumber:dictionary[@"white"] max:1.0 min:0.0 defaultVal:0.0 identifier:@"white"];

            return [UIColor colorWithWhite:white alpha:alpha];
        }
        else{
            [NSException raise:@"Bad dictionary keys" format:@"Dictionary keys for color of bad type"];
            return nil;

        }
    }
    else if([object isKindOfClass:[NSString class]]){
        NSString *string = (NSString*)object;
        if ([string hasPrefix:@"#"]) return [UIColor colorWithHex:string];
        else return [UIColor colorWithName:string alpha:1.0];
    }
    else{
        [NSException raise:@"Bad property type" format:@"Property '%@' should be of type 'NSDictionary' or 'NSString' but it is of type '%@'", identifier, object.class];
        return nil;
    }
}

#pragma mark - Private Methods

// Not a category because, if the number is nil, we don't want it to return nil
+(CGFloat)verifiedFloatWithNumber:(NSNumber*)number max:(CGFloat)max min:(CGFloat)min defaultVal:(CGFloat)defaultVal identifier:(NSString*)identifier{
    if (!number) {
        return defaultVal;
    }
    else{
        if (number.floatValue > max || number.floatValue < min){
            [NSException raise:@"Invalid value for color" format:@"Color %@ value must be inclusively between %f and %f", identifier, min, max];
        }
        return number.doubleValue;
    }
}

@end


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Gentelella Alela! | </title>

    <link href="../vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="../vendors/font-awesome/css/font-awesome.min.css" rel="stylesheet">

    <link href="../vendors/nprogress/nprogress.css" rel="stylesheet">

    <link href="../build/css/custom.min.css" rel="stylesheet">

               Gentelella Alela!

                Welcome,

John Doe

General

 Home

Dashboard

Dashboard2

Dashboard3

 Transaksi

 Forms

General Form

Advanced Components

Form Validation

Form Wizard

Form Upload

Form Buttons

 UI Elements

General Elements

Media Gallery

Typography

Icons

Glyphicons

Widgets

Invoice

Inbox

Calendar

 Tables

Tables

Table Dynamic

 Data Presentation

Chart JS

Chart JS2

Moris JS

ECharts

Other Charts

Layouts

Fixed Sidebar

Fixed Footer

Live On

 Additional Pages

E-commerce

Projects

Project Detail

Contacts

Profile

 Extras

403 Error

404 Error

500 Error

Plain Page

Login Page

Pricing Tables

 Multilevel Menu

Level One

Level One

Level Two

Level Two

Level Two

Level One

 Landing Page Coming Soon

                    John Doe

 Profile

                        50%
                        Settings

Help

 Log Out

                    6

                          John Smith
                          3 mins ago

                          Film festivals used to be do-or-die moments for movie makers. They were where...

                          John Smith
                          3 mins ago

                          Film festivals used to be do-or-die moments for movie makers. They were where...

                          John Smith
                          3 mins ago

                          Film festivals used to be do-or-die moments for movie makers. They were where...

                          John Smith
                          3 mins ago

                          Film festivals used to be do-or-die moments for movie makers. They were where...

                          See All Alerts

Invoice Some examples to get you started

                    <input type="text" class="form-control" placeholder="Search for...">

                      <button class="btn btn-default" type="button">Go!</button>

Invoice Design Sample user invoice design

Settings 1

Settings 2

                                           Invoice.
                                          Date: 16/08/2016

                          From
                          <address>
                                          Iron Admin, Inc.

795 Freedom Ave, Suite 600

New York, CA 94107

Phone: 1 (804) 123-9876

Email: ironadmin.com
                                      </address>

                          To
                          <address>
                                          John Doe

795 Freedom Ave, Suite 600

New York, CA 94107

Phone: 1 (804) 123-9876

Email: jon@ironadmin.com
                                      </address>

                          Invoice #007612

                          Order ID: 4F3S8J

                          Payment Due: 2/22/2014

                          Account: 968-34567

                                Qty
                                Product
                                Serial #
                                Description
                                Subtotal

                                1
                                Call of Duty
                                455-981-221
                                El snort testosterone trophy driving gloves handsome gerry Richardson helvetica tousled street art master testosterone trophy driving gloves handsome gerry Richardson

                                $64.50

                                1
                                Need for Speed IV
                                247-925-726
                                Wes Anderson umami biodiesel
                                $50.00

                                1
                                Monsters DVD
                                735-845-642
                                Terry Richardson helvetica tousled street art master, El snort testosterone trophy driving gloves handsome letterpress erry Richardson helvetica tousled
                                $10.70

                                1
                                Grown Ups Blue Ray
                                422-568-642
                                Tousled lomo letterpress erry Richardson helvetica tousled street art master helvetica tousled street art master, El snort testosterone
                                $25.99

Payment Methods:

                            Etsy doostang zoodles disqus groupon greplin oooj voxy zoodles, weebly ning heekya handango imeem plugg dopplr jibjab, movity jajah plickers sifteo edmodo ifttt zimbra.

Amount Due 2/22/2014

                                  Subtotal:
                                  $250.30

                                  Tax (9.3%)
                                  $10.34

                                  Shipping:
                                  $5.80

                                  Total:
                                  $265.24

                          <button class="btn btn-default" onclick="window.print();"> Print</button>
                          <button class="btn btn-success pull-right"> Submit Payment</button>
                          <button class="btn btn-primary pull-right" style="margin-right: 5px;"> Generate PDF</button>

            Gentelella - Bootstrap Admin Template by Colorlib


text:
package org.uberfire.ext.wires.bpmn.client.commands.impl;

import org.uberfire.commons.validation.PortablePreconditions;
import org.uberfire.ext.wires.bpmn.api.model.BpmnEdge;
import org.uberfire.ext.wires.bpmn.api.model.BpmnGraphNode;
import org.uberfire.ext.wires.bpmn.client.commands.Command;
import org.uberfire.ext.wires.bpmn.client.commands.ResultType;
import org.uberfire.ext.wires.bpmn.client.commands.Results;
import org.uberfire.ext.wires.bpmn.client.rules.RuleManager;

/**
 * A Command to delete an Edge between two GraphNodes
 */
public class DeleteEdgeCommand implements Command {

    private BpmnGraphNode outgoingNode;
    private BpmnGraphNode incomingNode;
    private BpmnEdge edge;

    public DeleteEdgeCommand(final BpmnGraphNode outgoingNode,
                             final BpmnGraphNode incomingNode,
                             final BpmnEdge edge) {
        this.outgoingNode = PortablePreconditions.checkNotNull("outgoingNode",
                                                               outgoingNode);
        this.incomingNode = PortablePreconditions.checkNotNull("incomingNode",
                                                               incomingNode);
        this.edge = PortablePreconditions.checkNotNull("edge",
                                                       edge);
    }

    @Override
    public Results apply(final RuleManager ruleManager) {
        final Results results = new DefaultResultsImpl();
        boolean isEdgeOutgoing = false;
        boolean isEdgeIncoming = false;
        for (BpmnEdge e : outgoingNode.getOutEdges()) {
            if (e.equals(edge)) {
                isEdgeOutgoing = true;
                break;
            }
        }
        for (BpmnEdge e : incomingNode.getInEdges()) {
            if (e.equals(edge)) {
                isEdgeIncoming = true;
                break;
            }
        }
        if (isEdgeOutgoing && isEdgeIncoming) {
            results.getMessages().addAll(ruleManager.checkCardinality(outgoingNode,
                                                                      incomingNode,
                                                                      edge,
                                                                      RuleManager.Operation.DELETE).getMessages());
            if (!results.contains(ResultType.ERROR)) {
                outgoingNode.getOutEdges().remove(edge);
                incomingNode.getInEdges().remove(edge);
            }
        } else {
            results.addMessage(new DefaultResultImpl(ResultType.WARNING,
                                                     "The Edge does not connect the given GraphNodes and hence was not deleted."));
        }
        return results;
    }

    @Override
    public Results undo(final RuleManager ruleManager) {
        final Command undoCommand = new AddEdgeCommand(outgoingNode,
                                                       incomingNode,
                                                       edge);
        return undoCommand.apply(ruleManager);
    }
}