text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;
using System.Net.Http.Headers;
using BlueYonder.Companion.Entities;

namespace BlueYonder.ReservationManager.Controllers
{
    public class ReservationsController : Controller
    {
        string _companionService = WebConfigurationManager.AppSettings["webapi:BlueYonderCompanionService"];

        public ActionResult Index()
        {
            IEnumerable<TravelerDTO> travelers = null;
            using (var proxy = new HttpClient() { BaseAddress = new Uri(_companionService) })
            {
                travelers = proxy.GetAsync("Travelers").Result.Content.
                    ReadAsAsync<IEnumerable<TravelerDTO>>().Result;
            }
            return View(travelers);
        }

        public PartialViewResult Reservations(int travelerId)
        {
            IEnumerable<ReservationDTO> reservations = null;
            using (var proxy = new HttpClient() { BaseAddress = new Uri(_companionService) })
            {
                TravelerDTO traveler = proxy.GetAsync("travelers/" + travelerId).Result.Content.
                    ReadAsAsync<TravelerDTO>().Result;

                reservations = proxy.GetAsync("travelers/" + travelerId + "/reservations").Result.Content.
                    ReadAsAsync<IEnumerable<ReservationDTO>>().Result;

                ViewBag.UserId = traveler.TravelerUserIdentity;
            }

            return PartialView(reservations);
        }

        public ActionResult Approve(int id, string userId)
        {
            using (var proxy = new HttpClient() { BaseAddress = new Uri(_companionService) })
            {
                TripDTO trip = proxy.GetAsync("Trips/" + id).Result.Content.ReadAsAsync<TripDTO>().Result;
                if (trip.Status == FlightStatus.StandBy)
                {
                    trip.Status = FlightStatus.Confirmed;

                    proxy.PutAsJsonAsync("Trips/" + id, trip).Wait();

                    // TODO: Exercise 2: Task 3i: Notify the client about the update using service bus topics
                    NotifyTraveler(trip, userId, "ReservationConfirmed");
                }
            }
            return Redirect("/Reservations");
        }

        public ActionResult UpgradeClass(int id, string userId, SeatClass newClass)
        {
            using (var proxy = new HttpClient() { BaseAddress = new Uri(_companionService) })
            {
                TripDTO trip = proxy.GetAsync("Trips/" + id).Result.Content.ReadAsAsync<TripDTO>().Result;

                if ((trip.Class == SeatClass.Economy && newClass == SeatClass.Business) ||
                    (trip.Class == SeatClass.Business && newClass == SeatClass.First))
                {
                    trip.Class = newClass;

                    proxy.PutAsJsonAsync("Trips/" + id, trip).Wait();

                    // TODO: Exercise 2: Task 3i: Notify the client about the update using service bus topics
                    NotifyTraveler(trip, userId, "Upgrade");
                }
            }
            return Redirect("/Reservations");
        }

        private void NotifyTraveler(TripDTO trip, string travelerUserId, string updateType)
        {
            // TODO: Exercise 2: Task 3a: Connect to the service bus namespace

            // Create the topic if it does not exist already
            string connectionString =
                WebConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"];

            string topicName =
                WebConfigurationManager.AppSettings["Microsoft.ServiceBus.TopicName"];

            var namespaceManager =
                NamespaceManager.CreateFromConnectionString(connectionString);

            // TODO: Exercise 2: Task 3b: Each client requires a different subscription so they
            // will only get their own updates. Create a variable for the subscription name
            // and set its value to the id of the client that created the order

            string travelerSubscriptionName = travelerUserId;

            // TODO: Exercise 2: Task 3c: Each subsription is for a different client,
            // create a filter that looks for a message sent for the specific client
            CorrelationFilter travelerFilter = new CorrelationFilter(travelerSubscriptionName);

            // TODO: Exercise 2: Task 3d: Verify the subscription exists, and create it if it doesn't
            if (!namespaceManager.SubscriptionExists(topicName, travelerSubscriptionName))
            {
                namespaceManager.CreateSubscription(topicName, travelerSubscriptionName, travelerFilter);
            }

            // TODO: Exercise 2: Task 3e: Connect to the topic
            TopicClient Client = TopicClient.CreateFromConnectionString(connectionString, topicName);

            // TODO: Exercise 2: Task 3f: Create the brokered message
            BrokeredMessage message = new BrokeredMessage(trip);

            // TODO: Exercise 2: Task 3g: Set the ClientId property so the message will be delivered
            // to the required subscription, and set the UpdateType property to reflect the
            // reason this message was sent to the client

            // Set additional custom app-specific property
            message.CorrelationId = travelerSubscriptionName;
            message.Properties["UpdateType"] = updateType;

            // TODO: Exercise 2: Task 3h: Send the message to the topic
            Client.Send(message);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Datto\JsonRpc;

/**
 * Class Error
 * @package Datto\JsonRpc
 *
 * A description of an error that occurred on the server
 *
 * @link http://www.jsonrpc.org/specification#error_object
 */
class Error
{
    private $message;

    private $code;

    private $data;

    /**
     * @param $message
      * Short description of the error that occurred. This message SHOULD
      * be limited to a single, concise sentence.
     *
     * @param int $code
     * Integer identifying the type of error that occurred.
     *
     * @param null|boolean|integer|float|string|array $data
      * An optional primitive value that contains additional information about
     * the error.
     */
    public function __construct($message, $code, $data)
    {
        $this->message = $message;
        $this->code = $code;
        $this->data = $data;
    }

    /**
     * @return mixed
     */
    public function getCode()
    {
        return $this->code;
    }

    public function getMessage()
    {
        return $this->message;
    }

    public function getData()
    {
        return $this->data;
    }
}


text:
package neetlisp.fns.core;

import neetlisp.Context;
import neetlisp.Fn;
import neetlisp.FnMeta;
import neetlisp.Number;
import neetlisp.numbers.NumChar;

public class FnChar extends Fn
{
    public FnChar(final Context context)
    {
        super(context, new FnMeta("core/char",
                "(num)\n" +
                " Returns num as a char",
                1, false, 0));
    }

    public Object eval(Object num)
    {
        return NumChar.toThis((Number)num);
    }

    @Override
    public Object invoke(Object ... objects)
    {
        this.assureArguments(objects.length);
        return this.eval(objects[0]);
    }
}


text:
import enums = require("ui/enums");
import definitios = require("ui/styling/font");
import converters = require("ui/styling/converters");

export class Font implements definitios.Font {
    public static default = undefined;

    private _fontFamily: string;
    private _fontStyle: string;
    private _fontWeight: string;
    private _fontSize: number;

    get fontFamily(): string {
        return this._fontFamily;
    }
    set fontFamily(value: string) {
        throw new Error("fontFamily is read-only");
    }

    get fontStyle(): string {
        return this._fontStyle;
    }
    set fontStyle(value: string) {
        throw new Error("fontStyle is read-only");
    }

    get fontWeight(): string {
        return this._fontWeight;
    }
    set fontWeight(value: string) {
        throw new Error("fontWeight is read-only");
    }

    get fontSize(): number {
        return this._fontSize;
    }
    set fontSize(value: number) {
        throw new Error("fontSize is read-only");
    }

    get isBold(): boolean {
        return this._fontWeight.toLowerCase() === enums.FontWeight.bold;;
    }
    set isBold(value: boolean) {
        throw new Error("isBold is read-only");
    }

    get isItalic(): boolean {
        return this._fontStyle.toLowerCase() === enums.FontStyle.italic;;
    }
    set isItalic(value: boolean) {
        throw new Error("isItalic is read-only");
    }

    constructor(family: string, size: number, style: string, weight: string) {
        this._fontFamily = family;
        this._fontSize = size;
        this._fontStyle = style;
        this._fontWeight = weight;
    }

    public getAndroidTypeface(): android.graphics.Typeface {
        return undefined;
    }

    public getUIFont(defaultFont: UIFont): UIFont {
        return undefined;
    }

    public withFontFamily(family: string): Font {
        throw new Error("This should be called on the derived class");
    }

    public withFontStyle(style: string): Font {
        throw new Error("This should be called on the derived class");
    }

    public withFontWeight(weight: string): Font {
        throw new Error("This should be called on the derived class");
    }

    public withFontSize(size: number): Font {
        throw new Error("This should be called on the derived class");
    }

    public static equals(value1: Font, value2: Font): boolean {
        // both values are falsy
        if (!value1 && !value2) {
            return true;
        }

        // only one is falsy
        if (!value1 || !value2) {
            return false;
        }

        return value1.fontFamily === value2.fontFamily &&
            value1.fontSize === value2.fontSize &&
            value1.fontStyle === value2.fontStyle &&
            value1.fontWeight === value2.fontWeight;
    }

    public static parse(cssValue: string): Font {
        var parsed = parseFont(cssValue);
        var size = converters.fontSizeConverter(parsed.fontSize);
        size = !!size ? size : undefined;

        return new Font(parsed.fontFamily, size, parsed.fontStyle, parsed.fontWeight);
    }
}

export function parseFontFamily(value: string): Array<string> {
    var result = new Array<string>();
    if (!value) {
        return result;
    }

    var split = value.split(",");
    for (var i = 0; i < split.length; i++) {
        var str = split[i].trim().replace(/['"]+/g, '');
        if (str) {
            result.push(str);
        }
    }
    return result;
}

export module genericFontFamilies {
    export var serif = "serif";
    export var sansSerif = "sans-serif";
    export var monospace = "monospace";
}

var styles = new Set();
["italic", "oblique"].forEach((val, i, a) => styles.add(val));
var weights = new Set();
["bold", "bolder", "lighter", "100", "200", "300", "400", "500", "600", "700", "800", "900"].forEach((val, i, a) => weights.add(val));

interface ParsedFont {
    fontStyle?: string;
    fontVariant?: string;
    fontWeight?: string,
    lineHeight?: string,
    fontSize?: string,
    fontFamily?: string
}

function parseFont(fontValue: string): ParsedFont {
    var result: ParsedFont = {
        fontStyle: "normal",
        fontVariant: "normal",
        fontWeight: "normal",
    }

    var parts = fontValue.split(/\s+/);
    var part: string;
    while (part = parts.shift()) {
        if (part === "normal") {
            // nothing to do here
        }
        else if (part === "small-caps") {
            // The only supported font variant in shorthand font
            result.fontVariant = part;
        }
        else if (styles.has(part)) {
            result.fontStyle = part
        }
        else if (weights.has(part)) {
            result.fontWeight = part;
        }
        else if (!result.fontSize) {
            var sizes = part.split("/");
            result.fontSize = sizes[0];
            result.lineHeight = sizes.length > 1 ? sizes[1] : undefined;
        }
        else {
            result.fontFamily = part;
            if (parts.length) {
                result.fontFamily += " " + parts.join(" ");
            }
            break;
        }
    }

    return result;
}


text:
<?php

$lang['jb_blankpage_message'] = "The Upload process had not started, or started, but had not finished yet, or your browser could not reach the remote server.";

/* End of file jbstrings_lang.php */


text:
/**
 * @author Gulfem
 */
package edu.uci.python.nodes;

import com.oracle.truffle.api.frame.*;

/**
 * @author Gulfem
 */

public final class ZippyTranslationErrorNode extends PNode {

    public static final String MESSAGE = "ZippyTranslationError";

    private static ZippyTranslationErrorNode instance = new ZippyTranslationErrorNode();

    private ZippyTranslationErrorNode() {
    }

    public static ZippyTranslationErrorNode getInstance() {
        return instance;
    }

    @Override
    public Object execute(VirtualFrame frame) {
        return MESSAGE;
    }

}


text:
#ifndef _IRTKGAUSSIANNOISEWITHPADDING_H

#define _IRTKGAUSSIANNOISEWITHPADDING_H

#include <irtkGaussianNoise.h>

/**
 * Class for adding Gaussian noise to images which are padded
 *
 * This class implements a filter for adding Gaussian noise to images which
 * are padded.
 *
 */

template <class VoxelType> class irtkGaussianNoiseWithPadding : public irtkGaussianNoise<VoxelType>
{

protected:
  /// Returns the name of the class.
  virtual const char* NameOfClass();

  /// The padding value.
  VoxelType _PaddingValue;

public:

  // Default constructor
  irtkGaussianNoiseWithPadding();

  /** Constructor.  Sets mean value and standard deviation of the noise
   *  distribution, the padding value, and the image range.
   */
  irtkGaussianNoiseWithPadding(double Mean, double Sigma, VoxelType PaddingValue, VoxelType MinVal, VoxelType MaxVal);

  /// Destructor (empty).
  ~irtkGaussianNoiseWithPadding() {};

  /// Set padding value
  SetMacro(PaddingValue, VoxelType);

  /// Get padding value
  GetMacro(PaddingValue, VoxelType);

  /// Adds noise to input image.
  virtual double Run(int, int, int, int);

};

#endif


text:
package com.phoenixnap.oss.ramlplugin.raml2code.raml.raml10;

import static com.phoenixnap.oss.ramlplugin.raml2code.SrpMatchers.emptyMap;
import static com.phoenixnap.oss.ramlplugin.raml2code.SrpMatchers.mapWithSize;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.anything;
import static org.hamcrest.Matchers.emptyIterable;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.everyItem;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isA;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.hamcrest.Matchers.notNullValue;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.junit.BeforeClass;
import org.junit.Test;
import org.raml.v2.api.model.v10.datamodel.ArrayTypeDeclaration;
import org.raml.v2.api.model.v10.datamodel.IntegerTypeDeclaration;
import org.raml.v2.api.model.v10.datamodel.ObjectTypeDeclaration;
import org.raml.v2.api.model.v10.datamodel.StringTypeDeclaration;

import com.phoenixnap.oss.ramlplugin.raml2code.exception.InvalidRamlResourceException;
import com.phoenixnap.oss.ramlplugin.raml2code.raml.RamlActionType;
import com.phoenixnap.oss.ramlplugin.raml2code.raml.RamlDataType;
import com.phoenixnap.oss.ramlplugin.raml2code.raml.RamlDocumentationItem;
import com.phoenixnap.oss.ramlplugin.raml2code.raml.RamlMimeType;
import com.phoenixnap.oss.ramlplugin.raml2code.raml.RamlResource;
import com.phoenixnap.oss.ramlplugin.raml2code.raml.RamlRoot;
import com.phoenixnap.oss.ramlplugin.raml2code.rules.AbstractRuleTestBase;
import com.phoenixnap.oss.ramlplugin.raml2code.rules.RamlLoader;

/**
 * @author aweisser
 */
public class RJP10V2RamlRootTest extends AbstractRuleTestBase {

	private static RamlRoot ramlRoot, ramlRootEmptyValues, ramlSchemaRoot;

	@BeforeClass
	public static void initRamlRoot() throws InvalidRamlResourceException {
		ramlRoot = RamlLoader.loadRamlFromFile(AbstractRuleTestBase.RESOURCE_BASE + "raml-root-test-v10.raml");
		ramlRootEmptyValues = RamlLoader.loadRamlFromFile(AbstractRuleTestBase.RESOURCE_BASE + "raml-root-test-emptyValues-v10.raml");
		ramlSchemaRoot = RamlLoader.loadRamlFromFile(AbstractRuleTestBase.RESOURCE_BASE + "raml-root-schemas-test-v10.raml");
	}

	@Test
	public void factoryShouldCreateRamlRootFromFile() {
		assertThat(ramlRoot, is(notNullValue()));
		assertThat(ramlRootEmptyValues, is(notNullValue()));
	}

	@Test
	public void ramlRootShouldReflectBaseUri() {
		assertThat(ramlRoot.getBaseUri(), equalTo("api"));
	}

	@Test
	public void ramlRootShouldHandleEmptyBaseUriWithoutException() {
		assertThat(ramlRootEmptyValues.getBaseUri(), isEmptyOrNullString());
	}

	@Test
	public void ramlRootShouldReflectMediaType() {
		assertThat(ramlRoot.getMediaType(), equalTo("application/json"));
	}

	@Test
	public void ramlRootShouldHandleEmptyMediaTypeWithoutException() {
		assertThat(ramlRootEmptyValues.getMediaType(), isEmptyOrNullString());
	}

	@Test
	public void ramlRootShouldReflectSchemas() {
		Map<String, String> personSchema = ramlSchemaRoot.getSchemas().get(0);
		assertThat(personSchema, notNullValue());
		assertThat(personSchema.keySet().iterator().next(), equalTo("person"));
		assertThat(personSchema.values().iterator().next(), startsWith("{"));
	}

	@Test
	public void ramlRootShouldReflectDataTypes() {
		Map<String, RamlDataType> personType = ramlRoot.getTypes();

		ObjectTypeDeclaration personDataType = (ObjectTypeDeclaration) personType.get("Person").getType();

		assertThat(personDataType.displayName().value(), equalTo("Person"));
		assertThat(personDataType.type(), equalTo("object"));

		StringTypeDeclaration testXProp = (StringTypeDeclaration) personDataType.properties().get(0);
		assertThat(testXProp.displayName().value(), equalTo("testX"));
		assertThat(testXProp.defaultValue(), equalTo("def_value"));
		assertThat(testXProp.minLength(), equalTo(3));
		assertThat(testXProp.maxLength(), equalTo(10));

		ArrayTypeDeclaration testY = (ArrayTypeDeclaration) personDataType.properties().get(1);
		assertThat(testY.description().value(), equalTo("array attribute"));
		assertThat(testY.example().value(), endsWith("[\n\"a\",\n\"b\"\n]"));
		assertThat(testY.items().type(), equalTo("string"));
		assertThat(testY.minItems(), equalTo(2));
		assertThat(testY.maxItems(), equalTo(5));

		ObjectTypeDeclaration managerDataType = (ObjectTypeDeclaration) personType.get("Manager").getType();
		assertThat(managerDataType.type(), equalTo("Person"));

		ArrayTypeDeclaration personsDataType = (ArrayTypeDeclaration) personType.get("Persons").getType();
		assertThat(personsDataType.type(), equalTo("array"));
		assertThat(personsDataType.items().type(), equalTo("Person"));
	}

	@Test
	public void ramlRootShouldReflectDataTypesFromLibraries() {
		Map<String, RamlDataType> dataTypes = ramlRoot.getTypes();

		ObjectTypeDeclaration personDataType = (ObjectTypeDeclaration) dataTypes.get("Song").getType();

		assertThat(personDataType.displayName().value(), equalTo("Song"));
		assertThat(personDataType.type(), equalTo("object"));

		StringTypeDeclaration title = (StringTypeDeclaration) personDataType.properties().get(0);
		assertThat(title.displayName().value(), equalTo("title"));
		assertThat(title.example().value(), equalTo("Smells Like Teen Spirit"));
		assertThat(title.minLength(), equalTo(5));
		assertThat(title.maxLength(), equalTo(999));

		StringTypeDeclaration artist = (StringTypeDeclaration) personDataType.properties().get(1);
		assertThat(artist.name(), equalTo("artist"));
		assertThat(artist.required(), equalTo(true));

		ObjectTypeDeclaration album = (ObjectTypeDeclaration) personDataType.properties().get(2);
		assertThat(album.name(), equalTo("album"));
		assertThat(album.required(), equalTo(false));

		IntegerTypeDeclaration year = (IntegerTypeDeclaration) personDataType.properties().get(3);
		assertThat(year.name(), equalTo("year"));
		assertThat(year.example().value(), equalTo("1991"));
		assertThat(year.required(), equalTo(false));
	}

	@Test
	public void ramlRootShouldReflectDataTypesFromAllLibraries() {
		Map<String, RamlDataType> dataTypes = ramlRoot.getTypes();

		// this data type is defined in library that is referenced in another
		// library (and not in a root raml)
		ObjectTypeDeclaration albumDataType = (ObjectTypeDeclaration) dataTypes.get("Album").getType();

		assertThat(albumDataType.displayName().value(), equalTo("Album"));
		assertThat(albumDataType.type(), equalTo("object"));

		StringTypeDeclaration title = (StringTypeDeclaration) albumDataType.properties().get(0);
		assertThat(title.displayName().value(), equalTo("title"));
		assertThat(title.example().value(), equalTo("Nevermind"));
		assertThat(title.minLength(), equalTo(1));
		assertThat(title.maxLength(), equalTo(999));

		StringTypeDeclaration artist = (StringTypeDeclaration) albumDataType.properties().get(1);
		assertThat(artist.name(), equalTo("artist"));
		assertThat(artist.required(), equalTo(true));

		StringTypeDeclaration studio = (StringTypeDeclaration) albumDataType.properties().get(2);
		assertThat(studio.name(), equalTo("studio"));
		assertThat(studio.required(), equalTo(false));

		IntegerTypeDeclaration year = (IntegerTypeDeclaration) albumDataType.properties().get(3);
		assertThat(year.name(), equalTo("year"));
		assertThat(year.example().value(), equalTo("1991"));
		assertThat(year.required(), equalTo(false));
	}

	@Test
	public void ramlRootShouldHandleEmptySchemasWithoutException() {
		assertThat(ramlRootEmptyValues.getSchemas(), is(emptyIterable()));
	}

	@Test
	public void ramlRootShouldReflectToplevelResources() {
		assertThat(ramlRoot.getResources(), is(mapWithSize(4)));
		assertThat(ramlRoot.getResources().keySet(), hasItems("/persons", "/managers", "/defaultType", "/songs"));

		Iterable<Object> topLevelItems = ramlRoot.getResources().values().stream().collect(Collectors.toList());
		assertThat(topLevelItems, everyItem(is(anything())));

		Iterable<RamlResource> topLevelRamlResources = ramlRoot.getResources().values().stream().collect(Collectors.toList());
		assertThat(topLevelRamlResources, everyItem(isA(RamlResource.class)));
	}

	@Test
	public void ramlRootShouldReflectToplevelResourceByNameIgnoringSlashes() {
		// Note: The following 2 assertions were removed since they were changed
		// to maintain equivalence with the Raml08 getResource behaviour,
		// which will not return these resources if no preceding slash is
		// supplied
		// assertThat(ramlRoot.getResource("persons"), is(notNullValue()));
		// assertThat(ramlRoot.getResource("persons/"), is(notNullValue()));
		assertThat(ramlRoot.getResource("/persons"), is(notNullValue()));
		assertThat(ramlRoot.getResource("/persons/"), is(notNullValue()));
	}

	@Test
	public void ramlRootShouldReflectBodyWhenDefaultMediaTypeSet() {
		assertThat(ramlRoot.getResource("/defaultType"), is(notNullValue()));
		Map<String, RamlMimeType> body = ramlRoot.getResource("/defaultType").getAction(RamlActionType.GET).getResponses().get("200")
				.getBody();
		assertThat(body.isEmpty(), is(false));
	}

	@Test
	public void ramlRootShouldHandleEmptyToplevelResourcesWithoutException() {
		assertThat(ramlRootEmptyValues.getResources(), is(emptyMap()));
	}

	@Test
	public void factoryShouldReflectDocumentation() {
		List<RamlDocumentationItem> documentation = ((RJP10V2RamlRoot) ramlRoot).getDocumentation();

		assertThat(((RJP10V2RamlDocumentationItem) documentation.get(0)).getDocumentationItem().title().value(), equalTo("Home"));
		assertThat(((RJP10V2RamlDocumentationItem) documentation.get(0)).getDocumentationItem().content().value(),
				startsWith("Welcome to the _Sample API_ Documentation."));

		assertThat(((RJP10V2RamlDocumentationItem) documentation.get(1)).getDocumentationItem().title().value(), equalTo("Legal"));
		assertThat(((RJP10V2RamlDocumentationItem) documentation.get(1)).getDocumentationItem().content().value(),
				startsWith("CWIE (c) All Rights Reserved"));

	}

}


text:
@implementation UIView (TFAdditions)

///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGFloat)tfLeft {
    return self.frame.origin.x;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setTfLeft:(CGFloat)x {
    CGRect frame = self.frame;
    frame.origin.x = x;
    self.frame = frame;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGFloat)tfTop {
    return self.frame.origin.y;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setTfTop:(CGFloat)y {
    CGRect frame = self.frame;
    frame.origin.y = y;
    self.frame = frame;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGFloat)tfRight {
    return self.frame.origin.x + self.frame.size.width;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setTfRight:(CGFloat)right {
    CGRect frame = self.frame;
    frame.origin.x = right - frame.size.width;
    self.frame = frame;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGFloat)tfBottom {
    return self.frame.origin.y + self.frame.size.height;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setTfBottom:(CGFloat)bottom {
    CGRect frame = self.frame;
    frame.origin.y = bottom - frame.size.height;
    self.frame = frame;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGFloat)tfCenterX {
    return self.center.x;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setTfCenterX:(CGFloat)centerX {
    self.center = CGPointMake(centerX, self.center.y);
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGFloat)tfCenterY {
    return self.center.y;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setTfCenterY:(CGFloat)centerY {
    self.center = CGPointMake(self.center.x, centerY);
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGFloat)tfWidth {
    return self.frame.size.width;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setTfWidth:(CGFloat)width {
    CGRect frame = self.frame;
    frame.size.width = width;
    self.frame = frame;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGFloat)tfHeight {
    return self.frame.size.height;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setTfHeight:(CGFloat)height {
    CGRect frame = self.frame;
    frame.size.height = height;
    self.frame = frame;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGFloat)tfScreenX {
    CGFloat x = 0.0f;
    for (UIView* view = self; view; view = view.superview) {
        x += view.tfLeft;
    }
    return x;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGFloat)tfScreenY {
    CGFloat y = 0.0f;
    for (UIView* view = self; view; view = view.superview) {
        y += view.tfTop;
    }
    return y;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGFloat)tfScreenViewX {
    CGFloat x = 0.0f;
    for (UIView* view = self; view; view = view.superview) {
        x += view.tfLeft;

        if ([view isKindOfClass:[UIScrollView class]]) {
            UIScrollView* scrollView = (UIScrollView*)view;
            x -= scrollView.contentOffset.x;
        }
    }

    return x;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGFloat)tfScreenViewY {
    CGFloat y = 0;
    for (UIView* view = self; view; view = view.superview) {
        y += view.tfTop;

        if ([view isKindOfClass:[UIScrollView class]]) {
            UIScrollView* scrollView = (UIScrollView*)view;
            y -= scrollView.contentOffset.y;
        }
    }
    return y;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGRect)tfScreenFrame {
    return CGRectMake(self.tfScreenViewX, self.tfScreenViewY, self.tfWidth, self.tfHeight);
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGPoint)tfOrigin {
    return self.frame.origin;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setTfOrigin:(CGPoint)origin {
    CGRect frame = self.frame;
    frame.origin = origin;
    self.frame = frame;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGSize)tfSize {
    return self.frame.size;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setTfSize:(CGSize)size {
    CGRect frame = self.frame;
    frame.size = size;
    self.frame = frame;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGFloat)tfOrientationWidth {
    return UIInterfaceOrientationIsLandscape((UIInterfaceOrientation)TFDeviceOrientation())
    ? self.tfHeight : self.tfWidth;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGFloat)tfOrientationHeight {
    return UIInterfaceOrientationIsLandscape((UIInterfaceOrientation)TFDeviceOrientation())
    ? self.tfWidth : self.tfHeight;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIView*)descendantOrSelfWithClass:(Class)cls {
    if ([self isKindOfClass:cls])
        return self;

    for (UIView* child in self.subviews) {
        UIView* it = [child descendantOrSelfWithClass:cls];
        if (it)
            return it;
    }

    return nil;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIView*)ancestorOrSelfWithClass:(Class)cls {
    if ([self isKindOfClass:cls]) {
        return self;

    } else if (self.superview) {
        return [self.superview ancestorOrSelfWithClass:cls];

    } else {
        return nil;
    }
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)removeAllSubviews {
    while (self.subviews.count) {
        UIView* child = self.subviews.lastObject;
        [child removeFromSuperview];
    }
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGPoint)offsetFromView:(UIView*)otherView {
    CGFloat x = 0.0f, y = 0.0f;
    for (UIView* view = self; view && view != otherView; view = view.superview) {
        x += view.tfLeft;
        y += view.tfTop;
    }
    return CGPointMake(x, y);
}

@end


text:
package dev.nick.android.imageloader;

import android.support.annotation.Nullable;

import dev.nick.android.imageloader.worker.ProgressListener;

public class ProgressListenerStub<T> implements ProgressListener<T> {

    @Override
    public void onComplete(@Nullable T result) {
        // Nothing.
    }

    @Override
    public void onProgressUpdate(float progress) {
        // Nothing.
    }

    @Override
    public void onCancel() {
        // Nothing.
    }

    @Override
    public void onStartLoading() {
        // Nothing.
    }
}


text:
//dojo.require("esri.tasks.query");
//dojo.require("esri.map");
//dojo.require("dojo.data.ItemFileReadStore");
// dojo.require("dojo.store.Memory");
//dojo.require("esri.layers.FeatureLayer");
//dojo.require("dojox.grid.DataGrid");
// dojo.require("dijit.layout.BorderContainer");
//dojo.require("dijit.layout.ContentPane");

var queryTask, query;
require([
    "esri/tasks/query", "esri/tasks/QueryTask",
    "dojo/dom", "dojo/on", "dojo/domReady!",
    "dojo/store/Memory", "dojo/data/ItemFileReadStore",
    "dojox/grid//DataGrid", "dijit/layout/BorderContainer",
    "dijit/layout/ContentPane"
], function (Query, QueryTask, dom, on) {
    queryTask = new QueryTask("http://services.azgs.az.gov/ArcGIS/rest/services/aasggeothermal/AZWellHeaders/MapServer/0");

    query = new Query();
    query.returnGeometry = false;
    query.outFields = ["apino", "operator", "wellname", "drillertotaldepth", "county", "twp", "rge", "section_", "formationtd", "otherid"];

    on(dom.byId("execute"), "click", execute);

    function execute() {
        //query.text = dom.byId("apinum","operatorid","wellnameid","statusid","fieldid","countyid","twpid","rgeid","sectionid","formationtdid","stateperm").value;
        query.text = dom.byId("countyid").value;
        //execute query
        queryTask.execute(query, updateGrid(featureSet));
    }

    /*function execute() {
     var whereclause = "apino = 02-001-05159";

     function addToWhereClause(inputEleId, fieldName) {
     var content = dom.byId(inputEleId).value;
     if (content !== "") {
     whereclause += fieldName + "='" + content + "'";
     }
     }

     // Start moving through the inputs
     // APINO
     addToWhereClause("apinum", "apino");

     // OPERATOR
     addToWhereClause("operatorid", "operator");

     //WELLNAME
     addToWhereClause("wellnameid", "wellname");

     //STATUS
     addToWhereClause("statusid", "status");

     //FIELD
     addToWhereClause("fieldid", "field");

     //COUNTY
     addToWhereClause("countyid", "county");

     //TOWNSHIP
     addToWhereClause("twpid", "twp");

     //RANGE
     addToWhereClause("rgeid", "rge");

     //SECTION
     addToWhereClause("sectionid", "section_");

     //FORMATIONTD
     addToWhereClause("formationtdid","formationtd");

     //OTHERID
     addToWhereClause("stateperm","otherid");

     query.where = whereclause

     queryTask.execute(query, showResults);
     }*/

    function updateGrid(featureSet){
        var data=[];
        var grid = dijit.byId('grid');
        dojo.forEach(featureSet, function (entry) {
            //if related geographic then related = entry.att.related
            // else api search related= entry.feature.att.related
            console.log(entry);
            var logs = [],
                las = [],               folders = [],
                relatedResource = entry.attributes.relatedresource === null ? "no value" : entry.attributes.relatedresource;

            var raw = relatedResource.split("|");
            raw.forEach(function (bit){
                var resource = bit.split(", ");
                if (resource[0] && resource[1]){
                    var url = resource[1].trim();
                    var name = resource[0].trim();
                }
                var anchor = "
" + name + "
";
                if (url != null ){
                    if ( url.indexOf(".tif", url.length -4) !==-1){
                        logs.push(anchor);
                    }
                    if ( url.indexOf(".pdf", url.length -4) !==-1){
                        folders.push(anchor);
                    }
                    if ( url.indexOf(".las", url.length -4) !==-1){
                        las.push(anchor);
                    }
                }
            });

            data.push({
                objectid:entry.attributes.objectid,//0
                apino:entry.attributes.apino,//1
                otherid:entry.attributes.otherid,//2
                wellname:entry.attributes.wellname,//3
                county:entry.attributes.county,//4
                twp:entry.attributes.twp,//5
                rge:entry.attributes.rge,//6
                section_:entry.attributes.section_,//8
                drillertotaldepth:entry.attributes.drillertotaldepth,//9
                formationtd:entry.attributes.formationtd,//10
                logField: '
' + logs.join(" ") + '
',
                lasField: '
' + las.join(" ") + '
',
                folderField: '
' + folders.join(" ") + '
'
            });
        });
        var dataForGrid= {
            items: data
        };

        var store = new dojo.data.ItemFileReadStore({data:dataForGrid});
        grid.setStore(store);
    )

        /*function showResults(results) {
         var s = "";
         for (var i=0, il=results.features.length; i<il; i++) {
         var featureAttributes = results.features[i].attributes;
         for (att in featureAttributes) {
         s = s + "" + att + ":  " + featureAttributes[att] + "
";
         }
         s = s + "
";
         }
         dom.byId("results").innerHTML = s;
         }*/

    });


text:
layout: post
status: publish
published: true
title: X-Face
author:
  display_name: shorne
  login: admin
  email: shorne@gmail.com
  url: http://blog.shorne-pla.net
author_login: admin
author_email: shorne@gmail.com
author_url: http://blog.shorne-pla.net
wordpress_id: 69
wordpress_url: http://blog.shorne-pla.net/?p=69
date: !binary |-
  MjAwNy0wNS0xMyAwNjoxODoyMyArMDkwMA==
date_gmt: !binary |-
  MjAwNy0wNS0xMiAyMzoxODoyMyArMDkwMA==
categories:
- Tech Stories
tags: []
comments: []
---

Today I received a mail on the enlightenment file list and I was suprised to see a little icon displayed in the mail header.  As you may know, I have working on mail filtering servers before, so I am very familiar with how e-mail works and the various headers.

I was supprised to discover the  X-Face header.  It seems to be a pretty neat idea but its rather limited, See below.  Anyway, I was just wondering what happens if I try to clear up the image a bit.  I applied a 5.0 px gaussian blut and I got what looks like ablurred photograph.

Now, if everyone placed their own faces in their emails using this technique I might be inclined to write a patch for my mail client, Sylpheed, to automatically apply the blur. The only problem is that this is not very popular at all.


text:
source `dirname $0`/../common.sh

docker run -v $OUTPUT_DIR:/tmp/output -v $CACHE_DIR:/tmp/cache -e VERSION=2.2.7  -e STACK=cedar-14 -e PATCH_URL=https://bugs.ruby-lang.org/attachments/download/6690/rubygems-2613-ruby22.patch hone/ruby-builder:cedar-14


text:
import * as T from './tracks'
import { ChordLane, ChordLaneChord, Note, TimeSignature } from './types'
import { getBeatLen, rand, randRange, sample } from './util'
import samples from './samples'

export const urlify = (sample: string) => `samples/${sample}.ogg`

export const getSamples = (track: string) => {
  const spec = samples[track]
  if (spec.length === 1) {
    return spec
  }
  return spec[1].map(x => `${spec[0]}_${x}`)
}

const createNote = (velocity?: number, pitch?: number) => ({
  velocity: velocity || 0,
  pitch: pitch || null
})

const getCurrentChord = (lane: ChordLane, index: number) => {
  const i = index % lane.length
  if (lane[i]) {
    return lane[i]
  }
  let prev = i - 1
  while (!lane[prev] && prev > 0) {
    prev--
  }
  return lane[prev]
}

type NextChordType = {
  at: number
  distance: number
  chord: ChordLaneChord
}

const getNextChords = (
  lane: ChordLane,
  index: number,
  lookAhead: number
): Array<NextChordType> => {
  let p = index - 2
  const out: Array<NextChordType> = []
  while (p <= index + lookAhead) {
    const i = p % lane.length
    if (lane[i]) {
      out.push({ at: p, distance: p - index, chord: lane[i] as ChordLaneChord })
    }
    p++
  }
  return out
}

const MIDI_C5 = 60
const MIDI_F5 = 65

const getPatternNote = (
  pattern,
  i: number,
  beatLen: number,
  isBeat,
  offBeat
) => {
  if (!isBeat && !offBeat) {
    return undefined
  }
  const patternStepLen = beatLen / 2
  const patternLenTicks = patternStepLen * pattern.length
  const currentPos = Math.floor((i % patternLenTicks) / patternStepLen)
  //console.log(pattern, i, patternStepLen, patternLenTicks, currentPos)
  return pattern[currentPos]
}

const handlePattern = (opts: IteratorOpts, key, i, pitch) => {
  const {
    state: { currentPattern, setPattern, clearPattern },
    beatLen,
    beatInfo: { isBeat, offBeat, isStartOfMeasure }
  } = opts
  let pattern = currentPattern
  let started = false
  const patternAuth = key === T.KICK
  let triggerPattern
  if (isStartOfMeasure(i) && patternAuth) {
    triggerPattern = rand(20)
  }
  if (!currentPattern && triggerPattern) {
    pattern = setPattern()
    //console.log('started pattern', i, pattern)
    started = true
  }
  if (pattern && pattern[key]) {
    if (!started && isStartOfMeasure(i) && patternAuth) {
      //console.log('cleared pattern', i)
      clearPattern()
    }
    const patternNote = getPatternNote(
      pattern[key],
      i,
      beatLen,
      isBeat(i),
      offBeat(i)
    )
    if (patternNote) {
      return createNote(
        patternNote === 1 ? randRange(70, 99) : patternNote,
        pitch
      )
    }
    return createNote()
  }
}

type GeneratedNote = {
  velocity: number
  pitch: number | null
}

type IteratorBeatInfo = {
  isFillAccent: (i: number) => boolean
  isBeat: (i: number) => boolean
  offBeat: (i: number) => boolean
  isStartOfMeasure: (i: number) => boolean
  beatsPerBar: (i: number) => number
}

type IteratorOpts = {
  beatLen: number
  isTriple: boolean
  beatInfo: IteratorBeatInfo
  timeSignature: TimeSignature
  state?: Record<string, unknown>
}

interface IteratorFn {
  (i: number, pitch: number, lane: ChordLane, opts: IteratorOpts): GeneratedNote
}

type Iterators = {
  [x: string]: IteratorFn | Iterators
}

const getBeatsPerBar = (i: number, timeSignature: TimeSignature) => {
  return timeSignature[1] === 4
    ? timeSignature[0]
    : timeSignature[0] === 12 || timeSignature[0] === 9
    ? 4
    : 4
}

const getLookAhead = (
  bars: number,
  timeSignature: TimeSignature,
  beatLen: number
) => {
  return Math.round(bars * beatLen * getBeatsPerBar(0, timeSignature))
}

type NoteProps = { note: Note; offset?: number }

const BASS_LOWEST = 28 // E1

const noteAdjustment = (note: number) => {
  if (note <= BASS_LOWEST + 24) {
    return note + 12
  } else if (note > 75) {
    return note + -12
  }
  return note
}

const withOffset = (noteProps: NoteProps, isBass?: boolean) => {
  let offset = isBass ? 12 : 0
  if (rand(50)) {
    // Change octave
    let jump = rand(50) ? -12 : 12
    const resultingNote = noteProps.note.midiNote + jump + offset
    offset += noteAdjustment(resultingNote) - resultingNote
  }
  //console.log('offset', noteProps.note.midiNote, offset)
  return { ...noteProps, offset }
}

const selectBassNote = (chord: ChordLaneChord, isFirst: boolean): NoteProps => {
  if (chord.bass) {
    const bassNote = chord.bassNote
    return withOffset({ note: bassNote }, true)
  }
  const root = chord.notes.filter(note => note.role === 'root')[0]
  const third = chord.notes.filter(note => note.role === 'third')[0]
  const fifth = chord.notes.filter(note => note.role === 'fifth')[0]
  let note = root
  if (rand(isFirst ? 1 : 20)) {
    if (rand(75)) {
      note = third || root
    } else {
      note = fifth || third || root
    }
  }
  return withOffset({ note })
}

const selectLeadingTone = (
  nextNote: Note,
  nextChord: ChordLaneChord
): NoteProps => {
  let note
  if (rand(75)) {
    note = { midiNote: nextNote.midiNote + (rand(50) ? 1 : -1) }
  } else {
    const nextBn = selectBassNote(nextChord, true)
    note = { midiNote: nextBn.note.midiNote + (rand(50) ? 7 : -5) }
  }

  return { note }
}

type MemItem = { pos: number; chord: ChordLaneChord } & NoteProps

const isWaltz = (ts: TimeSignature) => ts[0] === 9 && ts[1] === 8

const getPrimaryBassNote = (mem: MemItem): Note => {
  if (mem.note) {
    return mem.note
  }
  if (mem.chord) {
    return mem.chord.bass
      ? mem.chord.bassNote
      : mem.chord.notes.filter(note => note.role === 'root')[0]
  }
  return undefined
}

type BassState = {
  memorySet: number | undefined
  memory: Array<MemItem>
}

const walkLines = (
  maj?: boolean,
  dom?: boolean
): Record<string, Array<Array<number>>> => ({
  '5': [
    [2, 3, 4],
    [2, 7, 6],
    [0, 2, maj ? 4 : 3],
    [1, 2, maj ? 4 : 3]
  ],
  '-7': [
    [-2, -3, -5],
    [-2, -4, -6] // alt
  ],
  '7': [
    [2, maj ? 4 : 3, 5],
    [maj ? 4 : 3, 5, 6]
  ],
  '-5': [
    [-1, -2, -3],
    [dom ? -2 : -1, -3, -4]
  ]
})

const sameLines = (fifth: number, maj?: boolean, dom?: boolean) => {
  const th = maj ? 4 : 3
  const sv = dom ? -2 : -1
  const sx = maj ? -3 : -4
  return [
    [th, th - 1, th],
    [2, th, 2],
    [0, th, fifth],
    [0, fifth, fifth],
    [sv, sx, fifth],
    [0, 2, 2],
    [fifth, 12, fifth]
  ]
}

const isMajor = (chord: ChordLaneChord) => {
  if (chord.quality === 'm' || chord.quality === 'dim') {
    return false
  }
  return true
}

const sortMemory = arr =>
  arr.sort((a, b) => {
    if (a.pos < b.pos) return -1
    if (a.pos > b.pos) return 1
    return 0
  })

const iterators: Iterators = {
  default: {},
  jazz: {
    [T.BASS]: (i, pitch, lane, opts) => {
      const { timeSignature, beatLen } = opts
      const state = opts.state as BassState
      const lookAheadTime = getLookAhead(2.1, timeSignature, beatLen)
      const nextChords = getNextChords(lane, i, lookAheadTime)

      if (!state.memorySet) {
        // First place chord changes
        const chordPositions: Record<number, boolean> = {}
        for (let c = 0; c < nextChords.length; ++c) {
          const nc = nextChords[c].chord
          const pos = nextChords[c].at
          const laneIndex = pos % lane.length
          const isFirst = laneIndex === 0 || !!lane[laneIndex]?.section
          const noteProps = selectBassNote(nc, isFirst)
          chordPositions[pos] = true
          state.memory.push({ pos, chord: nc, ...noteProps })
        }

        // Check for chord staying the same
        let startingLength = state.memory.length
        for (let c = 0; c < startingLength; ++c) {
          const mem = state.memory[c]
          const nextIndex = c + 1
          const nextMem =
            state.memory[
              nextIndex < startingLength ? nextIndex : state.memory.length
            ]
          if (mem && nextMem && mem.chord.name === nextMem.chord.name) {
            const numBeats = Math.floor((nextMem.pos - (mem.pos + 1)) / beatLen)
            if (numBeats === 3 && rand(75)) {
              const isMaj = isMajor(mem.chord)
              let fifth = 7
              if (mem.chord.quality === 'dim' || mem.chord.quality === 'alt') {
                fifth--
              } else if (mem.chord.quality === 'aug') {
                fifth++
              }
              const pattern = sample(
                sameLines(fifth, isMaj, mem.chord.quality !== 'maj')
              )
              for (let x = 0; x < numBeats; ++x) {
                const newNote = {
                  pos: mem.pos + beatLen * (x + 1),
                  note: {
                    midiNote: noteAdjustment(mem.note.midiNote + pattern[x])
                  },
                  chord: mem.chord
                }
                state.memory.push(newNote)
              }
            }
          }
        }
        state.memory = sortMemory(state.memory)

        // Check for 4th/5th movements or possible repeats in descending/ascending lines
        startingLength = state.memory.length
        for (let c = 0; c < startingLength; ++c) {
          const mem = state.memory[c]
          const nextIndex = c + 1
          const nextMem =
            state.memory[
              nextIndex < startingLength ? nextIndex : state.memory.length
            ]
          if (mem && nextMem) {
            const numBeats = Math.floor((nextMem.pos - (mem.pos + 1)) / beatLen)
            const noteDifference =
              getPrimaryBassNote(nextMem).midiNote -
              getPrimaryBassNote(mem).midiNote
            const noteDiff = Math.abs(noteDifference) % 12
            if (
              numBeats === 3 &&
              (noteDiff === 7 || noteDiff === 5) &&
              mem.note.role === 'root' &&
              nextMem.note.role === 'root' &&
              rand(50)
            ) {
              const isMaj = isMajor(mem.chord)
              const pattern = sample(
                walkLines(isMaj, mem.chord.quality !== 'maj')[
                  String(noteDifference)
                ]
              )
              for (let x = 0; x < numBeats; ++x) {
                const newNote = {
                  pos: mem.pos + beatLen * (x + 1),
                  note: {
                    midiNote: noteAdjustment(mem.note.midiNote + pattern[x])
                  },
                  chord: mem.chord
                }
                state.memory.push(newNote)
              }
            } else if (
              numBeats === 1 &&
              rand(75) &&
              (noteDiff === 1 ||
                noteDiff === 2 ||
                noteDiff === 10 ||
                noteDiff === 11)
            ) {
              // Repeat, or change octave
              const jump = rand(50) ? 12 : -12
              const offset = rand(5) ? jump : 0
              const pos = mem.pos + beatLen
              if (pos % beatLen === 0) {
                const midiNote = noteAdjustment(mem.note.midiNote + offset)
                const newNote = {
                  pos,
                  note: { midiNote },
                  chord: mem.chord
                }
                state.memory.push(newNote)
              }
            }
          }
        }
        state.memory = sortMemory(state.memory)

        // Place leading tones
        startingLength = state.memory.length
        for (let c = 0; c < startingLength; ++c) {
          const mem = state.memory[c]
          const pos = mem.pos - beatLen
          if (
            !chordPositions[pos] &&
            pos % lane.length >= i &&
            pos % beatLen === 0
          ) {
            const noteProps = selectLeadingTone(mem.note, mem.chord)
            state.memory.push({ pos, chord: mem.chord, ...noteProps })
          }
        }
        state.memory = sortMemory(state.memory)

        // Fill out gaps
        startingLength = state.memory.length
        for (let c = 0; c < startingLength; ++c) {
          const mem = state.memory[c]
          const nextIndex = c + 1
          const nextMem =
            state.memory[
              nextIndex < startingLength ? nextIndex : state.memory.length
            ]
          if (mem && nextMem) {
            const numBeats = Math.floor((nextMem.pos - (mem.pos + 1)) / beatLen)
            const noteDifference = nextMem.note.midiNote - mem.note.midiNote
            const noteDiff = Math.abs(noteDifference)
            const semitoneStep = noteDiff === numBeats + 1
            if (numBeats && semitoneStep) {
              // direct chromatic walk possible
              for (let x = 0; x < numBeats; ++x) {
                const newNote = {
                  pos: mem.pos + beatLen * (x + 1),
                  note: {
                    midiNote: noteAdjustment(
                      mem.note.midiNote +
                        (x + 1) * (noteDifference > 1 ? 1 : -1)
                    )
                  }
                }
                state.memory.push(newNote)
              }
            } else {
              for (let x = 0; x < numBeats; ++x) {
                const newNote = {
                  pos: mem.pos + beatLen * (x + 1),
                  note: sample(
                    mem.chord.notes.filter(x =>
                      ['root', 'third', 'fifth'].includes(x.role)
                    )
                  )
                }
                state.memory.push(newNote)
              }
            }
          }
        }

        const maxIndex = state.memory.reduce(
          (acc, curr) => Math.max(curr.pos, acc),
          0
        )
        state.memorySet = maxIndex
        state.memory = sortMemory(state.memory)
      } else {
        const ind = state.memory.findIndex(x => i === x.pos % lane.length)
        if (ind > -1) {
          const match = { ...state.memory[ind] }
          if (ind === state.memory.length - 1) {
            // clear memory
            state.memory = []
            state.memorySet = undefined
          }
          return createNote(
            127,
            pitch + match.note.midiNote - MIDI_C5 + (match.offset || 0)
          )
        }
      }

      return createNote()
    }
  },
  [T.BASS]: (i, pitch, lane, { beatLen }) => {
    const chord = getCurrentChord(lane, i)
    if (chord) {
      const bassnotes = chord.bass
        ? { root: chord.bassNote }
        : chord.notes
            .filter(
              note =>
                note.role === 'root' ||
                note.role === 'fifth' ||
                note.role === 'third'
            )
            .reduce((acc, c) => {
              acc[c.role] = c
              return acc
            }, {})
      const bassnote = bassnotes.root
      //console.log('bassnote', bassnote, chord)
      const offset = chord.bass ? 12 : 0
      if (i % (beatLen * 2) === 0 || (i + 2) % (beatLen * 2) === 0) {
        return createNote(127, pitch + bassnote.midiNote - MIDI_C5 + offset)
      }
    }
    return createNote()
  },
  [T.RIDE]: (
    i,
    pitch,
    lane,
    { beatLen, timeSignature, beatInfo: { isFillAccent } }
  ) => {
    let weak = (i + 2) % (beatLen * 2) === 0
    if (isWaltz(timeSignature)) {
      weak = (i + 2) % (beatLen * 3) === 0
    }
    if (isFillAccent(i) && rand(20)) {
      //console.log('fill ride')
      return createNote(randRange(110, 127), pitch)
    }
    if (i % beatLen === 0 || weak) {
      //console.log('yield ride', i, weak)
      return createNote(weak ? randRange(30, 64) : randRange(70, 108), pitch)
    }
    return createNote()
  },
  [T.HC]: (i, pitch, lane, opts) => {
    const { beatLen } = opts
    const ret = handlePattern(opts, T.HC, i, pitch)
    if (ret) {
      return ret
    }
    let hit = (i + beatLen) % (beatLen * 2) === 0
    if (isWaltz(opts.timeSignature)) {
      hit = (i + beatLen) % (beatLen * 3) === 2 * beatLen
    }
    if (hit) {
      return createNote(randRange(85, 108), pitch)
    }
    return createNote()
  },
  [T.KICK]: (i, pitch, lane, opts) => {
    const {
      beatInfo: { isBeat, offBeat, isFillAccent }
    } = opts

    if (isFillAccent(i) && rand(15)) {
      //console.log('fill kick')
      return createNote(randRange(110, 127), pitch)
    }

    const ret = handlePattern(opts, T.KICK, i, pitch)
    if (ret) {
      return ret
    }
    if ((isBeat(i) || offBeat(i)) && rand(5)) {
      //console.log('yield kick', i)
      return createNote(randRange(20, 109), pitch)
    }
    return createNote()
  },
  [T.SNARE]: (i, pitch, lane, opts) => {
    const {
      beatLen,
      isTriple,
      beatInfo: { offBeat, isBeat, isFillAccent }
    } = opts
    if (isFillAccent(i) && rand(20)) {
      //console.log('fill snare')
      return createNote(randRange(110, 126), pitch)
    }

    const ret = handlePattern(opts, T.SNARE, i, pitch)
    if (ret) {
      return ret
    }

    const mid = isTriple && (i - 2) % beatLen === 0
    if (
      (offBeat(i) && rand(10)) ||
      (isBeat(i) && rand(5)) ||
      (mid && rand(3))
    ) {
      const roll = rand(5)
      return createNote(roll ? 127 : randRange(20, 109), pitch)
    }
    return createNote()
  }
}

const iteratePattern = ({ patternLength, pitch, chordLane, opts }, iterator) =>
  Array.from({ length: patternLength }).map((_, i) => {
    const { beatLen } = opts
    const isBeat = i % beatLen === 0
    const isStartOfMeasure =
      isBeat && i % (opts.timeSignature[0] * beatLen) === 0
    const beatInfo = {
      isBeat,
      offBeat: (i + 2) % beatLen === 0,
      isStartOfMeasure
    }
    return iterator(i, pitch, chordLane, { ...opts, beatInfo })
  })

const getOpts = timeSignature => ({
  timeSignature,
  isTriple: timeSignature[1] === 8,
  beatLen: getBeatLen(timeSignature)
})

const bassMemStore = {
  state: { memory: [] }
}

export const clearBassMemory = () => {
  bassMemStore.state.memory = []
  bassMemStore.state.memorySet = undefined
}

export const createBass = (scene, chordLane, style, timeSignature) => {
  const track = T.BASS
  const samples = getSamples(track)
  const pitch = 0
  const iter = iterators[style][track]
    ? iterators[style][track]
    : iterators[track]

  const state = bassMemStore.state
  clearBassMemory()
  const opts = { ...getOpts(timeSignature), state }

  scene.parts[track] = {
    style,
    samples: samples.map(urlify),
    generator: (function* gen() {
      let currentNote = 0
      currentNote = yield
      while (true) {
        currentNote = yield iter(currentNote, pitch, chordLane, {
          ...opts,
          beatInfo: getBeatInfo(opts)
        })
      }
    })()
  }
}

export const createChords = (
  scene,
  chordLane,
  key,
  samples,
  timeSignature,
  style
) => {
  const voices = [1, 2, 3, 4]
  const opts = getOpts(timeSignature)
  const patterns = voices.map(() =>
    iteratePattern(
      {
        patternLength: chordLane.length,
        pitch: 0,
        chordLane,
        opts
      },
      () => createNote()
    )
  )
  const jazz = opts.isTriple && style === 'jazz'
  for (let i = 0; i < chordLane.length; ++i) {
    const nextChord = chordLane[i]
    let pos = jazz ? i - opts.beatLen / 3 : i
    if (pos < 0) {
      pos += chordLane.length
    }
    if (nextChord) {
      let notes = jazz ? nextChord.voicing || nextChord.notes : nextChord.notes
      if (notes.length > 4) {
        notes = notes.filter(note => note.role !== 'root')
      }
      notes.forEach((note, j) => {
        if (j <= 3) {
          patterns[j][pos] = createNote(127, note.midiNote - MIDI_F5)
        }
      })
    }
  }
  voices.forEach((voice, i) => {
    const voiceKey = `${key}${voice}`
    scene.parts[voiceKey] = {
      samples,
      //pattern: patterns[i]
      generator: (function* gen() {
        let currentNote = 0
        currentNote = yield
        while (true) {
          currentNote = yield patterns[i][currentNote % chordLane.length]
        }
      })()
    }
  })
}

const drumPatterns = [
  'sh-ssh-k',
  'sssh-hsk',
  '-hsh-hsh',
  '-s-ksh-k',
  '-sshshk-',
  'shksshk-',
  'shsh-sks',
  '-hkssksh'
].map(x => ({
  [T.SNARE]: x.split('').map(c => (c === 's' ? 1 : 0)),
  [T.KICK]: x.split('').map(c => (c === 'k' ? 1 : 0)),
  [T.HC]: x.split('').map(c => (c === 'h' ? 1 : 0))
}))

const getBeatInfo = (opts): IteratorBeatInfo => {
  const { beatLen } = opts
  const isBeat = i => i % beatLen === 0
  const offBeat = i => (i + 2) % beatLen === 0
  const beatsPerBar = i => getBeatsPerBar(i, opts.timeSignature)
  const measure = i => i / (beatsPerBar(i) * beatLen)
  const currentMeasure = i => Math.floor(measure(i)) + 1
  const currentBarProgress = i => 1 - (currentMeasure(i) - measure(i))
  const isStartOfMeasure = i =>
    isBeat(i) && i % (beatsPerBar(i) * beatLen) === 0
  const isFillAccent = i =>
    offBeat(i) && currentMeasure(i) % 4 === 0 && currentBarProgress(i) > 0.9
  return {
    isBeat,
    offBeat,
    isStartOfMeasure,
    isFillAccent,
    beatsPerBar
  }
}

export const createDrums = (scene, chordLane, timeSignature, style) => {
  const voices = [T.KICK, T.SNARE, T.HC, T.RIDE]

  const state = {
    currentPattern: undefined
  }
  state.setPattern = () => {
    const p = sample(drumPatterns)
    state.currentPattern = p
    return p
  }
  state.clearPattern = () => {
    state.currentPattern = undefined
  }

  const opts = { ...getOpts(timeSignature), state }
  const jazz = opts.isTriple && style === 'jazz'
  const pitch = 0

  voices.forEach(track => {
    const samples = getSamples(track)
    const iter = iterators[style][track]
      ? iterators[style][track]
      : iterators[track]

    scene.parts[track] = {
      style,
      samples: samples.map(urlify),
      //pattern: patterns[i],
      generator: (function* gen() {
        let currentNote = 0
        currentNote = yield
        while (true) {
          currentNote = yield iter(currentNote, pitch, chordLane, {
            ...opts,
            beatInfo: getBeatInfo(opts)
          })
        }
      })()
    }
  })
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

	<!-- Bind the request url with permission or role -->
	<bean id="shiroFilterString" class="java.lang.String">
		 <constructor-arg>
		 	<value>
		 	<!-- # some example chain definitions:
				/admin/** = authc, roles[admin]
				/docs/** = authc, perms[document:read]
				/** = authc
				# more URL-to-FilterChain definitions here

				/** = authc

				#Admin dict manage
				/admin/dict/** = perms[dict]
				/admin/dict/read/** = perms[dict:read]

				#User info manage
				/user/info/** = perms[info]

			-->
		 		/captcha/valiCode.jpg = anon
				/identity/authenticate=anon
				/login=anon
				/getUserInfo=anon
				/updatePassword=anon
				/resources/** = anon
				/7sManagementService/**=anon
				/SafetyService/**=anon
				/** = authc

		 	</value>
		 </constructor-arg>
	</bean>
</beans>


text:
<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

/*Route::get('/', function () {
    return view('welcome');
});*/

Route::get('/', 'HomeController@index');

//Group haven't to login
Route::group(['before' => 'guest'], function() {
    //Get Login system
    Route::get('auth/login', [
        'as'=>'auth.getLogin',
        'uses'=>'Auth\AuthController@getLogin'
    ]);

    //Post Login system
    Route::post('auth/login', [
        'before' => 'csrf',
        'as'=>'auth.postLogin',
        'uses'=>'AuthController@postLogin'
    ]);

    //Post Register system
    Route::post('auth/register', [
        'before' => 'csrf',
        'as'=>'auth.postRegister',
        'uses'=>'AuthController@postRegister'
    ]);

    //Get reset password
    Route::get('auth/reset-password', [
        'as'=>'auth.getResetPassword',
        'uses'=>'AuthController@getResetPassword'
    ]);

    // Gửi yêu cầu  lấy lại mật khẩu qua email
    Route::post('auth/reset-password', [
        'before' => 'csrf',
        'as'=>'auth.postResetpassword',
        'uses'=>'AuthController@postResetPassword'
    ]);

    // Gửi lại token xác minh tài khoản đăng nhập
    Route::get('auth/resend-token', [
        'as'=>'auth.getResendToken',
        'uses'=>'AuthController@getResendToken'
    ]);

    // Gửi lại token xác minh tài khoản đăng nhập
    Route::post('auth/resend-token', [
        'before' => 'csrf',
        'as'=>'auth.postResendToken',
        'uses'=>'AuthController@postResendToken'
    ]);

});

//Group have to login
Route::group(['before'=>['auth.login']], function() {
    Route::get('logout.html',[
        'as'=>'auth.logout',
        'uses'=>'AuthController@getLogout'
    ]);

});


text:
import algorithms.interfaces.JSorter;
import algorithms.sorting.JBucketSort;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * Created by jason on 2/6/15.
 */
public class Main {

    public static final String TAG = Main.class.getSimpleName();

    public static void main(String args[]) {
        String message = "This project is only meant for working through data structures, " +
                "algorithms, and JUnit testing.  There is nothing to run in the main.  " +
                "All testing will be done through JUnit.";

        Integer[] mUnsortedArray = new Integer[]{5,34,12,55,754,42,11,90,74,88};
        JSorter mBucketSort = new JBucketSort(new ArrayList<Integer>(Arrays.asList(mUnsortedArray)));

        mBucketSort.sort();
        mBucketSort.printArray();

        System.exit(0);
    }
}


text:
/* 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.
 */

package org.activiti.engine.impl.bpmn.behavior;

import javax.naming.NamingException;

import org.activiti.engine.ActivitiException;
import org.activiti.engine.ActivitiIllegalArgumentException;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.Expression;
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.pvm.delegate.ActivityExecution;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.SimpleEmail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Joram Barrez
 * @author Frederik Heremans
 * @author Tim Stephenson
 */
public class MailActivityBehavior extends AbstractBpmnActivityBehavior {

  private static final long serialVersionUID = 1L;

  private static final Logger LOG = LoggerFactory.getLogger(MailActivityBehavior.class);

  protected Expression to;
  protected Expression from;
  protected Expression cc;
  protected Expression bcc;
  protected Expression subject;
  protected Expression text;
	protected Expression textVar;
  protected Expression html;
  protected Expression htmlVar;
  protected Expression charset;
  protected Expression ignoreException;
  protected Expression exceptionVariableName;

  public void execute(ActivityExecution execution) {

    boolean doIgnoreException = Boolean.parseBoolean(getStringFromField(ignoreException, execution));
    String exceptionVariable = getStringFromField(exceptionVariableName, execution);
    Email email = null;
    try {
      String toStr = getStringFromField(to, execution);
      String fromStr = getStringFromField(from, execution);
      String ccStr = getStringFromField(cc, execution);
      String bccStr = getStringFromField(bcc, execution);
      String subjectStr = getStringFromField(subject, execution);
  		String textStr = textVar == null ? getStringFromField(text, execution)
  				: getStringFromField(getExpression(execution, textVar), execution);
  		String htmlStr = htmlVar == null ? getStringFromField(html, execution)
  				: getStringFromField(getExpression(execution, htmlVar), execution);
      String charSetStr = getStringFromField(charset, execution);

      email = createEmail(textStr, htmlStr);

      addTo(email, toStr);
      setFrom(email, fromStr);
      addCc(email, ccStr);
      addBcc(email, bccStr);
      setSubject(email, subjectStr);
      setMailServerProperties(email);
      setCharset(email, charSetStr);

      email.send();

    } catch (ActivitiException e) {
      handleException(execution, e.getMessage(), e, doIgnoreException, exceptionVariable);
    } catch (EmailException e) {
      handleException(execution, "Could not send e-mail in execution " + execution.getId(), e, doIgnoreException, exceptionVariable);
    }

    leave(execution);
  }

  protected Email createEmail(String text, String html) {
    if (html != null) {
      return createHtmlEmail(text, html);
    } else if (text != null) {
      return createTextOnlyEmail(text);
    } else {
      throw new ActivitiIllegalArgumentException("'html' or 'text' is required to be defined when using the mail activity");
    }
  }

  protected HtmlEmail createHtmlEmail(String text, String html) {
    HtmlEmail email = new HtmlEmail();
    try {
      email.setHtmlMsg(html);
      if (text != null) { // for email clients that don't support html
        email.setTextMsg(text);
      }
      return email;
    } catch (EmailException e) {
      throw new ActivitiException("Could not create HTML email", e);
    }
  }

  protected SimpleEmail createTextOnlyEmail(String text) {
    SimpleEmail email = new SimpleEmail();
    try {
      email.setMsg(text);
      return email;
    } catch (EmailException e) {
      throw new ActivitiException("Could not create text-only email", e);
    }
  }

  protected void addTo(Email email, String to) {
    String[] tos = splitAndTrim(to);
    if (tos != null) {
      for (String t : tos) {
        try {
          email.addTo(t);
        } catch (EmailException e) {
          throw new ActivitiException("Could not add " + t + " as recipient", e);
        }
      }
    } else {
      throw new ActivitiException("No recipient could be found for sending email");
    }
  }

  protected void setFrom(Email email, String from) {
    String fromAddres = null;

    if (from != null) {
      fromAddres = from;
    } else { // use default configured from address in process engine config
      fromAddres = Context.getProcessEngineConfiguration().getMailServerDefaultFrom();
    }

    try {
      email.setFrom(fromAddres);
    } catch (EmailException e) {
      throw new ActivitiException("Could not set " + from + " as from address in email", e);
    }
  }

  protected void addCc(Email email, String cc) {
    String[] ccs = splitAndTrim(cc);
    if (ccs != null) {
      for (String c : ccs) {
        try {
          email.addCc(c);
        } catch (EmailException e) {
          throw new ActivitiException("Could not add " + c + " as cc recipient", e);
        }
      }
    }
  }

  protected void addBcc(Email email, String bcc) {
    String[] bccs = splitAndTrim(bcc);
    if (bccs != null) {
      for (String b : bccs) {
        try {
          email.addBcc(b);
        } catch (EmailException e) {
          throw new ActivitiException("Could not add " + b + " as bcc recipient", e);
        }
      }
    }
  }

  protected void setSubject(Email email, String subject) {
    email.setSubject(subject != null ? subject : "");
  }

  protected void setMailServerProperties(Email email) {
    ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();

    String mailSessionJndi = processEngineConfiguration.getMailSesionJndi();
    if (mailSessionJndi != null) {
      try {
        email.setMailSessionFromJNDI(mailSessionJndi);
      } catch (NamingException e) {
        throw new ActivitiException("Could not send email: Incorrect JNDI configuration", e);
      }
    } else {
      String host = processEngineConfiguration.getMailServerHost();
      if (host == null) {
        throw new ActivitiException("Could not send email: no SMTP host is configured");
      }
      email.setHostName(host);

      int port = processEngineConfiguration.getMailServerPort();
      email.setSmtpPort(port);

      email.setSSL(processEngineConfiguration.getMailServerUseSSL());
      email.setTLS(processEngineConfiguration.getMailServerUseTLS());

      String user = processEngineConfiguration.getMailServerUsername();
      String password = processEngineConfiguration.getMailServerPassword();
      if (user != null && password != null) {
        email.setAuthentication(user, password);
      }
    }
  }

  protected void setCharset(Email email, String charSetStr) {
    if (charset != null) {
      email.setCharset(charSetStr);
    }
  }

  protected String[] splitAndTrim(String str) {
    if (str != null) {
      String[] splittedStrings = str.split(",");
      for (int i = 0; i < splittedStrings.length; i++) {
        splittedStrings[i] = splittedStrings[i].trim();
      }
      return splittedStrings;
    }
    return null;
  }

  protected String getStringFromField(Expression expression, DelegateExecution execution) {
    if (expression != null) {
      Object value = expression.getValue(execution);
      if(value != null) {
        return value.toString();
      }
    }
    return null;
  }

  protected Expression getExpression(ActivityExecution execution, Expression var) {
    String variable = (String) execution.getVariable(var.getExpressionText());
    return Context.getProcessEngineConfiguration().getExpressionManager()
        .createExpression(variable);
  }

  protected void handleException(ActivityExecution execution, String msg, Exception e, boolean doIgnoreException, String exceptionVariable) {
    if (doIgnoreException) {
      LOG.info("Ignoring email send error: " + msg, e);
      if (exceptionVariable != null && exceptionVariable.length() > 0) {
        execution.setVariable(exceptionVariable, msg);
      }
    } else {
      if (e instanceof ActivitiException) {
        throw (ActivitiException) e;
      } else {
        throw new ActivitiException(msg, e);
      }
    }
  }
}


text:
namespace BrowserAutomationStudioFramework
{

    void MultiLanguageString::SetData(const QHash<QString,QString>& Data)
    {
        this->Data = Data;
    }

    QHash<QString,QString> MultiLanguageString::GetData()
    {
        return Data;
    }

    void MultiLanguageString::Clear()
    {
        Data.clear();
    }

    void MultiLanguageString::SetTranslation(const QString &Language, const QString &Translation)
    {
         Data[Language] = Translation;
    }
    QString MultiLanguageString::GetTranslation(const QString &Language)
    {
        if(Language.isEmpty())
        {
            return Data["en"];
        }
        return Data[Language];
    }

    void MultiLanguageString::ParseXml(QXmlStreamReader* XmlStreamReader)
    {
        Clear();
        if(XmlStreamReader->attributes().count() > 0)
        {
            foreach(QXmlStreamAttribute attr, XmlStreamReader->attributes())
            {
                SetTranslation(attr.name().toString(),attr.value().toString());
            }

        }else
        {
            XmlStreamReader->readNext();
            SetTranslation("en",XmlStreamReader->text().toString());
        }

    }

    bool MultiLanguageString::IsEmpty()
    {
        return Data.isEmpty();
    }

    void MultiLanguageString::WriteXml(QXmlStreamWriter* XmlStreamWriter)
    {

        QHash<QString, QString>::iterator i;
        for (i = Data.begin(); i != Data.end(); ++i)
        {
            if(!i.key().isEmpty())
            {
                XmlStreamWriter->writeAttribute(i.key(),i.value());
            }
        }

    }
}


text:
package com.chillenious.common.util;

import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * A Duration is an immutable length of time stored as a number of
 * milliseconds. Various factory and conversion methods are available for
 * convenience.
 *

 * These static factory methods allow easy construction of value objects using
 * either long values like seconds(2034) or hours(3):
 *

 *

 *
Duration.milliseconds(long)
 *
Duration.seconds(int)
 *
Duration.minutes(int)
 *
Duration.hours(int)
 *
Duration.days(int)
 *

 *

 * ...or double-precision floating point values like days(3.2):
 *

 *

 *
Duration.milliseconds(double)
 *
Duration.seconds(double)
 *
Duration.minutes(double)
 *
Duration.hours(double)
 *
Duration.days(double)
 *

 *

 * In the case of milliseconds(double), the value will be rounded
 * off to the nearest integral millisecond using Math.round().
 *

 * The precise number of milliseconds represented by a Duration
 * object can be retrieved by calling the getMilliseconds method.
 * The value of a Duration object in a given unit like days or
 * hours can be retrieved by calling one of the following unit methods, each of
 * which returns a double-precision floating point number:
 *

 *

 *
seconds()
 *
minutes()
 *
hours()
 *
days()
 *

 *

 * Values can be added and subtracted using the add(Duration) and
 * subtract(Duration) methods, each of which returns a new
 * immutable Duration object.
 *

 * String values can be converted to Duration objects
 * using the static valueOf factory methods. The
 * String format is the opposite of the one created by
 * toString(), which converts a Duration object to a
 * readable form, such as "3.2 hours" or "32.5 minutes". Valid units are:
 * milliseconds, seconds, minutes hours and days. Correct English plural forms
 * are used in creating String values and are parsed as well. The
 * Locale is respected and "," will be used instead of "." in the
 * Eurozone.
 *

 *
 * @author Jonathan Locke
 */
public class Duration extends AbstractTimeValue {
    private static final long serialVersionUID = 1L;

    /**
     * Constant for maximum duration.
     */
    public static final Duration MAXIMUM = milliseconds(Long.MAX_VALUE);

    /**
     * Constant for no duration.
     */
    public static final Duration NONE = milliseconds(0);

    /**
     * Constant for one day.
     */
    public static final Duration ONE_DAY = days(1);

    /**
     * Constant for one hour.
     */
    public static final Duration ONE_HOUR = hours(1);

    /**
     * Constant for on minute.
     */
    public static final Duration ONE_MINUTE = minutes(1);

    /**
     * Constant for one second.
     */
    public static final Duration ONE_SECOND = seconds(1);

    /**
     * Constant for one week.
     */
    public static final Duration ONE_WEEK = days(7);

    /**
     * pattern to match strings
     */
    private static final Pattern pattern = Pattern.compile(
            "([0-9]+([.,][0-9]+)?)\\s+(millisecond|second|minute|hour|day)s?",
            Pattern.CASE_INSENSITIVE);

    /**
     * Benchmark the given command.
     *
     * @param code a Runnable
     * @return the Time value it took to run the code
     */
    public static Duration benchmark(final Runnable code) {
        // Get time before running code
        final Time start = Time.now();

        // Run code
        code.run();

        // Return the difference
        return Time.now().subtract(start);
    }

    /**
     * Retrieves the Duration based on days.
     *
     * @param days days double value
     * @return the Duration based on days
     */
    public static Duration days(final double days) {
        return hours(24.0 * days);
    }

    /**
     * Retrieves the Duration based on days.
     *
     * @param days days int value
     * @return the Duration based on days
     */
    public static Duration days(final int days) {
        return hours(24 * days);
    }

    /**
     * Calculates the amount of time elapsed since start time.
     *
     * @param start the start Time
     * @return the elapsed period as a Duration
     * @throws IllegalStateException if start Time is in the future
     */
    public static Duration elapsed(final Time start) {
        return start.elapsedSince();
    }

    /**
     * Retrieves the Duration based on hours.
     *
     * @param hours hours double value
     * @return the Duration based on hours
     */
    public static Duration hours(final double hours) {
        return minutes(60.0 * hours);
    }

    /**
     * Retrieves the Duration based on hours.
     *
     * @param hours hours int value
     * @return the Duration based on hours
     */
    public static Duration hours(final int hours) {
        return minutes(60 * hours);
    }

    /**
     * Retrieves the Duration based on milliseconds.
     *
     * @param milliseconds milliseconds double value
     * @return the Duration based on milliseconds
     */
    public static Duration milliseconds(final double milliseconds) {
        return milliseconds(Math.round(milliseconds));
    }

    /**
     * Retrieves the Duration based on milliseconds.
     *
     * @param milliseconds milliseconds long value
     * @return the Duration based on milliseconds
     */
    public static Duration milliseconds(final long milliseconds) {
        return new Duration(milliseconds);
    }

    /**
     * Retrieves the Duration based on minutes.
     *
     * @param minutes minutes double value
     * @return the Duration based on minutes
     */
    public static Duration minutes(final double minutes) {
        return seconds(60.0 * minutes);
    }

    /**
     * Retrieves the Duration based on minutes.
     *
     * @param minutes minutes int value
     * @return the Duration based on minutes
     */
    public static Duration minutes(final int minutes) {
        return seconds(60 * minutes);
    }

    /**
     * Retrieves the Duration based on seconds.
     *
     * @param seconds seconds double value
     * @return the Duration based on seconds
     */
    public static Duration seconds(final double seconds) {
        return milliseconds(seconds * 1000.0);
    }

    /**
     * Retrieves the Duration based on seconds.
     *
     * @param seconds seconds int value
     * @return the Duration based on seconds
     */
    public static Duration seconds(final int seconds) {
        return milliseconds(seconds * 1000L);
    }

    /**
     * Retrieves the given long as a Duration.
     *
     * @param time the duration long value in milliseconds
     * @return the Duration value
     */
    public static Duration valueOf(final long time) {
        return new Duration(time);
    }

    /**
     * Converts the given String to a new Duration
     * object. The string can take the form of a floating point number followed
     * by a number of milliseconds, seconds, minutes, hours or days. For example
     * "6 hours" or "3.4 days". Parsing is case-insensitive.
     *
     * @param string a String to parse
     * @return the Duration value of the given String
     * @throws StringValueConversionException
     */
    public static Duration valueOf(final String string)
            throws StringValueConversionException {
        return valueOf(string, Locale.getDefault());
    }

    /**
     * Converts the given String to a new Duration
     * object. The string can take the form of a floating point number followed
     * by a number of milliseconds, seconds, minutes, hours or days. For example
     * "6 hours" or "3.4 days". Parsing is case-insensitive.
     *
     * @param string a String to parse
     * @param locale the Locale used for parsing
     * @return the Duration value of the given String
     * @throws StringValueConversionException
     */
    public static Duration valueOf(final String string, final Locale locale)
            throws StringValueConversionException {
        final Matcher matcher = pattern.matcher(string);

        if (matcher.matches()) {
            final double value = StringValue.valueOf(matcher.group(1), locale)
                    .toDouble();
            final String units = matcher.group(3);

            if (units.equalsIgnoreCase("millisecond")) {
                return milliseconds(value);
            } else if (units.equalsIgnoreCase("second")) {
                return seconds(value);
            } else if (units.equalsIgnoreCase("minute")) {
                return minutes(value);
            } else if (units.equalsIgnoreCase("hour")) {
                return hours(value);
            } else if (units.equalsIgnoreCase("day")) {
                return days(value);
            } else {
                throw new StringValueConversionException("Unrecognized units: "
                        + string);
            }
        } else {
            throw new StringValueConversionException(
                    "Unable to parse duration: " + string);
        }
    }

    /**
     * Private constructor forces use of static factory methods.
     *
     * @param milliseconds number of milliseconds in this Duration
     */
    protected Duration(final long milliseconds) {
        super(milliseconds);
    }

    /**
     * Adds a given Duration to this Duration.
     *
     * @param duration the Duration to add
     * @return the sum of the Durations
     */
    public Duration add(final Duration duration) {
        return valueOf(getMilliseconds() + duration.getMilliseconds());
    }

    /**
     * Retrieves the number of days of the current Duration.
     *
     * @return number of days of the current Duration
     */
    public final double days() {
        return hours() / 24.0;
    }

    /**
     * Retrieves the number of hours of the current Duration.
     *
     * @return number of hours of the current Duration
     */
    public final double hours() {
        return minutes() / 60.0;
    }

    /**
     * Retrieves the number of minutes of the current Duration.
     *
     * @return number of minutes of the current Duration
     */
    public final double minutes() {
        return seconds() / 60.0;
    }

    /**
     * Retrieves the number of seconds of the current Duration.
     *
     * @return number of seconds of the current Duration
     */
    public final double seconds() {
        return getMilliseconds() / 1000.0;
    }

    /**
     * Sleeps for the current Duration.
     */
    public final void sleep() {
        if (getMilliseconds() > 0) {
            try {
                Thread.sleep(getMilliseconds());
            } catch (InterruptedException e) {
                // Ignored
            }
        }
    }

    /**
     * Subtracts a given Duration from this Duration.
     *
     * @param that the Duration to subtract
     * @return this Duration minus that Duration
     */
    public Duration subtract(final Duration that) {
        return valueOf(getMilliseconds() - that.getMilliseconds());
    }

    /**
     * Retrieves the String representation of this
     * Duration in days, hours, minutes, seconds or milliseconds,
     * as appropriate. Uses the default Locale.
     *
     * @return a String representation
     */
    public String toString() {
        return toString(Locale.getDefault());
    }

    /**
     * Retrieves the String representation of this
     * Duration in days, hours, minutes, seconds or milliseconds,
     * as appropriate.
     *
     * @param locale a Locale
     * @return a String representation
     */
    public String toString(final Locale locale) {
        if (getMilliseconds() >= 0) {
            if (days() >= 1.0) {
                return unitString(days(), "day", locale);
            }

            if (hours() >= 1.0) {
                return unitString(hours(), "hour", locale);
            }

            if (minutes() >= 1.0) {
                return unitString(minutes(), "minute", locale);
            }

            if (seconds() >= 1.0) {
                return unitString(seconds(), "second", locale);
            }

            return unitString(getMilliseconds(), "millisecond", locale);
        } else {
            return "N/A";
        }
    }

    /**
     * Converts a value to a unit-suffixed value, taking care of English
     * singular/plural suffix.
     *
     * @param value  a double value to format
     * @param units  the units to apply singular or plural suffix to
     * @param locale the Locale
     * @return a String representation
     */
    private String unitString(final double value, final String units,
                              final Locale locale) {
        return StringValue.valueOf(value, locale) + " " + units
                + ((value > 1.0) ? "s" : "");
    }
}


text:
package com.github.ltsopensource.jobtracker.channel;

import com.github.ltsopensource.core.cluster.NodeType;
import com.github.ltsopensource.core.constant.Constants;
import com.github.ltsopensource.core.factory.NamedThreadFactory;
import com.github.ltsopensource.core.logger.Logger;
import com.github.ltsopensource.core.logger.LoggerFactory;
import com.github.ltsopensource.core.support.SystemClock;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author Robert HG (254963746@qq.com) on 7/24/14.
 *         管理channel
 */
public class ChannelManager {

    private final Logger LOGGER = LoggerFactory.getLogger(ChannelManager.class);
    // 客户端列表 (要保证同一个group的node要是无状态的)
    private final ConcurrentHashMap<String/*clientGroup*/, List<ChannelWrapper>> clientChannelMap = new ConcurrentHashMap<String, List<ChannelWrapper>>();
    // 任务节点列表
    private final ConcurrentHashMap<String/*taskTrackerNodeGroup*/, List<ChannelWrapper>> taskTrackerChannelMap = new ConcurrentHashMap<String, List<ChannelWrapper>>();
    // 用来定时检查已经关闭的channel
    private final ScheduledExecutorService channelCheckExecutorService = Executors.newScheduledThreadPool(1, new NamedThreadFactory("LTS-Channel-Checker", true));
    private ScheduledFuture<?> scheduledFuture;
    // 存储离线一定时间内的节点信息
    private final ConcurrentHashMap<String/*identity*/, Long> offlineTaskTrackerMap = new ConcurrentHashMap<String, Long>();
    // 用来清理离线时间很长的信息
    private final ScheduledExecutorService offlineTaskTrackerCheckExecutorService = Executors.newScheduledThreadPool(1, new NamedThreadFactory("LTS-offline-TaskTracker-Checker", true));
    private ScheduledFuture<?> offlineTaskTrackerScheduledFuture;

    private AtomicBoolean start = new AtomicBoolean(false);

    public void start() {
        try {
            if (start.compareAndSet(false, true)) {
                scheduledFuture = channelCheckExecutorService.scheduleWithFixedDelay(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            checkCloseChannel(NodeType.JOB_CLIENT, clientChannelMap);
                            if (LOGGER.isDebugEnabled()) {
                                LOGGER.debug("JobClient Channel Pool " + clientChannelMap);
                            }
                            checkCloseChannel(NodeType.TASK_TRACKER, taskTrackerChannelMap);
                            if (LOGGER.isDebugEnabled()) {
                                LOGGER.debug("TaskTracker Channel Pool " + taskTrackerChannelMap);
                            }
                        } catch (Throwable t) {
                            LOGGER.error("Check channel error!", t);
                        }
                    }
                }, 10, 10, TimeUnit.SECONDS);

                offlineTaskTrackerScheduledFuture = offlineTaskTrackerCheckExecutorService.scheduleWithFixedDelay(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (offlineTaskTrackerMap.size() > 0) {
                                for (Map.Entry<String, Long> entry : offlineTaskTrackerMap.entrySet()) {
                                    // 清除离线超过一定时间的信息
                                    if (SystemClock.now() - entry.getValue() > 2 * Constants.DEFAULT_TASK_TRACKER_OFFLINE_LIMIT_MILLIS) {
                                        offlineTaskTrackerMap.remove(entry.getKey());
                                    }
                                }
                            }
                        } catch (Throwable t) {
                            LOGGER.error("Check offline channel error!", t);
                        }
                    }
                }, 1, 1, TimeUnit.MINUTES);     // 1分钟检查一次

            }
            LOGGER.info("Start channel manager success!");
        } catch (Throwable t) {
            LOGGER.error("Start channel manager failed!", t);
        }
    }

    public void stop() {
        try {
            if (start.compareAndSet(true, false)) {
                scheduledFuture.cancel(true);
                channelCheckExecutorService.shutdown();
                offlineTaskTrackerScheduledFuture.cancel(true);
                offlineTaskTrackerCheckExecutorService.shutdown();
            }
            LOGGER.info("Stop channel manager success!");
        } catch (Throwable t) {
            LOGGER.error("Stop channel manager failed!", t);
        }
    }

    /**
     * 检查 关闭的channel
     */
    private void checkCloseChannel(NodeType nodeType, ConcurrentHashMap<String, List<ChannelWrapper>> channelMap) {
        for (Map.Entry<String, List<ChannelWrapper>> entry : channelMap.entrySet()) {
            List<ChannelWrapper> channels = entry.getValue();
            List<ChannelWrapper> removeList = new ArrayList<ChannelWrapper>();
            for (ChannelWrapper channel : channels) {
                if (channel.isClosed()) {
                    removeList.add(channel);
                    LOGGER.info("close channel={}", channel);
                }
            }
            channels.removeAll(removeList);
            // 加入到离线列表中
            if (nodeType == NodeType.TASK_TRACKER) {
                for (ChannelWrapper channelWrapper : removeList) {
                    offlineTaskTrackerMap.put(channelWrapper.getIdentity(), SystemClock.now());
                }
            }
        }
    }

    public List<ChannelWrapper> getChannels(String nodeGroup, NodeType nodeType) {
        if (nodeType == NodeType.JOB_CLIENT) {
            return clientChannelMap.get(nodeGroup);
        } else if (nodeType == NodeType.TASK_TRACKER) {
            return taskTrackerChannelMap.get(nodeGroup);
        }
        return null;
    }

    /**
     * 根据 节点唯一编号得到 channel
     */
    public ChannelWrapper getChannel(String nodeGroup, NodeType nodeType, String identity) {
        List<ChannelWrapper> channelWrappers = getChannels(nodeGroup, nodeType);
        if (channelWrappers != null && channelWrappers.size() != 0) {
            for (ChannelWrapper channelWrapper : channelWrappers) {
                if (channelWrapper.getIdentity().equals(identity)) {
                    return channelWrapper;
                }
            }
        }
        return null;
    }

    /**
     * 添加channel
     */
    public void offerChannel(ChannelWrapper channel) {
        String nodeGroup = channel.getNodeGroup();
        NodeType nodeType = channel.getNodeType();
        List<ChannelWrapper> channels = getChannels(nodeGroup, nodeType);
        if (channels == null) {
            channels = new ArrayList<ChannelWrapper>();
            if (nodeType == NodeType.JOB_CLIENT) {
                clientChannelMap.put(nodeGroup, channels);
            } else if (nodeType == NodeType.TASK_TRACKER) {
                taskTrackerChannelMap.put(nodeGroup, channels);
                // 如果在离线列表中,那么移除
                if (offlineTaskTrackerMap.containsKey(channel.getIdentity())) {
                    offlineTaskTrackerMap.remove(channel.getIdentity());
                }
            }
            channels.add(channel);
            LOGGER.info("new connected channel={}", channel);
        } else {
            if (!channels.contains(channel)) {
                channels.add(channel);
                LOGGER.info("new connected channel={}", channel);
            }
        }
    }

    public Long getOfflineTimestamp(String identity) {
        return offlineTaskTrackerMap.get(identity);
    }

    public void removeChannel(ChannelWrapper channel) {
        String nodeGroup = channel.getNodeGroup();
        NodeType nodeType = channel.getNodeType();
        List<ChannelWrapper> channels = getChannels(nodeGroup, nodeType);
        if (channels != null) {
            channels.remove(channel);
            LOGGER.info("remove channel={}", channel);
        }
    }
}


text:
<?php

namespace Kemistra\MainBundle\Form;

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

class TypeConsommableType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('nom', null, array('label' => 'Nom : '))
            ->add('description', null, array('label' => 'Description : '))
            ->add('unite', null, array('label' => 'Unité : '))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Kemistra\MainBundle\Entity\TypeConsommable'
        ));
    }

    public function getName()
    {
        return 'kemistra_mainbundle_typeconsommabletype';
    }
}


text:
@interface QBValidationRangeRule ()

@property (nonatomic, assign, readwrite) NSNumber *minValue;
@property (nonatomic, assign, readwrite) NSNumber *maxValue;
@property (nonatomic, assign, readwrite) BOOL inclusive;

@end

@implementation QBValidationRangeRule

+ (instancetype)ruleWithMinValue:(NSNumber *)minValue maxValue:(NSNumber *)maxValue inclusive:(BOOL)inclusive
{
    return [[self alloc] initWithMinValue:minValue maxValue:maxValue inclusive:inclusive];
}

- (instancetype)initWithMinValue:(NSNumber *)minValue maxValue:(NSNumber *)maxValue inclusive:(BOOL)inclusive
{
    self = [super init];

    if (self) {
        self.minValue = minValue;
        self.maxValue = maxValue;
        self.inclusive = inclusive;
    }

    return self;
}

- (NSString *)description
{
    return [NSString stringWithFormat:@"<%@: %p; minValue = %@; maxValue = %@; inclusive = %@>",
            NSStringFromClass([self class]),
            self,
            self.minValue,
            self.maxValue,
            self.inclusive ? @"YES" : @"NO"
            ];
}

#pragma mark - Validating Value

- (BOOL)validateValue:(id)value
{
    if ([value isKindOfClass:[NSNumber class]] || [value isKindOfClass:[NSString class]]) {
        if ([value isKindOfClass:[NSString class]]) {
            value = @([(NSString *)value length]);
        }

        // Adjust min and max value
        NSNumber *minValue = self.minValue;
        NSNumber *maxValue = self.maxValue;

        if ([minValue compare:maxValue] == NSOrderedDescending) {
            minValue = self.maxValue;
            maxValue = self.minValue;
        }

        // Compare
        NSComparisonResult resultOfComparisonToMin = [value compare:minValue];
        NSComparisonResult resultOfComparisonToMax = [value compare:maxValue];

        if (self.inclusive) {
            return ((resultOfComparisonToMin == NSOrderedDescending || resultOfComparisonToMin == NSOrderedSame) &&
                    (resultOfComparisonToMax == NSOrderedAscending || resultOfComparisonToMax == NSOrderedSame));
        } else {
            return (resultOfComparisonToMin == NSOrderedDescending && resultOfComparisonToMax == NSOrderedAscending);
        }
    }

    return NO;
}

@end