text:
package com.microsoft.azure.management.servicebus.v2017_04_01.implementation;

import com.microsoft.azure.management.servicebus.v2017_04_01.MessageCountDetails;
import org.joda.time.DateTime;
import org.joda.time.Period;
import com.microsoft.azure.management.servicebus.v2017_04_01.EntityStatus;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
import com.microsoft.azure.ProxyResource;

/**
 * Description of queue Resource.
 */
@JsonFlatten
public class SBQueueInner extends ProxyResource {
    /**
     * Message Count Details.
     */
    @JsonProperty(value = "properties.countDetails", access = JsonProperty.Access.WRITE_ONLY)
    private MessageCountDetails countDetails;

    /**
     * The exact time the message was created.
     */
    @JsonProperty(value = "properties.createdAt", access = JsonProperty.Access.WRITE_ONLY)
    private DateTime createdAt;

    /**
     * The exact time the message was updated.
     */
    @JsonProperty(value = "properties.updatedAt", access = JsonProperty.Access.WRITE_ONLY)
    private DateTime updatedAt;

    /**
     * Last time a message was sent, or the last time there was a receive
     * request to this queue.
     */
    @JsonProperty(value = "properties.accessedAt", access = JsonProperty.Access.WRITE_ONLY)
    private DateTime accessedAt;

    /**
     * The size of the queue, in bytes.
     */
    @JsonProperty(value = "properties.sizeInBytes", access = JsonProperty.Access.WRITE_ONLY)
    private Long sizeInBytes;

    /**
     * The number of messages in the queue.
     */
    @JsonProperty(value = "properties.messageCount", access = JsonProperty.Access.WRITE_ONLY)
    private Long messageCount;

    /**
     * ISO 8601 timespan duration of a peek-lock; that is, the amount of time
     * that the message is locked for other receivers. The maximum value for
     * LockDuration is 5 minutes; the default value is 1 minute.
     */
    @JsonProperty(value = "properties.lockDuration")
    private Period lockDuration;

    /**
     * The maximum size of the queue in megabytes, which is the size of memory
     * allocated for the queue. Default is 1024.
     */
    @JsonProperty(value = "properties.maxSizeInMegabytes")
    private Integer maxSizeInMegabytes;

    /**
     * A value indicating if this queue requires duplicate detection.
     */
    @JsonProperty(value = "properties.requiresDuplicateDetection")
    private Boolean requiresDuplicateDetection;

    /**
     * A value that indicates whether the queue supports the concept of
     * sessions.
     */
    @JsonProperty(value = "properties.requiresSession")
    private Boolean requiresSession;

    /**
     * ISO 8601 default message timespan to live value. This is the duration
     * after which the message expires, starting from when the message is sent
     * to Service Bus. This is the default value used when TimeToLive is not
     * set on a message itself.
     */
    @JsonProperty(value = "properties.defaultMessageTimeToLive")
    private Period defaultMessageTimeToLive;

    /**
     * A value that indicates whether this queue has dead letter support when a
     * message expires.
     */
    @JsonProperty(value = "properties.deadLetteringOnMessageExpiration")
    private Boolean deadLetteringOnMessageExpiration;

    /**
     * ISO 8601 timeSpan structure that defines the duration of the duplicate
     * detection history. The default value is 10 minutes.
     */
    @JsonProperty(value = "properties.duplicateDetectionHistoryTimeWindow")
    private Period duplicateDetectionHistoryTimeWindow;

    /**
     * The maximum delivery count. A message is automatically deadlettered
     * after this number of deliveries. default value is 10.
     */
    @JsonProperty(value = "properties.maxDeliveryCount")
    private Integer maxDeliveryCount;

    /**
     * Enumerates the possible values for the status of a messaging entity.
     * Possible values include: 'Active', 'Disabled', 'Restoring',
     * 'SendDisabled', 'ReceiveDisabled', 'Creating', 'Deleting', 'Renaming',
     * 'Unknown'.
     */
    @JsonProperty(value = "properties.status")
    private EntityStatus status;

    /**
     * Value that indicates whether server-side batched operations are enabled.
     */
    @JsonProperty(value = "properties.enableBatchedOperations")
    private Boolean enableBatchedOperations;

    /**
     * ISO 8061 timeSpan idle interval after which the queue is automatically
     * deleted. The minimum duration is 5 minutes.
     */
    @JsonProperty(value = "properties.autoDeleteOnIdle")
    private Period autoDeleteOnIdle;

    /**
     * A value that indicates whether the queue is to be partitioned across
     * multiple message brokers.
     */
    @JsonProperty(value = "properties.enablePartitioning")
    private Boolean enablePartitioning;

    /**
     * A value that indicates whether Express Entities are enabled. An express
     * queue holds a message in memory temporarily before writing it to
     * persistent storage.
     */
    @JsonProperty(value = "properties.enableExpress")
    private Boolean enableExpress;

    /**
     * Queue/Topic name to forward the messages.
     */
    @JsonProperty(value = "properties.forwardTo")
    private String forwardTo;

    /**
     * Queue/Topic name to forward the Dead Letter message.
     */
    @JsonProperty(value = "properties.forwardDeadLetteredMessagesTo")
    private String forwardDeadLetteredMessagesTo;

    /**
     * Get message Count Details.
     *
     * @return the countDetails value
     */
    public MessageCountDetails countDetails() {
        return this.countDetails;
    }

    /**
     * Get the exact time the message was created.
     *
     * @return the createdAt value
     */
    public DateTime createdAt() {
        return this.createdAt;
    }

    /**
     * Get the exact time the message was updated.
     *
     * @return the updatedAt value
     */
    public DateTime updatedAt() {
        return this.updatedAt;
    }

    /**
     * Get last time a message was sent, or the last time there was a receive request to this queue.
     *
     * @return the accessedAt value
     */
    public DateTime accessedAt() {
        return this.accessedAt;
    }

    /**
     * Get the size of the queue, in bytes.
     *
     * @return the sizeInBytes value
     */
    public Long sizeInBytes() {
        return this.sizeInBytes;
    }

    /**
     * Get the number of messages in the queue.
     *
     * @return the messageCount value
     */
    public Long messageCount() {
        return this.messageCount;
    }

    /**
     * Get iSO 8601 timespan duration of a peek-lock; that is, the amount of time that the message is locked for other receivers. The maximum value for LockDuration is 5 minutes; the default value is 1 minute.
     *
     * @return the lockDuration value
     */
    public Period lockDuration() {
        return this.lockDuration;
    }

    /**
     * Set iSO 8601 timespan duration of a peek-lock; that is, the amount of time that the message is locked for other receivers. The maximum value for LockDuration is 5 minutes; the default value is 1 minute.
     *
     * @param lockDuration the lockDuration value to set
     * @return the SBQueueInner object itself.
     */
    public SBQueueInner withLockDuration(Period lockDuration) {
        this.lockDuration = lockDuration;
        return this;
    }

    /**
     * Get the maximum size of the queue in megabytes, which is the size of memory allocated for the queue. Default is 1024.
     *
     * @return the maxSizeInMegabytes value
     */
    public Integer maxSizeInMegabytes() {
        return this.maxSizeInMegabytes;
    }

    /**
     * Set the maximum size of the queue in megabytes, which is the size of memory allocated for the queue. Default is 1024.
     *
     * @param maxSizeInMegabytes the maxSizeInMegabytes value to set
     * @return the SBQueueInner object itself.
     */
    public SBQueueInner withMaxSizeInMegabytes(Integer maxSizeInMegabytes) {
        this.maxSizeInMegabytes = maxSizeInMegabytes;
        return this;
    }

    /**
     * Get a value indicating if this queue requires duplicate detection.
     *
     * @return the requiresDuplicateDetection value
     */
    public Boolean requiresDuplicateDetection() {
        return this.requiresDuplicateDetection;
    }

    /**
     * Set a value indicating if this queue requires duplicate detection.
     *
     * @param requiresDuplicateDetection the requiresDuplicateDetection value to set
     * @return the SBQueueInner object itself.
     */
    public SBQueueInner withRequiresDuplicateDetection(Boolean requiresDuplicateDetection) {
        this.requiresDuplicateDetection = requiresDuplicateDetection;
        return this;
    }

    /**
     * Get a value that indicates whether the queue supports the concept of sessions.
     *
     * @return the requiresSession value
     */
    public Boolean requiresSession() {
        return this.requiresSession;
    }

    /**
     * Set a value that indicates whether the queue supports the concept of sessions.
     *
     * @param requiresSession the requiresSession value to set
     * @return the SBQueueInner object itself.
     */
    public SBQueueInner withRequiresSession(Boolean requiresSession) {
        this.requiresSession = requiresSession;
        return this;
    }

    /**
     * Get iSO 8601 default message timespan to live value. This is the duration after which the message expires, starting from when the message is sent to Service Bus. This is the default value used when TimeToLive is not set on a message itself.
     *
     * @return the defaultMessageTimeToLive value
     */
    public Period defaultMessageTimeToLive() {
        return this.defaultMessageTimeToLive;
    }

    /**
     * Set iSO 8601 default message timespan to live value. This is the duration after which the message expires, starting from when the message is sent to Service Bus. This is the default value used when TimeToLive is not set on a message itself.
     *
     * @param defaultMessageTimeToLive the defaultMessageTimeToLive value to set
     * @return the SBQueueInner object itself.
     */
    public SBQueueInner withDefaultMessageTimeToLive(Period defaultMessageTimeToLive) {
        this.defaultMessageTimeToLive = defaultMessageTimeToLive;
        return this;
    }

    /**
     * Get a value that indicates whether this queue has dead letter support when a message expires.
     *
     * @return the deadLetteringOnMessageExpiration value
     */
    public Boolean deadLetteringOnMessageExpiration() {
        return this.deadLetteringOnMessageExpiration;
    }

    /**
     * Set a value that indicates whether this queue has dead letter support when a message expires.
     *
     * @param deadLetteringOnMessageExpiration the deadLetteringOnMessageExpiration value to set
     * @return the SBQueueInner object itself.
     */
    public SBQueueInner withDeadLetteringOnMessageExpiration(Boolean deadLetteringOnMessageExpiration) {
        this.deadLetteringOnMessageExpiration = deadLetteringOnMessageExpiration;
        return this;
    }

    /**
     * Get iSO 8601 timeSpan structure that defines the duration of the duplicate detection history. The default value is 10 minutes.
     *
     * @return the duplicateDetectionHistoryTimeWindow value
     */
    public Period duplicateDetectionHistoryTimeWindow() {
        return this.duplicateDetectionHistoryTimeWindow;
    }

    /**
     * Set iSO 8601 timeSpan structure that defines the duration of the duplicate detection history. The default value is 10 minutes.
     *
     * @param duplicateDetectionHistoryTimeWindow the duplicateDetectionHistoryTimeWindow value to set
     * @return the SBQueueInner object itself.
     */
    public SBQueueInner withDuplicateDetectionHistoryTimeWindow(Period duplicateDetectionHistoryTimeWindow) {
        this.duplicateDetectionHistoryTimeWindow = duplicateDetectionHistoryTimeWindow;
        return this;
    }

    /**
     * Get the maximum delivery count. A message is automatically deadlettered after this number of deliveries. default value is 10.
     *
     * @return the maxDeliveryCount value
     */
    public Integer maxDeliveryCount() {
        return this.maxDeliveryCount;
    }

    /**
     * Set the maximum delivery count. A message is automatically deadlettered after this number of deliveries. default value is 10.
     *
     * @param maxDeliveryCount the maxDeliveryCount value to set
     * @return the SBQueueInner object itself.
     */
    public SBQueueInner withMaxDeliveryCount(Integer maxDeliveryCount) {
        this.maxDeliveryCount = maxDeliveryCount;
        return this;
    }

    /**
     * Get enumerates the possible values for the status of a messaging entity. Possible values include: 'Active', 'Disabled', 'Restoring', 'SendDisabled', 'ReceiveDisabled', 'Creating', 'Deleting', 'Renaming', 'Unknown'.
     *
     * @return the status value
     */
    public EntityStatus status() {
        return this.status;
    }

    /**
     * Set enumerates the possible values for the status of a messaging entity. Possible values include: 'Active', 'Disabled', 'Restoring', 'SendDisabled', 'ReceiveDisabled', 'Creating', 'Deleting', 'Renaming', 'Unknown'.
     *
     * @param status the status value to set
     * @return the SBQueueInner object itself.
     */
    public SBQueueInner withStatus(EntityStatus status) {
        this.status = status;
        return this;
    }

    /**
     * Get value that indicates whether server-side batched operations are enabled.
     *
     * @return the enableBatchedOperations value
     */
    public Boolean enableBatchedOperations() {
        return this.enableBatchedOperations;
    }

    /**
     * Set value that indicates whether server-side batched operations are enabled.
     *
     * @param enableBatchedOperations the enableBatchedOperations value to set
     * @return the SBQueueInner object itself.
     */
    public SBQueueInner withEnableBatchedOperations(Boolean enableBatchedOperations) {
        this.enableBatchedOperations = enableBatchedOperations;
        return this;
    }

    /**
     * Get iSO 8061 timeSpan idle interval after which the queue is automatically deleted. The minimum duration is 5 minutes.
     *
     * @return the autoDeleteOnIdle value
     */
    public Period autoDeleteOnIdle() {
        return this.autoDeleteOnIdle;
    }

    /**
     * Set iSO 8061 timeSpan idle interval after which the queue is automatically deleted. The minimum duration is 5 minutes.
     *
     * @param autoDeleteOnIdle the autoDeleteOnIdle value to set
     * @return the SBQueueInner object itself.
     */
    public SBQueueInner withAutoDeleteOnIdle(Period autoDeleteOnIdle) {
        this.autoDeleteOnIdle = autoDeleteOnIdle;
        return this;
    }

    /**
     * Get a value that indicates whether the queue is to be partitioned across multiple message brokers.
     *
     * @return the enablePartitioning value
     */
    public Boolean enablePartitioning() {
        return this.enablePartitioning;
    }

    /**
     * Set a value that indicates whether the queue is to be partitioned across multiple message brokers.
     *
     * @param enablePartitioning the enablePartitioning value to set
     * @return the SBQueueInner object itself.
     */
    public SBQueueInner withEnablePartitioning(Boolean enablePartitioning) {
        this.enablePartitioning = enablePartitioning;
        return this;
    }

    /**
     * Get a value that indicates whether Express Entities are enabled. An express queue holds a message in memory temporarily before writing it to persistent storage.
     *
     * @return the enableExpress value
     */
    public Boolean enableExpress() {
        return this.enableExpress;
    }

    /**
     * Set a value that indicates whether Express Entities are enabled. An express queue holds a message in memory temporarily before writing it to persistent storage.
     *
     * @param enableExpress the enableExpress value to set
     * @return the SBQueueInner object itself.
     */
    public SBQueueInner withEnableExpress(Boolean enableExpress) {
        this.enableExpress = enableExpress;
        return this;
    }

    /**
     * Get queue/Topic name to forward the messages.
     *
     * @return the forwardTo value
     */
    public String forwardTo() {
        return this.forwardTo;
    }

    /**
     * Set queue/Topic name to forward the messages.
     *
     * @param forwardTo the forwardTo value to set
     * @return the SBQueueInner object itself.
     */
    public SBQueueInner withForwardTo(String forwardTo) {
        this.forwardTo = forwardTo;
        return this;
    }

    /**
     * Get queue/Topic name to forward the Dead Letter message.
     *
     * @return the forwardDeadLetteredMessagesTo value
     */
    public String forwardDeadLetteredMessagesTo() {
        return this.forwardDeadLetteredMessagesTo;
    }

    /**
     * Set queue/Topic name to forward the Dead Letter message.
     *
     * @param forwardDeadLetteredMessagesTo the forwardDeadLetteredMessagesTo value to set
     * @return the SBQueueInner object itself.
     */
    public SBQueueInner withForwardDeadLetteredMessagesTo(String forwardDeadLetteredMessagesTo) {
        this.forwardDeadLetteredMessagesTo = forwardDeadLetteredMessagesTo;
        return this;
    }

}


text:
/* vim: set expandtab ts=4 sw=4: */
/*
 * You may redistribute this program and/or modify it under the terms of
 * the GNU General Public License as published by the Free Software Foundation,
 * either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "admin/Admin.h"
#include "benc/Dict.h"
#include "benc/String.h"
#include "dht/Address.h"
#include "dht/dhtcore/SearchRunner_admin.h"
#include "dht/dhtcore/SearchRunner.h"
#include "dht/Address.h"
#include "memory/Allocator.h"
#include "util/AddrTools.h"

struct Context {
    struct Admin* admin;
    struct Allocator* allocator;
    struct SearchRunner* runner;
    Identity
};

static void showActiveSearch(Dict* args, void* vctx, String* txid, struct Allocator* alloc)
{
    struct Context* ctx = Identity_check((struct Context*) vctx);
    int number = *(Dict_getInt(args, String_CONST("number")));

    struct SearchRunner_SearchData* search =
        SearchRunner_showActiveSearch(ctx->runner, number, alloc);

    Dict* dict = Dict_new(alloc);

    // Nothing is an error
    Dict_putString(dict, String_new("error", alloc), String_new("none", alloc), alloc);

    if (number < search->activeSearches) {
        uint8_t target[40];
        AddrTools_printIp(target, search->target);
        Dict_putString(dict, String_new("target", alloc), String_new((char*)target, alloc), alloc);

        uint8_t lastNodeAsked[60];
        Address_print(lastNodeAsked, &search->lastNodeAsked);
        Dict_putString(dict,
                       String_new("lastNodeAsked", alloc),
                       String_new((char*)lastNodeAsked, alloc),
                       alloc);

        Dict_putInt(dict, String_new("totalRequests", alloc), search->totalRequests, alloc);
    }
    Dict_putInt(dict, String_new("activeSearches", alloc), search->activeSearches, alloc);

    Admin_sendMessage(dict, txid, ctx->admin);
}

void SearchRunner_admin_register(struct SearchRunner* runner,
                                 struct Admin* admin,
                                 struct Allocator* alloc)
{
    struct Context* ctx = Allocator_clone(alloc, (&(struct Context) {
        .admin = admin,
        .allocator = alloc,
        .runner = runner
    }));
    Identity_set(ctx);

    Admin_registerFunction("SearchRunner_showActiveSearch", showActiveSearch, ctx, true,
        ((struct Admin_FunctionArg[]) {
            { .name = "number", .required = 1, .type = "Int" }
        }), admin);
}

redpajama_set_name: RedPajamaGithub


text:
<user-mapping>
    <authorize
            username="abc"
            password="900150983cd24fb0d6963f7d28e17f72"
            encoding="md5">
        <protocol>rdp</protocol>
        <param name="hostname">127.0.0.1</param>
        <param name="port">3389</param>
        <param name="color-depth">16</param>
        <param name="ignore-cert">true</param>
        <param name="username">abc</param>
        <param name="password">abc</param>
    </authorize>
</user-mapping>


text:
using System;
using System.Collections.Immutable;
using System.IO;
using Microsoft.Extensions.Logging;
using OmniSharp.Utilities;

namespace OmniSharp.MSBuild.Discovery.Providers
{
    internal class StandAloneInstanceProvider : MSBuildInstanceProvider
    {
        private readonly bool _allowMonoPaths;

        public StandAloneInstanceProvider(ILoggerFactory loggerFactory, bool allowMonoPaths)
            : base(loggerFactory)
        {
            _allowMonoPaths = allowMonoPaths;
        }

        public override ImmutableArray<MSBuildInstance> GetInstances()
        {
            var path = FindLocalMSBuildDirectory();
            if (path == null)
            {
                return NoInstances;
            }

            var extensionsPath = path;
            var toolsPath = Path.Combine(extensionsPath, "15.0", "Bin");
            var roslynPath = Path.Combine(toolsPath, "Roslyn");

            var propertyOverrides = ImmutableDictionary.CreateBuilder<string, string>(StringComparer.OrdinalIgnoreCase);

            if (PlatformHelper.IsMono)
            {
                // This disables a hack in the "GetReferenceAssemblyPaths" task which attempts
                // guarantee that .NET Framework SP1 is installed when the target framework is
                // .NET Framework, but the version is less than 4.0. The hack attempts to locate
                // a particular assembly in the GAC as a "guarantee". However, we don't include that
                // in our Mono package. So, we'll just bypass the check.
                propertyOverrides.Add("BypassFrameworkInstallChecks", "true");

                // To better support older versions of Mono that don't include
                // MSBuild 15, we attempt to set property overrides to the locations
                // of Mono's 'xbuild' and 'xbuild-frameworks' paths.
                if (_allowMonoPaths)
                {
                    if (TryGetMonoXBuildPath(out var xbuildPath))
                    {
                        extensionsPath = xbuildPath;
                    }

                    if (TryGetMonoXBuildFrameworksPath(out var xbuildFrameworksPath))
                    {
                        propertyOverrides.Add("TargetFrameworkRootPath", xbuildFrameworksPath);
                    }
                }
            }

            propertyOverrides.Add("MSBuildToolsPath", toolsPath);
            propertyOverrides.Add("MSBuildExtensionsPath", extensionsPath);
            propertyOverrides.Add("CscToolPath", roslynPath);
            propertyOverrides.Add("CscToolExe", "csc.exe");

            return ImmutableArray.Create(
                new MSBuildInstance(
                    nameof(DiscoveryType.StandAlone),
                    toolsPath,
                    new Version(15, 0),
                    DiscoveryType.StandAlone,
                    propertyOverrides.ToImmutable(),
                    setMSBuildExePathVariable: true));
        }

        private static bool TryGetMonoXBuildPath(out string path)
        {
            path = null;

            var monoXBuildDirPath = PlatformHelper.GetMonoXBuildDirPath();
            if (monoXBuildDirPath == null)
            {
                return false;
            }

            var monoXBuild15DirPath = Path.Combine(monoXBuildDirPath, "15.0");
            if (!Directory.Exists(monoXBuild15DirPath))
            {
                return false;
            }

            path = monoXBuildDirPath;
            return true;
        }

        private static bool TryGetMonoXBuildFrameworksPath(out string path)
        {
            path = null;

            var monoMSBuildXBuildFrameworksDirPath = PlatformHelper.GetMonoXBuildFrameworksDirPath();
            if (monoMSBuildXBuildFrameworksDirPath == null)
            {
                return false;
            }

            path = monoMSBuildXBuildFrameworksDirPath;
            return true;
        }
    }
}


text:
public class HelloJava {

    public static void main(String[] args) {

        Marker[] markers = new Marker[5];

        Object object = new Object();
        for (int i = 0; i <markers.length; i++) {
            markers[i] = new Marker(i,"Color"+i);
        }

        for(Marker marker : markers ) {
            System.out.println( marker );
        }

    }
}

class Marker {
    public int length;
    public String color;

    public Marker(int length, String color) {
        this.length = length;
        this.color = color;
    }

    @Override
    public String toString() {
        return "Length: "+ length + " Color: "+ color;
    }
}


text:
from __future__ import absolute_import, unicode_literals
from .models import AuthorshipModel
from thecut.authorship.factories import AuthorshipFactory

class AuthorshipModelFactory(AuthorshipFactory):

    class Meta(object):
        model = AuthorshipModel


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Mozilla Communicator client code, released
 * March 31, 1998.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1998
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

/**
   File Name:          15.js
   ECMA Section:       15 Native ECMAScript Objects
   Description:        Every built-in prototype object has the Object prototype
   object, which is the value of the expression
   Object.prototype (15.2.3.1) as the value of its internal
   [[Prototype]] property, except the Object prototype
   object itself.

   Every native object associated with a program-created
   function also has the Object prototype object as the
   value of its internal [[Prototype]] property.

   Author:             christine@netscape.com
   Date:               28 october 1997

*/
var SECTION = "15-1";
var VERSION = "ECMA_1";
startTest();
var TITLE   = "Native ECMAScript Objects";

writeHeaderToLog( SECTION + " "+ TITLE);
/*
  new TestCase( SECTION,  "Function.prototype.__proto__", Object.prototype,   Function.prototype.__proto__ );
  new TestCase( SECTION,  "Array.prototype.__proto__",    Object.prototype,   Array.prototype.__proto__ );
  new TestCase( SECTION,  "String.prototype.__proto__",   Object.prototype,   String.prototype.__proto__ );
  new TestCase( SECTION,  "Boolean.prototype.__proto__",  Object.prototype,   Boolean.prototype.__proto__ );
  new TestCase( SECTION,  "Number.prototype.__proto__",   Object.prototype,   Number.prototype.__proto__ );
//    new TestCase( SECTION,  "Math.prototype.__proto__",     Object.prototype,   Math.prototype.__proto__ );
new TestCase( SECTION,  "Date.prototype.__proto__",     Object.prototype,   Date.prototype.__proto__ );
new TestCase( SECTION,  "TestCase.prototype.__proto__", Object.prototype,   TestCase.prototype.__proto__ );

new TestCase( SECTION,  "MyObject.prototype.__proto__", Object.prototype,   MyObject.prototype.__proto__ );
*/
new TestCase( SECTION,  "Function.prototype.__proto__ == Object.prototype", true,   Function.prototype.__proto__ == Object.prototype );
new TestCase( SECTION,  "Array.prototype.__proto__ == Object.prototype",    true,   Array.prototype.__proto__ == Object.prototype );
new TestCase( SECTION,  "String.prototype.__proto__ == Object.prototype",   true,   String.prototype.__proto__ == Object.prototype );
new TestCase( SECTION,  "Boolean.prototype.__proto__ == Object.prototype",  true,   Boolean.prototype.__proto__ == Object.prototype );
new TestCase( SECTION,  "Number.prototype.__proto__ == Object.prototype",   true,   Number.prototype.__proto__ == Object.prototype );
//    new TestCase( SECTION,  "Math.prototype.__proto__ == Object.prototype",     true,   Math.prototype.__proto__ == Object.prototype );
new TestCase( SECTION,  "Date.prototype.__proto__ == Object.prototype",     true,   Date.prototype.__proto__ == Object.prototype );
new TestCase( SECTION,  "TestCase.prototype.__proto__ == Object.prototype", true,   TestCase.prototype.__proto__ == Object.prototype );

new TestCase( SECTION,  "MyObject.prototype.__proto__ == Object.prototype", true,   MyObject.prototype.__proto__ == Object.prototype );

test();

function MyObject( value ) {
  this.value = value;
  this.valueOf = new Function( "return this.value" );
}


text:
package com.burnevsky.firu.model.exam;

public class FiruTestException extends Exception
{
    private static final long serialVersionUID = 8852271766860391932L;

    public FiruTestException() {
    }

    public FiruTestException(String detailMessage) {
        super(detailMessage);
    }

    public FiruTestException(String detailMessage, Throwable throwable) {
        super(detailMessage, throwable);
    }

    public FiruTestException(Throwable throwable) {
        super(throwable);
    }
}


text:
using ThreadPoolExecutionMode =
    base::test::TaskEnvironment::ThreadPoolExecutionMode;

namespace blink {

class DiskDataAllocatorTest : public ::testing::Test {
 public:
  explicit DiskDataAllocatorTest(
      ThreadPoolExecutionMode thread_pool_execution_mode =
          ThreadPoolExecutionMode::DEFAULT)
      : task_environment_(base::test::TaskEnvironment::TimeSource::MOCK_TIME,
                          thread_pool_execution_mode) {}

  static std::vector<std::unique_ptr<DiskDataMetadata>>
  Allocate(InMemoryDataAllocator* allocator, size_t size, size_t count) {
    std::string random_data = base::RandBytesAsString(size);

    std::vector<std::unique_ptr<DiskDataMetadata>> all_metadata;
    for (size_t i = 0; i < count; i++) {
      auto metadata = allocator->Write(random_data.c_str(), random_data.size());
      EXPECT_EQ(metadata->start_offset(), static_cast<int64_t>(i * size));
      all_metadata.push_back(std::move(metadata));
    }
    return all_metadata;
  }

 protected:
  void SetUp() override {
    // On some platforms, initialization takes time, though it happens when
    // base::ThreadTicks is used. To prevent flakiness depending on test
    // execution ordering, force initialization.
    if (base::ThreadTicks::IsSupported())
      base::ThreadTicks::WaitUntilInitialized();
  }

  base::test::TaskEnvironment task_environment_;
};

TEST_F(DiskDataAllocatorTest, ReadWrite) {
  InMemoryDataAllocator allocator;

  constexpr size_t kSize = 1000;
  std::string random_data = base::RandBytesAsString(kSize);
  auto metadata = allocator.Write(random_data.c_str(), random_data.size());
  EXPECT_TRUE(metadata);
  EXPECT_EQ(kSize, metadata->size());

  auto read_data = std::vector<char>(kSize);
  allocator.Read(*metadata, &read_data[0]);

  EXPECT_EQ(0, memcmp(&read_data[0], random_data.c_str(), kSize));
}

TEST_F(DiskDataAllocatorTest, ReadWriteDiscardMultiple) {
  InMemoryDataAllocator allocator;

  std::vector<std::pair<std::unique_ptr<DiskDataMetadata>, std::string>>
      data_written;

  for (int i = 0; i < 10; i++) {
    int size = base::RandInt(100, 1000);
    auto data = base::RandBytesAsString(size);
    auto metadata = allocator.Write(&data[0], size);
    ASSERT_TRUE(metadata);
    data_written.emplace_back(std::move(metadata), data);
  }

  base::RandomShuffle(data_written.begin(), data_written.end());

  for (const auto& p : data_written) {
    size_t size = p.first->size();
    auto read_data = std::vector<char>(size);
    allocator.Read(*p.first, &read_data[0]);

    EXPECT_EQ(0, memcmp(&read_data[0], &p.second[0], size));
  }

  base::RandomShuffle(data_written.begin(), data_written.end());

  for (auto& p : data_written) {
    auto metadata = std::move(p.first);
    allocator.Discard(std::move(metadata));
  }
}

TEST_F(DiskDataAllocatorTest, WriteEventuallyFail) {
  InMemoryDataAllocator allocator;

  constexpr size_t kSize = 1 << 18;
  std::string random_data = base::RandBytesAsString(kSize);

  static_assert(4 * kSize == InMemoryDataAllocator::kMaxSize, "");
  for (int i = 0; i < 4; i++) {
    auto metadata = allocator.Write(random_data.c_str(), random_data.size());
    EXPECT_TRUE(metadata);
  }
  auto metadata = allocator.Write(random_data.c_str(), random_data.size());
  EXPECT_FALSE(metadata);
  EXPECT_FALSE(allocator.may_write());
}

TEST_F(DiskDataAllocatorTest, CanReuseFreedChunk) {
  InMemoryDataAllocator allocator;

  constexpr size_t kSize = 1 << 10;
  std::vector<std::unique_ptr<DiskDataMetadata>> all_metadata;

  for (int i = 0; i < 10; i++) {
    std::string random_data = base::RandBytesAsString(kSize);
    auto metadata = allocator.Write(random_data.c_str(), random_data.size());
    ASSERT_TRUE(metadata);
    all_metadata.push_back(std::move(metadata));
  }

  auto metadata = std::move(all_metadata[4]);
  ASSERT_TRUE(metadata);
  int64_t start_offset = metadata->start_offset();
  allocator.Discard(std::move(metadata));

  std::string random_data = base::RandBytesAsString(kSize);
  auto new_metadata = allocator.Write(random_data.c_str(), random_data.size());
  ASSERT_TRUE(new_metadata);
  EXPECT_EQ(new_metadata->start_offset(), start_offset);
}

TEST_F(DiskDataAllocatorTest, ExactThenWorstFit) {
  InMemoryDataAllocator allocator;

  int count = 10;
  size_t size_increment = 1000;
  std::vector<std::unique_ptr<DiskDataMetadata>> all_metadata;

  size_t size = 10000;
  // Allocate a bunch of random-sized
  for (int i = 0; i < count; i++) {
    std::string random_data = base::RandBytesAsString(size);
    auto metadata = allocator.Write(random_data.c_str(), random_data.size());
    ASSERT_TRUE(metadata);
    all_metadata.push_back(std::move(metadata));
    size += size_increment;
  }

  auto& hole_metadata = all_metadata[4];
  size_t hole_size = hole_metadata->size();
  int64_t hole_offset = hole_metadata->start_offset();
  allocator.Discard(std::move(hole_metadata));

  auto& larger_hole_metadata = all_metadata[9];
  int64_t larger_hole_offset = larger_hole_metadata->start_offset();
  allocator.Discard(std::move(larger_hole_metadata));

  std::string random_data = base::RandBytesAsString(hole_size);
  auto metadata = allocator.Write(random_data.c_str(), random_data.size());
  // Exact fit.
  EXPECT_EQ(metadata->start_offset(), hole_offset);
  allocator.Discard(std::move(metadata));

  // -1 to check that this is not best fit.
  random_data = base::RandBytesAsString(hole_size - 1);
  metadata = allocator.Write(random_data.c_str(), random_data.size());
  EXPECT_EQ(metadata->start_offset(), larger_hole_offset);
}

TEST_F(DiskDataAllocatorTest, FreeChunksMerging) {
  constexpr size_t kSize = 100;

  auto allocator = std::make_unique<InMemoryDataAllocator>();
  auto chunks = Allocate(allocator.get(), kSize, 4);
  EXPECT_EQ(static_cast<int64_t>(4 * kSize), allocator->disk_footprint());
  EXPECT_EQ(0u, allocator->free_chunks_size());

  // Layout is (indices in |chunks|):
  // | 0 | 1 | 2 | 3 |
  // Discarding a higher index after a lower one triggers merging on the left.

  // Merge left.
  allocator->Discard(std::move(chunks[0]));
  EXPECT_EQ(1u, allocator->FreeChunks().size());
  allocator->Discard(std::move(chunks[1]));
  EXPECT_EQ(1u, allocator->FreeChunks().size());
  EXPECT_EQ(2 * kSize, allocator->FreeChunks().begin()->second);
  allocator->Discard(std::move(chunks[2]));
  EXPECT_EQ(1u, allocator->FreeChunks().size());
  EXPECT_EQ(3 * kSize, allocator->FreeChunks().begin()->second);
  EXPECT_EQ(3 * kSize, allocator->free_chunks_size());
  allocator->Discard(std::move(chunks[3]));
  EXPECT_EQ(1u, allocator->FreeChunks().size());
  EXPECT_EQ(4 * kSize, allocator->FreeChunks().begin()->second);
  EXPECT_EQ(static_cast<int64_t>(4 * kSize), allocator->disk_footprint());

  allocator = std::make_unique<InMemoryDataAllocator>();
  chunks = Allocate(allocator.get(), kSize, 4);

  // Merge right.
  allocator->Discard(std::move(chunks[3]));
  EXPECT_EQ(1u, allocator->FreeChunks().size());
  allocator->Discard(std::move(chunks[2]));
  EXPECT_EQ(1u, allocator->FreeChunks().size());
  EXPECT_EQ(2 * kSize, allocator->FreeChunks().begin()->second);
  allocator->Discard(std::move(chunks[0]));
  EXPECT_EQ(2u, allocator->FreeChunks().size());
  EXPECT_EQ(3 * kSize, allocator->free_chunks_size());
  // Multiple merges: left, then right.
  allocator->Discard(std::move(chunks[1]));
  EXPECT_EQ(1u, allocator->FreeChunks().size());

  allocator = std::make_unique<InMemoryDataAllocator>();
  chunks = Allocate(allocator.get(), kSize, 4);

  // Left then right merging.
  allocator->Discard(std::move(chunks[0]));
  allocator->Discard(std::move(chunks[2]));
  EXPECT_EQ(2u, allocator->FreeChunks().size());
  allocator->Discard(std::move(chunks[1]));
  EXPECT_EQ(1u, allocator->FreeChunks().size());
}

TEST_F(DiskDataAllocatorTest, ProvideInvalidFile) {
  DiskDataAllocator allocator;
  EXPECT_FALSE(allocator.may_write());
  allocator.ProvideTemporaryFile(base::File());
  EXPECT_FALSE(allocator.may_write());
}

TEST_F(DiskDataAllocatorTest, ProvideValidFile) {
  base::FilePath path;
  if (!base::CreateTemporaryFile(&path))
    GTEST_SKIP() << "Cannot create temporary file.";

  int flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_READ |
              base::File::FLAG_WRITE | base::File::FLAG_DELETE_ON_CLOSE;
  auto file = base::File(base::FilePath(path), flags);
  if (!file.IsValid())
    GTEST_SKIP() << "Cannot create temporary file.";

  DiskDataAllocator allocator;
  EXPECT_FALSE(allocator.may_write());
  allocator.ProvideTemporaryFile(std::move(file));
  EXPECT_TRUE(allocator.may_write());

  // Test read/write with a real file.
  constexpr size_t kSize = 1000;
  std::string random_data = base::RandBytesAsString(kSize);
  auto metadata = allocator.Write(random_data.c_str(), random_data.size());
  if (!metadata)
    GTEST_SKIP() << "Disk full?";

  EXPECT_EQ(kSize, metadata->size());

  auto read_data = std::vector<char>(kSize);
  allocator.Read(*metadata, &read_data[0]);

  EXPECT_EQ(0, memcmp(&read_data[0], random_data.c_str(), kSize));
}

}  // namespace blink


text:
require 'action_controller'

require 'ensure_param_exists'
require 'pry'

class TestClass < ActionController::Base
  include EnsureParamExists
end

describe EnsureParamExists do
  before :each do
    class TestClass
      attr_accessor :params
    end
  end

  subject { TestClass.new }

  context "ensure_param" do
    it "sets a before_filter" do
      TestClass.should_receive(:before_filter).with(:ensure_p1_exists, {})

      class TestClass
        ensure_param :p1
      end
    end

    it "sets a before_filter with opts" do
      TestClass.should_receive(:before_filter).with(:ensure_p1_exists, { only: [:show] })

      class TestClass
        ensure_param :p1, only: [:show]
      end
    end

    context "generated method logic" do
      it "accepts symbols" do
        class TestClass
          ensure_param :p1
        end

        TestClass.method_defined?(:ensure_p1_exists).should be_true
      end

      context "param is not set" do
        before :each do
          class TestClass
            ensure_param :p1
          end

          subject.params = { p1: nil }
        end

        it "renders with status: 422" do
          subject.should_receive(:render).with(hash_including(status: 422))
          subject.ensure_p1_exists
        end

        it "renders with an error response" do
          subject.should_receive(:render).with(hash_including(json: { success: false, message: "missing p1 parameter" }))
          subject.ensure_p1_exists
        end
      end
    end
  end

  context "ensure_any_params" do
    it "sets a before_filter" do
      TestClass.should_receive(:before_filter).with(:ensure_p1_or_p2_exists, {})

      class TestClass
        ensure_any_params :p1, :p2
      end
    end

    it "sets a before_filter with opts" do
      TestClass.should_receive(:before_filter).with(:ensure_p1_or_p2_exists, { only: [:show] })

      class TestClass
        ensure_any_params :p1, :p2, only: [:show]
      end
    end

    context "generated method logic" do
      before :each do
        class TestClass
          ensure_any_params :p1, :p2
        end
      end

      it "accepts symbols" do
        TestClass.method_defined?(:ensure_p1_or_p2_exists).should be_true
      end

      it "returns nil if parameter 1 and parameter 2 are set" do
        subject.params = { p1: 'set', p2: 'set' }
        subject.should_not_receive(:render)

        subject.ensure_p1_or_p2_exists
      end

      it "renders nil if parameter 1 is set and parameter 2 is not set" do
        subject.params = { p1: 'set', p2: nil }
        subject.should_not_receive(:render)

        subject.ensure_p1_or_p2_exists
      end

      it "returns nil if parameter 1 is not set and parameter 2 is set" do
        subject.params = { p1: 'set', p2: nil }
        subject.should_not_receive(:render)

        subject.ensure_p1_or_p2_exists
      end

      context "parameters 1 and parameters 2 not set" do
        before :each do
          subject.params = { p1: nil, p2: nil }
        end

        it "renders with status: 422" do
          subject.should_receive(:render).with(hash_including(status: 422))
          subject.ensure_p1_or_p2_exists
        end

        it "renders with an error response" do
          subject.should_receive(:render).with(hash_including(json: { success: false, message: "missing p1 or p2 parameter" }))
          subject.ensure_p1_or_p2_exists
        end
      end
    end

    context "ensure_all_params" do
      it "sets a before_filter" do
        TestClass.should_receive(:before_filter).with(:ensure_p1_and_p2_exists, {})

        class TestClass
          ensure_all_params :p1, :p2
        end
      end

      it "sets a before_filter with opts" do
        TestClass.should_receive(:before_filter).with(:ensure_p1_and_p2_exists, { only: [:show] })

        class TestClass
          ensure_all_params :p1, :p2, only: [:show]
        end
      end

      context "generated method logic" do
        before :each do
          class TestClass
            ensure_all_params :p1, :p2
          end
        end

        it "accepts symbols" do
          TestClass.method_defined?(:ensure_p1_and_p2_exists).should be_true
        end

        it "returns nil if parameter 1 and parameter 2 are set" do
          subject.params = { p1: 'set', p2: 'set' }
          subject.should_not_receive(:render)

          subject.ensure_p1_and_p2_exists
        end

        it "renders status: 422 if parameter 1 is set and parameter 2 is not set" do
          subject.params = { p1: 'set', p2: nil }
          subject.should_receive(:render).with(hash_including(status: 422))

          subject.ensure_p1_and_p2_exists
        end

        it "returns status: 422 if parameter 1 is not set and parameter 2 is set" do
          subject.params = { p1: 'set', p2: nil }
          subject.should_receive(:render).with(hash_including(status: 422))

          subject.ensure_p1_and_p2_exists
        end

        context "parameters 1 and parameters 2 not set" do
          before :each do
            subject.params = { p1: nil, p2: nil }
          end

          it "renders with status: 422" do
            subject.should_receive(:render).with(hash_including(status: 422))
            subject.ensure_p1_and_p2_exists
          end

          it "renders with an error response" do
            subject.should_receive(:render).with(hash_including(json: { success: false, message: "missing p1 and p2 parameter" }))
            subject.ensure_p1_and_p2_exists
          end
        end
      end
    end
  end

end


text:
import os.path
import sys

ordered_game_files = [
  'util',
  'event_emitter',
  'position',

  'level',
  'graphic',
  'background_graphic',
  'entity_graphic',
  'entity_sprite_graphic',

  'factory',
  'graphic_factory',
  'sprite_builder',
  'simple_sprite_builder',

  'game_info',
  'keybindings',

  'move_behavior',
  'tracking_move_behavior',
  'user_input_move_behavior',

  'animation',

  'entity',
  'player',

  'entity_sprite_factory',
  'entity_factory',

  'enemy_spawner',
  'level_factory',
  'renderer',
  'game',
]
for i, file_name in enumerate(ordered_game_files):
  ordered_game_files[i] = '<script type=\"text/javascript" src="%s.js"></script>' % (file_name)

template = open('nodejs_web/index.html', 'r+')
html_content = template.read()
template.close()

game_files = []
if len(sys.argv) >= 2 and sys.argv[1] == "PROD":
  game_files = ordered_game_files
else:
  for coffee_file in os.listdir('coffee'):
    fileName = coffee_file[:-len('.coffee')]
    filePath = '<script type="text/javascript" src="%s.js"></script>' % (fileName)
    game_files.append(filePath)

js_content = '\n  '.join(game_files)
if len(sys.argv) >= 2 and sys.argv[1] == "DEV":
  js_content *= len(game_files)

html_content = html_content.replace('$GAME FILES$', js_content)
output = open('bin/index.html', 'w')
output.write(html_content)
output.close()


text:
package net.glowstone.net.codec.play.entity;

import com.flowpowered.network.Codec;
import com.flowpowered.network.util.ByteBufUtils;
import io.netty.buffer.ByteBuf;
import net.glowstone.net.message.play.entity.CollectItemMessage;

import java.io.IOException;

public final class CollectItemCodec implements Codec<CollectItemMessage> {
    @Override
    public CollectItemMessage decode(ByteBuf buf) throws IOException {
        int id = ByteBufUtils.readVarInt(buf);
        int collector = ByteBufUtils.readVarInt(buf);
        return new CollectItemMessage(id, collector);
    }

    @Override
    public ByteBuf encode(ByteBuf buf, CollectItemMessage message) throws IOException {
        ByteBufUtils.writeVarInt(buf, message.getId());
        ByteBufUtils.writeVarInt(buf, message.getCollector());
        return buf;
    }
}


text:
import sys
sys.path.append('../.')
sys.path.append('.')
import h5py
import pgmlink as track
import numpy as np
import math
import os
import os.path as path
import argparse
from hytra.util.progressbar import ProgressBar

def get_feature(h5file, feature_path, object_id):
    if not feature_path in h5file:
        raise Exception("Feature %s not found in %s." % (feature_path, h5file.filename))
    return h5file[feature_path][object_id, ...]

def get_feature_vector(traxel, feature_name, num_dimensions):
    #print traxel.print_available_features()
    result = []
    for i in range(num_dimensions):
        try:
            result.append(traxel.get_feature_value(feature_name, i))
        except:
            print("Error when accessing feature {}[{}] for traxel (Id={},Timestep={})".format(feature_name,
                                                                                i,
                                                                                traxel.Id,
                                                                                traxel.Timestep))
            print "Available features are: "
            print traxel.print_available_features()
            raise Exception
    return result

# def rank_solutions(ground_truth_filename, feature_vector_filename, proposal_basename, num_iterations):
#     import structsvm
#     proposal_filenames = [proposal_basename + '_' + str(i) + '.txt' for i in range(num_iterations)]

#     problem = structsvm.struct_svm_ranking_problem(feature_vector_filename,
#                                                    ground_truth_filename,
#                                                    proposal_filenames)
#                                                    #,args.loss_weights)
#     solver = structsvm.struct_svm_solver_primal(problem)
#     weights = solver.solve()
#     weights = np.array(weights)
#     problem.print_scores(weights)

#     print("Found weights: {}".format(weights))
#     return weights

class LineagePart:
    """
    Parent class for all parts of a lineage, e.g. track, division, lineage
    """

    def __init__(self):
        self.features = {}
        pass

    track_feature_map = {
        'single': [
            'track_outlier_svm_score',
            'track_length'
        ],
        'mean_var': [
            'sq_diff_RegionCenter',
            'sq_diff_Count',
            'sq_diff_Mean',
            'sq_diff_Variance',
            'sq_accel_RegionCenter',
            'sq_accel_Count',
            'sq_accel_Mean',
            'sq_accel_Variance',
            'angles_RegionCenter',
            # 'outlier_id_RegionCenter',
            'outlier_id_Count',
            'outlier_id_Mean',
            'outlier_id_Variance',
            'diff_outlier_RegionCenter',
            'diff_outlier_Count',
            'diff_outlier_Mean',
            'diff_outlier_Variance',
            'Count',
            'Mean',
            'Variance',
            'Sum',
            'Kurtosis',
            'Skewness',
            'Weighted<PowerSum<0> >',
            'Central< PowerSum<2> >',
            'Central< PowerSum<3> >',
            'Central< PowerSum<4> >',
            'detProb',
            'divProb'
        ]
    }

    division_feature_map = {
        'single': [
            'div_outlier_svm_score'
        ],
        'mean_var': [
            'child_decel_Count',
            'child_decel_Count_outlier_score',
            'child_decel_Mean',
            'child_decel_Mean_outlier_score',
            'child_decel_RegionCenter',
            'child_decel_RegionCenter_outlier_score',
            'child_decel_Variance',
            'child_decel_Variance_outlier_score',
            'sq_diff_Count',
            'sq_diff_Count_outlier_score',
            'sq_diff_Mean',
            'sq_diff_Mean_outlier_score',
            'sq_diff_RegionCenter',
            'sq_diff_RegionCenter_outlier_score',
            'sq_diff_Variance',
            'sq_diff_Variance_outlier_score',
            'detProb',
            'divProb'
        ]
    }

    all_feature_names = track_feature_map['single'] \
                        + ['mean_' + f for f in track_feature_map['mean_var']] \
                        + ['var_' + f for f in track_feature_map['mean_var']] \
                        + division_feature_map['single'] \
                        + ['mean_' + f for f in division_feature_map['mean_var']] \
                        + ['var_' + f for f in division_feature_map['mean_var']]

    @staticmethod
    def get_num_track_features():
        return 2 * len(LineagePart.track_feature_map['mean_var']) + len(LineagePart.track_feature_map['single'])

    @staticmethod
    def get_num_division_features():
        return 2 * len(LineagePart.division_feature_map['mean_var']) + len(LineagePart.division_feature_map['single'])

    @staticmethod
    def get_feature_vector_size():
        return LineagePart.get_num_track_features() + LineagePart.get_num_division_features()

    @staticmethod
    def weight_idx_to_feature(idx):
        return LineagePart.all_feature_names[idx]

    @staticmethod
    def feature_to_weight_idx(feature_name):
        return LineagePart.all_feature_names.index(feature_name)

    @staticmethod
    def get_expanded_feature_names(series_expansion_range):
        len_track_feat = LineagePart.get_num_track_features()

        expanded_feature_names = []
        for f in LineagePart.all_feature_names[:len_track_feat]:
            for i in range(series_expansion_range[0], series_expansion_range[1]):
                exponent = str(i) + " - "
                expanded_feature_names += [exponent + f, ]

        expanded_feature_names += LineagePart.all_feature_names[len_track_feat:]
        return expanded_feature_names

    def get_feature_vector(self):
        """
        This should return the feature vector (concatenated track and division features)
        such that it can be multiplied by the weight vector to return this track's score
        :return: a numpy array
        """
        result = np.zeros(LineagePart.get_feature_vector_size())

        for i, k in enumerate(LineagePart.all_feature_names):
            if k in self.features:
                result[i] = self.features[k]

        return result

    def get_expanded_feature_vector(self, series_expansion_range):
        """
        To allow for using length scaled versions of the track features,
        this vector contains modified duplicates the track features,
        followed by the division features.
        The modification can be specified by overwriting the expansion_modifier function
        :param series_expansion_range: (lower_bound, upper_bound) of the expansion range (used as exponent)
        :return:
        """
        num_expansions = series_expansion_range[1] - series_expansion_range[0]
        len_track_feat = LineagePart.get_num_track_features()

        result = np.zeros(num_expansions * len_track_feat + LineagePart.get_num_division_features())

        # insert duplicated and modified track features
        # (from [f1, f2, f3] to [f'1, f''1, f'''1, f'2, f''2, f'''2, f'3, f''3, f'''3]
        for i, k in enumerate(LineagePart.all_feature_names[:len_track_feat]):
            if k in self.features:
                for e in range(num_expansions):
                    result[i * num_expansions + e] = self.features[k] * self.expansion_factor(e)

        # insert division features just once
        for i, k in enumerate(LineagePart.all_feature_names[len_track_feat:]):
            if k in self.features:
                result[num_expansions * len_track_feat + i] = self.features[k]

        return result

    def expansion_factor(self, expansion):
        """
        Expansion modifier, defaults to identity.
        :param expansion:
        :return:
        """
        return 1

    def extract(self, track_features_h5):
        """
        Extract all important information about this part of the lineage from the features h5 file
        """
        raise NotImplementedError("Please Specialize this method")

    def compute_score(self, weights, series_expansion_range=[0,1], feature_means=None, feature_variances=None):
        """
        :return: the score as linear combination of feature vector and supplied weights
        """
        import structsvm
        feature_vec = self.get_expanded_feature_vector(series_expansion_range)
        feature_vec = np.expand_dims(feature_vec, axis=1)
        if feature_means != None and feature_variances != None:
            structsvm.utils.apply_feature_normalization(feat_vec, feature_means, feature_variances)
        return np.dot(weights, feature_vec[:,0])

class Track(LineagePart):
    """
    A track is a part of a lineage tree between two division/appearance/disappearance events
    """

    def __init__(self, track_id):
        LineagePart.__init__(self)
        self.track_id = track_id
        # number of traxels in track
        self.length = 0

        # reference to division that created this track. -1 if it stems from appearance
        self.start_division_id = -1
        # reference to division where this track ends. -1 if it disappears
        self.end_division_id = -1

        # first and last traxel ids
        self.start_traxel_id = -1
        self.end_traxel_id = -1
        self.traxels = None

        # map of named features of this track
        self.features = {}

    def extract_region_features(self, ts, region_features):
        """
        Extract the region features of this track's traxels from the traxelstore,
        and compute mean an variance.
        """
        assert(self.traxels != None and len(self.traxels) > 0)

        # temporary storage for features over traxels
        f = {}

        for timestep, idx in self.traxels.transpose():
            traxel = ts.get_traxel(int(idx), int(timestep))
            for feat_name, feat_dims in region_features:
                if feat_name not in f:
                    f[feat_name] = []
                f[feat_name].append(get_feature_vector(traxel, feat_name, feat_dims))

        # create a feature matrix per feature, and store mean + var
        for k in LineagePart.track_feature_map['mean_var']:
            if k in f:
                v = f[k]
                feature_matrix = np.array(v)
                # compute mean & variance
                self.features['mean_' + k] = np.mean(feature_matrix)
                self.features['var_'  + k] = np.var(feature_matrix)

        # get the feature value for the arguments where mean + var doesn't make sense
        for k in LineagePart.track_feature_map['single']:
            # split multi-dim-features
            if '[' in k:
                try:
                    k, idx = k.split('[')
                    idx = int(idx.replace(']', ''))
                except:
                    print "Did not recognize format of feature name: ", k
                    idx = 0
            else:
                idx = 0

            if k in f:
                feature_matrix = np.array(f[k]).flatten()
                self.features[k] = feature_matrix[idx]

    def extract(self, track_features_h5):
        """
        Get the higher order features of this track from the HDF5 file,
        and compute the mean of each feature.
        """
        t_features = track_features_h5['tracks/' + str(self.track_id) + '/']
        self.length = int(t_features['track_length'].value[0, 0])
        self.traxels = t_features['traxels'].value
        assert(self.traxels.shape[1] > 0)
        self.start_traxel_id = tuple(self.traxels[:, 0])
        self.end_traxel_id = tuple(self.traxels[:, -1])

        # get all features from the HDF5 file
        for v in LineagePart.track_feature_map['mean_var']:
            try:
                feature_matrix = t_features[v].value
                self.features['mean_' + v] = np.mean(feature_matrix)
                self.features['var_' + v] = np.var(feature_matrix)
            except:
                # print("Could not find feature {} for track {}".format(v, self.track_id))
                pass
        try:
            self.features['track_outlier_svm_score'] = track_features_h5['track_outliers_svm'].value.flatten()[self.track_id]
        except:
            self.features['track_outlier_svm_score'] = -1

    def expansion_factor(self, expansion):
        """
        Expansion modifier for tracks is to multiply by powers of the length
        :param expansion:
        :return:
        """
        return math.pow(self.length, expansion)

class Division(LineagePart):
    def __init__(self, division_id):
        LineagePart.__init__(self)
        self.division_id = division_id

        # track ids
        self.parent_track_id = -1
        self.children_track_ids = [-1, -1]

        # traxel ids
        self.parent_traxel_id = -1
        self.children_traxel_ids = [-1, -1]

        # set of features of this division
        self.features = {}

    def extract(self, track_features_h5):
        d_features = track_features_h5['divisions/' + str(self.division_id) + '/']
        traxels = d_features['traxels'].value
        assert(traxels.shape[1] == 3)
        self.parent_traxel_id = tuple(traxels[:, 0])
        self.children_traxel_ids = [tuple(traxels[:, 1]), tuple(traxels[:, 2])]

        # get all features from the HDF5 file
        for v in LineagePart.division_feature_map['mean_var']:
            try:
                feature_matrix = d_features[v].value
                self.features['mean_' + v] = np.mean(feature_matrix)
                self.features['var_' + v] = np.var(feature_matrix)
            except:
                # print("Could not find feature {} for division {}".format(v, self.division_id))
                pass

        try:
            self.features['div_outlier_svm_score'] = track_features_h5['division_outliers_svm'].value.flatten()[self.division_id]
        except:
            self.features['div_outlier_svm_score'] = -1

class LineageTree(LineagePart):
    """
    A lineage tree holds all tracks and divisions that have one common ancestor.
    The returned feature vectors are the averaged features over tracks and divisions whithin the lineage tree.
    """

    def __init__(self, lineage_tree_id, track, tracks, divisions):
        LineagePart.__init__(self)
        self.lineage_tree_id = lineage_tree_id
        self.tracks = [track]
        self.divisions = []
        self.length = 0 # todo remove this, just left in to allow for unpickling

        # follow the supplied track along divisions
        from collections import deque
        queue = deque([track])

        while len(queue) > 0:
            t = queue.popleft()
            if t.end_division_id != -1:
                self.divisions.append(divisions[t.end_division_id])
                for i in [0, 1]:
                    next_track_id = self.divisions[-1].children_track_ids[i]
                    if next_track_id == -1:
                        print("Warning: lineage tree could not find child {} of division {}, "
                              "discarding branch.".format(i, self.divisions[-1].division_id))
                        continue
                    self.tracks.append(tracks[next_track_id])
                    queue.append(tracks[next_track_id])

    def get_feature_vector(self):
        result = np.zeros(self.get_feature_vector_size())

        for t in self.tracks:
            result += t.get_feature_vector() / len(self.tracks)

        for d in self.divisions:
            result += d.get_feature_vector() / len(self.divisions)

        return result

    def get_expanded_feature_vector(self, series_expansion_range):
        num_expansions = series_expansion_range[1] - series_expansion_range[0]
        result = np.zeros(num_expansions * self.get_num_track_features() + self.get_num_division_features())

        for t in self.tracks:
            result += t.get_expanded_feature_vector(series_expansion_range) / len(self.tracks)

        for d in self.divisions:
            result += d.get_expanded_feature_vector(series_expansion_range) / len(self.divisions)

        return result

    def get_all_traxels(self):
        """
        Assuming that no divisions start with an appearance, or end at disappearances,
        all participating traxels are stored inside the tracks.
        The traxels are returned as list tuples of (timestep, ID).
        """
        traxels = []
        for t in self.tracks:
            for i in xrange(t.traxels.shape[1]):
                traxels.append(tuple(t.traxels[0:2, i]))
        return traxels

def create_and_link_tracks_and_divisions(track_features_h5, ts, region_features):
    # storage for all tracks and divisions
    tracks = {}
    divisions = {}

    # mapping of traxelID at front and back of track to track_id
    track_starts_with_traxel_id = {}
    track_ends_with_traxel_id = {}

    pb = ProgressBar(0, len(track_features_h5['tracks'].keys()) + len(track_features_h5['divisions'].keys()))
    print("Extracting Tracks and Divisions")

    for track_id in track_features_h5['tracks'].keys():
        pb.show()
        track_id_int = int(track_id)
        t = Track(track_id_int)
        t.extract(track_features_h5)
        t.extract_region_features(ts, region_features)

        # store in container
        tracks[track_id_int] = t

        # create mappings
        track_starts_with_traxel_id[t.start_traxel_id] = track_id_int
        track_ends_with_traxel_id[t.end_traxel_id] = track_id_int

    max_length = max([t.length for t in tracks.values()])
    for t in tracks.values():
        t.features['track_length'] = float(t.length) / max_length

    for division_id in track_features_h5['divisions'].keys():
        pb.show()
        division_id_int = int(division_id)
        d = Division(division_id_int)
        d.extract(track_features_h5)

        # find the tracks that are connected by this division
        # and update information in the tracks
        try:
            d.parent_track_id = track_ends_with_traxel_id[d.parent_traxel_id]
            tracks[d.parent_track_id].end_division_id = division_id_int
        except KeyError as e:
            print("Could not find parent track of division {}: ".format(division_id), e.message)

        for i in [0, 1]:
            try:
                d.children_track_ids[i] = track_starts_with_traxel_id[d.children_traxel_ids[i]]
                tracks[d.children_track_ids[i]].start_division_id = division_id_int
            except KeyError as e:
                print("Could not find child track of division {}: ".format(division_id), e.message)

        # store in container
        divisions[division_id_int] = d
    return tracks, divisions

def build_lineage_trees(tracks, divisions):
    # select all tracks that have no parent division (appearances)
    appearances = [t for t in tracks.values() if t.start_division_id == -1]

    # create a new lineage tree for each of those
    lineageTrees = [LineageTree(l_id, t, tracks, divisions) for l_id, t in enumerate(appearances)]

    return lineageTrees

def score_solutions(tracks, divisions, lineage_trees, out_dir, reranker_weight_filename, series_expansion_range):
    # if reranker weights are already given, compute overall, and track scores and plot a histogram
    if reranker_weight_filename and len(reranker_weight_filename) > 0:
        reranker_weights = np.loadtxt(reranker_weight_filename)

        track_scores = [t.compute_score(reranker_weights, series_expansion_range) for t in tracks.values()]
        division_scores = [d.compute_score(reranker_weights, series_expansion_range) for d in divisions.values()]
        lineage_scores = [l.compute_score(reranker_weights, series_expansion_range) for l in lineage_trees]
        overall_score = sum(lineage_scores)

        for s_name, scores in [("track_scores", track_scores),
                               ("division_scores", division_scores),
                               ("lineage_scores", lineage_scores)]:
            fn = out_dir.rstrip('/') + '/' + s_name + '.txt'
            print("Saving {} to:".format(s_name, fn))
            np.savetxt(fn, scores)

            import matplotlib
            matplotlib.use('Agg')
            import matplotlib.pyplot as plt
            plt.figure()
            plt.hist(scores, 100)
            plt.savefig(out_dir.rstrip('/') + '/' + s_name + '.pdf')

            # todo: compute loss and/or precision of each track / division / lineage and plot the correspondance!

        print("Overall score of tracking is: {}".format(overall_score))
        return overall_score
    else:
        return -1

def compute_traxel_set_measures(args):
    (traxel_set, associations, filename_pairs, timestep0) = args
    from empryonic.learning import quantification as quant
    taxonomies = []

    for i, v in enumerate(filename_pairs[1:]):
        t = quant.compute_filtered_taxonomy(associations[i],
                                            associations[i + 1],
                                            v[0],
                                            v[1],
                                            traxel_set,
                                            i + timestep0 + 1)
        taxonomies.append(t)
    overall = reduce(quant.Taxonomy.union, taxonomies)
    return overall

def compare_lineage_trees_to_gt(gt_dir, proposal_dir, lineage_trees):
    import compare_tracking
    from multiprocessing import Pool, cpu_count
    import itertools

    print("Parallelizing over {} cores".format(cpu_count()))
    processing_pool = Pool(cpu_count())

    gt_filenames, proposal_filenames = compare_tracking.get_tracking_filenames(gt_dir, proposal_dir)
    first_timestep = int(os.path.splitext(os.path.basename(gt_filenames[0]))[0])

    timesteps = min(len(gt_filenames), len(proposal_filenames))
    associations = compare_tracking.construct_associations(gt_filenames, proposal_filenames, timesteps)

    filename_pairs = zip(gt_filenames[0:timesteps], proposal_filenames[0:timesteps])
    lineage_tree_traxels = [lt.get_all_traxels() for lt in lineage_trees]

    pb = ProgressBar(0, len(lineage_trees))
    lineage_tree_measures = []
    for measure in processing_pool.imap(compute_traxel_set_measures,
                                        itertools.izip(lineage_tree_traxels,
                                                       itertools.repeat(associations),
                                                       itertools.repeat(filename_pairs),
                                                       itertools.repeat(first_timestep))):
        lineage_tree_measures.append(measure)
        pb.show()

    return lineage_tree_measures

def extract_features_and_compute_score(reranker_weight_filename,
                                       outlier_svm_filename,
                                       out_dir,
                                       iteration,
                                       hypotheses_graph,
                                       ts,
                                       fov,
                                       feature_vector_filename,
                                       region_features,
                                       series_expansion_range=[-1, 2]):

    # extract higher order features and per-track features
    print("Extracting features of solution {}\n\tCreating Feature extractor...".format(iteration))
    track_features_filename = out_dir.rstrip('/') + '/iter_' + str(iteration) + '/track_features.h5'
    feature_extractor = track.TrackingFeatureExtractor(hypotheses_graph, fov)

    # load outlier SVMs if available
    if len(outlier_svm_filename) > 0:  # when the svm was trained in this run, it automatically sets load_outlier_svm
        with open(outlier_svm_filename, 'r') as svm_dump:
            import pickle
            outlier_track_svm = pickle.load(svm_dump)
            outlier_division_svm = pickle.load(svm_dump)

            feature_extractor.set_track_svm(outlier_track_svm)
            feature_extractor.set_division_svm(outlier_division_svm)
            print("Trained outlier SVM loaded from " + outlier_svm_filename)

    # extract all the features and save them to disk
    try:
        os.remove(track_features_filename)
    except:
        pass
    feature_extractor.set_track_feature_output_file(track_features_filename)
    sys.stdout.write("\tComputing features...")
    feature_extractor.compute_features()
    print("...Done")

    # create complete lineage trees with extracted features:
    with h5py.File(track_features_filename, 'r') as track_features_h5:
        tracks, divisions = create_and_link_tracks_and_divisions(track_features_h5, ts, region_features)
        lineage_trees = build_lineage_trees(tracks, divisions)

    # save lineage trees
    lineage_tree_dump_filename = out_dir.rstrip('/') + '/iter_' + str(iteration) + '/lineage_trees.dump'
    save_lineage_dump(lineage_tree_dump_filename, tracks, divisions, lineage_trees)

    # accumulate feature vectors
    feature_vector = lineage_trees[0].get_expanded_feature_vector(series_expansion_range)
    for lt in lineage_trees[1:]:
        feature_vector += lt.get_expanded_feature_vector(series_expansion_range)

    # compute score if weight file is given
    overall_score = score_solutions(tracks, divisions, lineage_trees,
                                    out_dir.rstrip('/') + '/iter_' + str(iteration),
                                    reranker_weight_filename,
                                    series_expansion_range)

    return feature_vector, overall_score, LineagePart.get_expanded_feature_names(series_expansion_range)

def load_lineage_dump(filename):
    with open(filename, 'r') as lineage_dump:
        import pickle
        tracks = pickle.load(lineage_dump)
        divisions = pickle.load(lineage_dump)
        lineage_trees = pickle.load(lineage_dump)

    return tracks, divisions, lineage_trees

def save_lineage_dump(filename, tracks, divisions, lineage_trees):
    with open(filename, 'w') as lineage_dump:
        import pickle
        pickle.dump(tracks, lineage_dump)
        pickle.dump(divisions, lineage_dump)
        pickle.dump(lineage_trees, lineage_dump)

def analyze_lineage_dump(args):
    # load lineages
    tracks, divisions, lineage_trees = load_lineage_dump(args.lineage_dump_file)
    # find gt an proposal files that start with a number and end with h5

    # gt_filenames = [path.abspath(path.join(args.gt_path, fn))
    #                 for fn in os.listdir(args.gt_path) if fn.endswith('.h5') and fn[0].isdigit()]
    # gt_filenames.sort()
    # proposal_filenames = [path.abspath(path.join(args.proposal_path, fn))
    #                       for fn in os.listdir(args.proposal_path) if fn.endswith('.h5') and fn[0].isdigit()]
    # proposal_filenames.sort()

    # evaluate
    print("Analyzing {} lineage trees".format(len(lineage_trees)))
    taxonomies = compare_lineage_trees_to_gt(args.gt_path, args.proposal_path, lineage_trees)
    precisions = [t.precision() for t in taxonomies]
    recalls = [t.recall() for t in taxonomies]
    fmeasures = [t.f_measure() for t in taxonomies]

    def replaceNan(a):
        if np.isnan(a):
            return 0.0
        else:
            return a

    precisions = map(replaceNan, precisions)
    recalls = map(replaceNan, recalls)
    fmeasures = map(replaceNan, fmeasures)
    np.savetxt(args.out_dir.rstrip('/') + '/precisions.txt', np.array(precisions))
    np.savetxt(args.out_dir.rstrip('/') + '/recalls.txt', np.array(recalls))
    np.savetxt(args.out_dir.rstrip('/') + '/fmeasures.txt', np.array(fmeasures))
    import matplotlib

    matplotlib.use('Agg')
    import matplotlib.pyplot as plt

    plt.figure()
    plt.hist(precisions, 100)
    plt.savefig(args.out_dir.rstrip('/') + '/precisions.pdf')

    plt.figure()
    plt.hist(recalls, 100)
    plt.savefig(args.out_dir.rstrip('/') + '/recalls.pdf')

    plt.figure()
    plt.hist(fmeasures, 100)
    plt.savefig(args.out_dir.rstrip('/') + '/fmeasures.pdf')

    if len(args.weight_filename) > 0 and os.path.isfile(args.weight_filename):
        # load weights and compute all scores
        weights = np.loadtxt(args.weight_filename)
        assert len(weights) == len(lineage_trees[0].get_feature_vector())
        scores = [np.dot(weights, lt.get_feature_vector()) for lt in lineage_trees]

        plt.figure()
        plt.scatter(scores, precisions)
        plt.savefig(args.out_dir.rstrip('/') + '/score_vs_precision.pdf')

        plt.figure()
        plt.scatter(scores, fmeasures)
        plt.savefig(args.out_dir.rstrip('/') + '/score_vs_fmeasure.pdf')

        ## -----------------------------
        ## how to test lineage tree construction:
        ## -----------------------------
        # import trackingfeatures
        # import pickle
        # import h5py
        # out_dir = '/Users/chaubold/hci/data/hufnagel2012-08-03/current-bests/m4-rerank-2015-03-24_17-29-18/'
        # ts_in = open('drosophila-7ts-2015-03-22_12-56-32.dump', 'rb')
        # ts = pickle.load(ts_in)
        # fs = pickle.load(ts_in)
        # ts.set_feature_store(fs)
        # ts_in.close()
        # def getRegionFeatures(ndim):
        # region_features = [
        #             ("RegionCenter", ndim),
        #             ("Count", 1),
        #             ("Variance", 1),
        #             ("Sum", 1),
        #             ("Mean", 1),
        #             ("RegionRadii", ndim),
        #             ("Central< PowerSum<2> >", 1),
        #             ("Central< PowerSum<3> >", 1),
        #             ("Central< PowerSum<4> >", 1),
        #             ("Kurtosis", 1),
        #             ("Maximum", 1),
        #             ("Minimum", 1),
        #             ("RegionAxes", ndim**2),
        #             ("Skewness", 1),
        #             ("Weighted<PowerSum<0> >", 1),
        #             ("Coord< Minimum >", ndim),
        #             ("Coord< Maximum >", ndim)
        #         ]
        #     return region_features
        # iteration = 0
        # track_features_filename = out_dir.rstrip('/') + '/iter_' + str(iteration) + '/track_features.h5'
        # track_features_h5 = h5py.File(track_features_filename, 'r')
        # tracks, divisions = trackingfeatures.create_and_link_tracks_and_divisions(track_features_h5, ts, getRegionFeatures(3))
        # lineage_trees = trackingfeatures.build_lineage_trees(tracks, divisions)
        # track_features_h5.close()

if __name__ == "__main__":
    """
    Executing this script will take a lineage tree dump together with ground truth
    and proposal solution h5 files (containing the events). It then evaluates the
    quality of each lineage independently.
    """

    parser = argparse.ArgumentParser(description='Evaluate precision/recall/f-measure'
                                                 'for each lineage independently')
    parser.add_argument('--lineage-dump', required=True, type=str, dest='lineage_dump_file',
                        help='Filename of the lineage dump created by a multitrack run')
    parser.add_argument('--gt-path', required=True, type=str, dest='gt_path',
                        help='Path to folder containing the ground truth .h5 files')
    parser.add_argument('--proposal-path', required=True, type=str, dest='proposal_path',
                        help='Path to folder containing the proposal .h5 files')
    parser.add_argument('--out', type=str, dest='out_dir', default='.', help='Output directory')
    parser.add_argument('--weights', type=str, dest='weight_filename', default='',
                        help='If a filename for the weights is specified, this tool also plots scores vs precision etc')

    args = parser.parse_args()

    analyze_lineage_dump(args)


text:
<?php

namespace IngatlanCom\ApiClient\Service;

use GuzzleHttp\Client;
use IngatlanCom\ApiClient\ApiClient;

/**
 * Class ClientFactoryService
 *
 * Guzzle Client factory
 *
 * @package IngatlanCom\ApiClient\Service
 */
class ClientFactoryService
{
    /**
     * @param string $baseUrl
     * @param null   $config
     * @return Client
     */
    public function getClient($baseUrl = '', $config = null)
    {
        $config['base_uri'] = $baseUrl;
        $config['headers'] = ['X-Icom-Client-Version' => ApiClient::CLIENT_VERSION];

        return new Client($config);
    }
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use dosamigos\datepicker\DatePicker;
use dosamigos\tinymce\TinyMce;
use pendalf89\filemanager\widgets\FileInput;
/* @var $this yii\web\View */
/* @var $model backend\models\Books */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data']]); ?>

    <?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'description')->widget(TinyMce::className(), [
        'options' => ['rows' => 6],
        'language' => 'en_GB',

        'clientOptions' => [
            'plugins' => [
                "advlist autolink lists link charmap print preview anchor",
                "searchreplace visualblocks code fullscreen",
                "insertdatetime media table contextmenu paste",
                "image"
            ],
            //'menubar' => 'false',
            'toolbar' => "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",

        ]
    ]);?>

    <?= $form->field($model, 'author')->textInput(['maxlength' => true]) ?>
    <?= $form->field($model, 'source')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'file')->widget(FileInput::className(), [
        'buttonTag' => 'button',
        'buttonName' => 'Browse',
        'buttonOptions' => ['class' => 'btn btn-default'],
        'options' => ['class' => 'form-control'],
        // Widget template
        'template' => '
{input}{button}
',
        // Optional, if set, only this image can be selected by user
       // 'thumb' => 'original',
        // Optional, if set, in container will be inserted selected image
        'imageContainer' => '.img',
        // Default to FileInput::DATA_URL. This data will be inserted in input field
        'pasteData' => FileInput::DATA_URL,
        // JavaScript function, which will be called before insert file data to input.
        // Argument data contains file data.
        // data example: [alt: "Ведьма с кошкой", description: "123", url: "/uploads/2014/12/vedma-100x100.jpeg", id: "45"]
        'callbackBeforeInsert' => 'function(e, data) {
            console.log( data );
        }',
    ]); ?>

    <?= $form->field($model, 'download_link')->textInput(['maxlength' => true]) ?>
    <?= $form->field($model, 'sort_value')->textInput() ?>
    <?= $form->field($model, 'allowcomments')->textInput() ?> yes or no

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

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


text:
// Copyright (c) 2014 Baidu.com, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Author: qinzuoyan01@baidu.com (Qin Zuoyan)

// This file is modified from boost.
//
// Copyright Beman Dawes 2002, 2006
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See library home page at http://www.boost.org/libs/system

#ifndef _SOFA_PBRPC_SMART_PTR_CHECKED_DELETE_
#define _SOFA_PBRPC_SMART_PTR_CHECKED_DELETE_

namespace sofa {
namespace pbrpc {

template <typename T>
inline void checked_delete(T* px)
{
    typedef char type_must_be_complete[sizeof(T) ? 1 : -1 ];
    (void) sizeof(type_must_be_complete);
    delete px;
}

template<class T> inline void checked_array_delete(T * x)
{
    typedef char type_must_be_complete[ sizeof(T)? 1: -1 ];
    (void) sizeof(type_must_be_complete);
    delete [] x;
}

template<class T> struct checked_deleter
{
    typedef void result_type;
    typedef T * argument_type;

    void operator()(T * x) const
    {
        ::sofa::pbrpc::checked_delete(x);
    }
};

template<class T> struct checked_array_deleter
{
    typedef void result_type;
    typedef T * argument_type;

    void operator()(T * x) const
    {
        ::sofa::pbrpc::checked_array_delete(x);
    }
};

} // namespace pbrpc
} // namespace sofa

#endif // _SOFA_PBRPC_SMART_PTR_CHECKED_DELETE_

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


text:
<?php
namespace Qurel\Nodes;

class DeleteStatement extends Binary
{
    public $relation;
    public $limit;
    public $offset;
    public $orders = array();
    public $wheres = array();

    public function __construct(\Qurel\Table $relation = null, array $wheres = array())
    {
        parent::__construct($relation, $wheres);
        $this->relation =& $this->left;
        $this->wheres   =& $this->right;
    }
}