text:
package com.afterkraft.kraftrpg.api.role;

import java.util.List;
import java.util.Optional;
import java.util.Set;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;

import org.spongepowered.api.text.Text;

import com.google.common.base.Objects;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.reflect.TypeToken;
import ninja.leaping.configurate.ConfigurationNode;
import ninja.leaping.configurate.objectmapping.ObjectMappingException;
import ninja.leaping.configurate.objectmapping.Setting;
import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable;
import ninja.leaping.configurate.objectmapping.serialize.TypeSerializer;
import ninja.leaping.configurate.objectmapping.serialize.TypeSerializers;

import com.afterkraft.kraftrpg.api.RpgCommon;
import com.afterkraft.kraftrpg.api.RpgPlugin;
import com.afterkraft.kraftrpg.api.role.aspect.HealthAspect;
import com.afterkraft.kraftrpg.api.role.aspect.ResourceAspect;
import com.afterkraft.kraftrpg.api.role.aspect.RestrictedSkillAspect;
import com.afterkraft.kraftrpg.api.role.aspect.SkillAspect;
import com.afterkraft.kraftrpg.api.skill.Skill;

/**
 * A Role is an Immutable object representing the skill tree and damage values that a {@link
 * com.afterkraft.kraftrpg.api.entity.Sentient} may have. All {@link Skill}s are granted for use to
 * {@link com.afterkraft.kraftrpg.api.entity.SkillCaster}s and experience is gained by {@link
 * com.afterkraft.kraftrpg.api.entity.Sentient}s. To construct a Role, use the linked {@link
 * Builder}
 */
public final class Role {

    private static final TypeSerializer<Role> TYPE_SERIALIZER;

    public static final Role DEFAULT_PRIMARY = null;
    public static final Role DEFAULT_SECONDARY = null;

    private final RoleAspect[] aspects;
    private final String name;
    private final String[] children;
    private final String[] parents;
    private final RoleType type;
    private final int advancementLevel;
    private final int maxLevel;
    private final boolean choosable;
    private final Text description;

    private Role(Builder builder) {
        this.name = builder.name;
        this.type = builder.type;
        this.choosable = builder.choosable;
        this.description = builder.description;
        this.advancementLevel = builder.advancementLevel;
        this.maxLevel = builder.maxLevel;
        this.children = builder.children
                .toArray(new String[builder.children.size()]);
        this.parents = builder.parents
                .toArray(new String[builder.parents.size()]);
        this.aspects = builder.aspects.toArray(new RoleAspect[builder.aspects
                .size()]);
    }

    /**
     * Construct a Role. It is necessary to provide the link to {@link RpgPlugin} as many of the
     * operations performed in a Role use it.
     *
     * @return This builder
     */
    public static Builder builder() {
        return new Builder();
    }

    /**
     * Gets the maximum level that can be achieved with this Role.
     *
     * @return The maximum level that can be achieved with this role
     */
    @SuppressWarnings("unused")
    public int getMaxLevel() {
        return this.maxLevel;
    }

    /**
     * Get the type of Role this is.
     *
     * @return The {@link RoleType}
     */
    public final RoleType getType() {
        return this.type;
    }

    /**
     * Gets the desired {@link RoleAspect} of this role if available.
     *
     * @param clazz The resource class
     * @param <T>   The type of resource
     *
     * @return The resource aspect, if available
     */
    @SuppressWarnings({"unchecked", "unused"})
    public <T extends RoleAspect> Optional<T> getAspect(Class<T> clazz) {
        checkNotNull(clazz);
        checkArgument(!RoleAspect.class.equals(clazz)
                              && !ResourceAspect.class.equals(clazz));
        for (RoleAspect aspect : this.aspects) {
            if (clazz.isInstance(aspect)) {
                return Optional.of((T) aspect);
            }
        }
        return Optional.empty();
    }

    /**
     * Creates an immutable set of Roles that are defined as this Role's parents
     *
     * @return an immutable set of roles that are this role's parents
     */
    @SuppressWarnings("unused")
    public Set<Role> getParents() {
        ImmutableSet.Builder<Role> builder = ImmutableSet.builder();
        for (String roleName : this.parents) {
            builder.add(RpgCommon.getRoleManager().getRole(roleName).get());
        }
        return builder.build();
    }

    /**
     * Creates an immutable set of Roles that are defined as this Role's children
     *
     * @return an immutable set of roles that are this role's children
     */
    @SuppressWarnings("unused")
    public Set<Role> getChildren() {
        ImmutableSet.Builder<Role> builder = ImmutableSet.builder();
        for (String roleName : this.children) {
            builder.add(RpgCommon.getRoleManager().getRole(roleName).get());
        }
        return builder.build();
    }

    /**
     * Check if this Role is defined as the default Role as configured in RpgCommon.
     *
     * @return true if this role is the default role
     */
    @SuppressWarnings("unused")
    public boolean isDefault() {
        if (this.type == RoleType.PRIMARY) {
            return this == RpgCommon.getRoleManager().getDefaultPrimaryRole();
        } else if (this.type == RoleType.SECONDARY
                && RpgCommon.getRoleManager()
                .getDefaultSecondaryRole().isPresent()) {
            return this == RpgCommon.getRoleManager()
                    .getDefaultSecondaryRole().get();
        }
        return false;
    }

    /**
     * Check if this role can by chosen by players. A non-choosable role must be granted through
     * some means other than role tree advancement.
     *
     * @return can be chosen
     */
    @SuppressWarnings("unused")
    public boolean isChoosable() {
        return this.choosable;
    }

    /**
     * Gets the level at which this Role is considered eligible for advancement.
     *
     * @return the level that this role is eligible for advancement to a child role
     */
    @SuppressWarnings("unused")
    public int getAdvancementLevel() {
        return this.advancementLevel;
    }

    /**
     * Gets the description of this role.
     *
     * @return the description of this role
     */
    @SuppressWarnings("unused")
    public Text getDescription() {
        return this.description;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(this.name,
                                this.description,
                                this.choosable,
                                this.children,
                                this.parents,
                                this.aspects,
                                this.type,
                                this.advancementLevel,
                                this.maxLevel);
    }

    @Override
    public boolean equals(Object obj) {
        checkNotNull(obj);
        if (obj.getClass() != this.getClass()) {
            return false;
        }
        if (this == obj) {
            return true;
        }
        Role role = (Role) obj;

        return Objects.equal(this.name, role.getName())
                && Objects.equal(this.description, role.description)
                && Objects.equal(this.maxLevel, role.maxLevel)
                && Objects.equal(this.type, role.type)
                && Objects.equal(this.choosable, role.choosable)
                && Objects.equal(this.advancementLevel, role.advancementLevel)
                && Objects.equal(this.aspects, role.aspects)
                && Objects.equal(this.children, role.children)
                && Objects.equal(this.parents, role.parents);
    }

    /**
     * Return the configured name for this Role
     *
     * @return The name for this role
     */
    public String getName() {
        return this.name;
    }

    /**
     * Creates a copy of this current role with all settings.
     *
     * @return A copy of this Role
     */
    @SuppressWarnings("unused")
    public Role asNewCopy() {
        return copyOf(this).build();
    }

    /**
     * Creates a builder using a role as a template for further modification.
     *
     * @param role The role to copy
     *
     * @return This builder
     */
    public static Builder copyOf(Role role) {
        checkNotNull(role);
        Builder builder = new Builder()
                .setName(role.name)
                .setAdvancementLevel(role.advancementLevel)
                .setMaxLevel(role.maxLevel)
                .setChoosable(role.choosable)
                .setDescription(role.description)
                .setType(role.type);
        for (String child : role.children) {
            builder.addChild(RpgCommon.getRoleManager().getRole(child).get());
        }
        for (String parent : role.parents) {
            builder.addParent(
                    RpgCommon.getRoleManager().getRole(parent).get());
        }
        for (RoleAspect aspect : role.aspects) {
            builder.addAspect(aspect);
        }
        return builder;
    }

    /**
     * Standard definition of the various types of Roles.
     */
    public static enum RoleType {

        /**
         * A Primary role. Usually defined as a combat Role with skill granting and health and mana
         * benefits. It may contain restrictions on skill usage provided by other Roles. A {@link
         * com.afterkraft.kraftrpg.api.entity.Sentient} may only have one Primary Role active at any
         * given time.
         */
        PRIMARY,
        /**
         * A Secondary role. Usually a professional Role defining non combat skills and minor health
         * and mana benefits. It may contain restrictions on skill usage provided by other Roles. A
         * {@link com.afterkraft.kraftrpg.api.entity.Sentient} may only have one Secondary Role
         * active at any given time.
         */
        SECONDARY,
        /**
         * An Additional role defines only skills to be granted at level 0 or a progressing skill
         * tree. It does not alter health or mana benefits. Nor does it provide any
         * weapon/armor/item allowances. It should be noted that a {@link
         * com.afterkraft.kraftrpg.api.entity.Sentient} may have several active Additional roles at
         * any given time. Additional roles may still provide skill settings.
         */
        ADDITIONAL
    }

    /**
     * This is a builder for Role.
     */
    public static final class Builder {
        String name;
        List<RoleAspect> aspects = Lists.newArrayList();
        RoleType type = RoleType.PRIMARY;
        List<String> children = Lists.newArrayList();
        List<String> parents = Lists.newArrayList();
        int advancementLevel;
        int maxLevel = 1;
        boolean choosable = true;
        Text description;

        Builder() { }

        /**
         * Set the specified RoleType
         *
         * @param type of Role
         *
         * @return this builder for chaining
         */
        public Builder setType(RoleType type) {
            checkNotNull(type);
            this.type = type;
            return this;
        }

        /**
         * Sets the description for the role.
         *
         * @param description The description
         *
         * @return This builder for chaining
         */
        public Builder setDescription(Text description) {
            checkNotNull(description);
            checkArgument(!description.isEmpty(), "The description cannot be empty!");
            this.description = description;
            return this;
        }

        /**
         * Sets the role to be choosable by players in game.
A choosable role means that it can
         * be chosen by players without assistance of admin commands or external plugin
         * behaviors.

         *
         * @param choosable Whether the role is choosable in game
         *
         * @return This builder for chaining
         */
        public Builder setChoosable(boolean choosable) {
            this.choosable = choosable;
            return this;
        }

        /**
         * Sets the maximum level of the role.
         *
         * @param maxLevel The maximum level of the role
         *
         * @return This builder for chaining
         */
        public Builder setMaxLevel(int maxLevel) {
            checkArgument(maxLevel > 0 && maxLevel >= this.advancementLevel,
                          "Cannot have a max level lower than the advancement level or less than zero!");
            this.maxLevel = maxLevel;
            return this;
        }

        /**
         * Sets the level of which the role qualifies for advancement to a child role.
         *
         * @param advancementLevel The advancement level
         *
         * @return This builder for chaining
         */
        public Builder setAdvancementLevel(int advancementLevel) {
            checkArgument(advancementLevel >= 0,
                          "Cannot have a less than zero advancement level!");
            this.advancementLevel = advancementLevel;
            return this;
        }

        /**
         * Sets the name of the role.
         *
         * @param name The name of the role
         *
         * @return This builder for chaining
         */
        public Builder setName(String name) {
            checkNotNull(name);
            checkArgument(!name.isEmpty(), "Cannot have an empty Role name!");
            this.name = name;
            return this;
        }

        /**
         * Adds the given aspect to the role.
Aspects further customize Roles to perform various
         * tasks and calculations, such as skill granting, skill restriction, item damage, and
         * health benefits.

{@link RoleAspect} is considered immutble, so once created, they
         * can not be modified.

         *
         * @param aspect The role aspect
         *
         * @return This builder for chaining
         */
        public Builder addAspect(RoleAspect aspect) {
            checkNotNull(aspect);
            if (aspect instanceof HealthAspect) {
                checkArgument(((HealthAspect) aspect).getBaseHealth() > 0);
            }
            if (aspect instanceof RestrictedSkillAspect) {
                for (RoleAspect roleAspect : this.aspects) {
                    if (roleAspect instanceof SkillAspect) {
                        SkillAspect skillAspect = (SkillAspect) roleAspect;
                        for (Skill skill : skillAspect.getAllSkills()) {
                            checkArgument(!((RestrictedSkillAspect) aspect)
                                    .isSkillRestricted(skill));
                        }
                    }
                }
            }
            this.aspects.add(aspect);
            return this;
        }

        /**
         * Add a Role as a child to this role. This will not affect the child role being parented.
         *
         * @param child The child being added to this role
         *
         * @return This builder for chaining
         * @throws IllegalArgumentException if the child was already added as a parent
         */
        public Builder addChild(Role child) {
            checkNotNull(child);
            checkArgument(!this.parents.contains(child.getName()),
                          "Cannot add a child role when it is already a parent role!");
            this.children.add(child.getName());
            return this;
        }

        /**
         * Add a Role as a child to this role. This will not affect the parent being dependend on.
         *
         * @param parent The parent being added to this role
         *
         * @return This builder for chaining
         * @throws IllegalArgumentException if the parent was already added as a child
         */
        public Builder addParent(Role parent) {
            checkNotNull(parent);
            checkArgument(!this.children.contains(parent.getName()),
                          "Cannot add a parent role when it is already a child role!");
            this.parents.add(parent.getName());
            return this;
        }

        /**
         * Removes the child from the dependency list. This will not affect the child Role.
         *
         * @param child The child to remove from the dependency list
         *
         * @return This builder for chaining
         */
        public Builder removeChild(Role child) {
            checkNotNull(child);
            checkArgument(!this.parents.contains(child.getName()),
                          "Cannot remove a child role when it is already a parent role!");
            this.children.remove(child.getName());
            return this;
        }

        /**
         * Removes the parent from the dependency list. This will not affect the parent Role.
         *
         * @param parent The parent to remove from the dependency list
         *
         * @return This builder for chaining
         * @throws IllegalArgumentException If the parent is also a child
         */
        public Builder removeParent(Role parent) {
            checkNotNull(parent);
            checkArgument(!this.children.contains(parent.getName()),
                          "Cannot remove a parent role when it is already a child role!");
            this.parents.remove(parent.getName());
            return this;
        }

        /**
         * Gets a Role from the present state of the Builder. There are requirements to generating a
         * Role that otherwise, the Builder is in an incomplete state. The requirements are:

         *
A name

A description

A max level

Minimum health at level
         * 0

Health gains per level is not 0

Mana per level is not 0

         *
         * @return A newly constructed Role that can not be changed.
         * @throws IllegalStateException If maximum level has not been set
         * @throws IllegalStateException If the health at level zero has not been set
         * @throws IllegalStateException If the health per level gained is less than zero
         * @throws IllegalStateException If the mana gained per level at max level is less than
         *                               zero
         */
        public Role build() {
            checkState(this.advancementLevel > 0,
                       "Cannot have a zero advancement level!");
            checkState(this.maxLevel > 0, "Cannot have a zero max level!");
            checkState(!this.name.isEmpty());
            return new Role(this);
        }

    }

    static {
        TYPE_SERIALIZER = new TypeSerializer<Role>() {
            @Override
            public Role deserialize(TypeToken<?> type, ConfigurationNode value) throws
                    ObjectMappingException {
                return null; // TODO
            }

            @Override
            public void serialize(TypeToken<?> type, Role obj, ConfigurationNode value) throws
                    ObjectMappingException {
                // TODO

            }
        };
        TypeSerializers.getDefaultSerializers()
                .registerType(TypeToken.of(Role.class), TYPE_SERIALIZER);
    }

}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>current_story_runner= (Spec::Story::Runner::StoryRunner)</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <link rel="stylesheet" href="../../../../.././rdoc-style.css" type="text/css" media="screen" />

# File lib/spec/story/runner/story_runner.rb, line 9
        def self.current_story_runner=(current_story_runner)
          @current_story_runner = current_story_runner
        end

redpajama_set_name: RedPajamaGithub


text:
var assert = require('assert'),
	TaskManager = require(__dirname+'/../');

var testOKResult = [
	[ 'hello world!' ],
	[ 'users subscribed', [ 1, 2 ] ],
	[ 'completed', 'task' ],
	[ 'users subscribed', [ 1, 2 ] ],
	[ 'global completed', 'Task Example' ]
];

var testOKResultGlobals = [
	['completed', 'self'],
	['global completed', '1'],
	['global completed', '2']
];

describe("Generic main tests", function() {

	this.timeout(800);

	it('Start Events Test', function(done){
		assert.doesNotThrow(function(){

			var outputOk = ['beforeStart', 'start', 'afterStart'];

			var output = [];

			TaskManager(0).flush();

			TaskManager(0).on('done',function(){
				assert.deepEqual(output, outputOk);
				done();
			});

			TaskManager().addTask(function(){
				this.step(this.done);
			}).on('beforeStart', function(){
				output.push('beforeStart');
			}).on('start', function(){
				output.push('start');
			}).on('afterStart', function(){
				output.push('afterStart');
			}).start();

		})
	});

	it("Steps with events", function(done){
		assert.doesNotThrow(function() {

			var output = [];

			TaskManager(0).flush();

			TaskManager(0).on('done', function(){
				output.push(8);
				assert.deepEqual([1,2,3,4,5,6,7,8], output);
				done();
			});

			TaskManager(3).addTask(function(){
				this.step(function(){
					output.push(1);
				});
				this.step(function(){
					output.push(2);
				});
				this.step(function(){
					output.push(3);
				});
				this.step(function(){
					this.trigger('test');
				});
				this.step(function(){
					output.push(5);
				});
				this.step(function(){
					output.push(6);
				});

				this.done();

			}).on('test', function(){

				output.push(4);

			}).on('done', function(){

				output.push(7);

			}).start();

		});
	});

	it("Global events", function(done){

		assert.doesNotThrow(function() {

			setTimeout(function(){

				TaskManager(0).flush();

				// Register first global done event
				TaskManager().on('done', function(){

					this.__settings.a++; // Increment option a

				});

				// Create task and start it immediately
				TaskManager(1).addTask(function(){

					this.done(); // Call done event

				}).settings({

					a: 1 // Set variables as object or function with sync calculations

				}).on('done', function(){

					this.__settings.a++; // Executed before all global events with name `done`

				}).start();

				// Register second global done event after start task
				TaskManager().on('done', function(){

					assert.strictEqual(3, this.get('a'));

					done();

				});

			}, 0);

		});

	});

	it("Set Settings as Object", function(done){

		assert.doesNotThrow(function() {

			setTimeout(function(){

				TaskManager(0).flush();

				TaskManager(2).addTask(function(){

					this.__settings['a']++;

					this.done();

				}).settings({a: 2}).on('done', function(){

					assert.strictEqual(3, this.get('a'));

					done();

				}).start();

			}, 0);

		});

	});

	it("Collection output correct values and sorting", function(done) {

		assert.doesNotThrow(function() {

			setTimeout(function(){

				TaskManager(0).flush();

				var userId = 1; // user id, will be subscribed at the start

				var output = [];

				TaskManager().on('done', function(){

					output.push(['global completed', this.get('name')]);

				});

				// Get TaskManager Environment By UserID
				// And create task with some calculations
				TaskManager(userId).addTask(function(){

					var self = this; // save link to Task instance

					this.step(function(){
						this.trigger('test', {hello: 'hello world!'}); // trigger test event
					});

					this.step(function() {

						// emulate long process work
						setTimeout(function () {

							self.done(); // call task done

						}, 40);

					});

					this.step(function(){

						this.subscribe(2); // subscribe new user id before done

					});

				}).settings({
					some: 'task',
					name: 'Task Example'
				}).on('done', function(){

					output.push(['completed', this.get('some')]); // completed task

					output.push(['users subscribed', this.getSubscribers()]); // get subscribers at end

					//this.stop(); @todo Release Stop method

				}).on('test',function(context){

					output.push([context.hello]); // hello world!

					output.push(['users subscribed', this.getSubscribers()]); // get subscribers at any event

				}).start(); // Run task

				TaskManager().on('done', function(){

					assert.deepEqual(testOKResult, output);

					done();

				});

			}, 0);

		});

	});

	it("Additions Global Events", function(done){

		assert.doesNotThrow(function() {

			setTimeout(function(){

				TaskManager(0).flush();

				var userId = 1;
				var output = [];

				TaskManager(0).on('done', function(){
					output.push(['global completed', '1']);
				});

				TaskManager(userId).addTask(function(){
					var self = this;

					this.step(function(){
						self.done();
					});

				}).on('done', function(){

					output.push(['completed', 'self']);

				}).start();

				TaskManager(0).on('done', function(){
					output.push(['global completed', '2']);
				});

				TaskManager(0).on('done', function(){

					assert.deepEqual(testOKResultGlobals, output);

					done();

				});

			}, 0);

		});

	});

});


text:
(function() {

    "use strict";

    /**
     * think.view.ListItem
     */
    think.view.ListItem = xin.ui.Outlet.extend({
        events: {
            'click a[href="#remove"]': 'remove',
            'click a[href="#full"]': 'full',
            'click a[href="#moveto"]': 'moveTo',
            'click a[href="#movehere"]': 'moveHere',
            'click a[href="#due"]': 'due',
            'click a[href="#subtask"]': 'subtask',
            'click': 'select'
        },

        initialize: function() {
            xin.ui.Outlet.prototype.initialize.apply(this, arguments);
            var that = this;
            Backbone.Events.on('mode-move', function(v) {
                if (that != v) {
                    that.$el.addClass('mode-move');
                    that.moveObject = v;
                }
            });

            Backbone.Events.on('mode-default', function(v) {
                if (that != v) {
                    that.$el.removeClass('mode-move');
                }
            });
        },

        select: function(evt) {
            evt.preventDefault();

            var $el = this.$el,
                $children = this.$el.parent().children().filter('.active');

            $children.removeClass('selected');

            if (this.$el.hasClass('active')) {
                this.$el.toggleClass('active');
            } else {
                $el.addClass('selected');

                if ($children.length) {
                    // $children.on('webkitTransitionEnd', function() {
                    //     $children.off('webkitTransitionEnd');
                        $el.addClass('active');
                    // });
                    $children.removeClass('active');
                } else {
                    $el.addClass('active');
                }
            }

            Backbone.Events.trigger('mode-default', this);

        },

        full: function(evt) {
            evt.preventDefault();
            evt.stopImmediatePropagation();

            comingSoon();
        },

        due: function(evt) {
            evt.preventDefault();
            evt.stopImmediatePropagation();

            comingSoon();
        },

        moveTo: function(evt) {
            var that = this;
            evt.preventDefault();
            evt.stopImmediatePropagation();

            Backbone.Events.trigger('mode-move', this);
        },

        moveHere: function(evt) {
            evt.preventDefault();
            evt.stopImmediatePropagation();

            this.moveObject.model.moveTo(this.model);
            this.subtask(evt);
        },

        subtask: function(evt) {
            evt.preventDefault();
            evt.stopImmediatePropagation();

            this.model.collection.setParent(this.model.id);
        },

        remove: function(evt) {
            evt.preventDefault();
            evt.stopImmediatePropagation();

            var that = this;

            customConfirm('Are you sure?', function(value) {
                if (value) {
                    that.model.collection.remove(that.model.cid);
                    that.model.destroy();
                }
            });

            return false;
        }
    });

})();


text:
require File.expand_path('../../../../spec_helper', __FILE__)
require 'rexml/document'

describe "REXML::Attribute#namespace" do
  it "returns the namespace url" do
    e = REXML::Element.new("root")
    e.add_attribute REXML::Attribute.new("xmlns:ns", "http://some_uri")
    e.namespace("ns").should == "http://some_uri"
  end

  it "returns nil if namespace is not defined" do
    e = REXML::Element.new("root")
    e.add_attribute REXML::Attribute.new("test", "value")
    e.namespace("test").should == nil
    e.namespace("ns").should == nil
  end

  it "defaults arg to nil" do
    e = REXML::Element.new("root")
    e.add_attribute REXML::Attribute.new("xmlns:ns", "http://some_uri")
    e.namespace.should == ""
    e.namespace("ns").should == "http://some_uri"
  end
end


text:
<?php

namespace Core\CoreBundle\Form\Type;

use Doctrine\ORM\EntityNotFoundException;
use Symfony\Bridge\Doctrine\RegistryInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class GenericEntityType extends AbstractType
{
    /**
     * @var RegistryInterface
     */
    private $doctrine;

    /**
     * @var OptionsResolverInterface
     */
    private $resolver;

    public function __construct(RegistryInterface $doctrine)
    {
        $this->doctrine = $doctrine;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $this->resolver = $resolver;
        $resolver->setDefaults(array(
                                   'fixed_values' => array()
                               ));
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // Check entity
        $ORMmanager = $this->doctrine->getManager();
        try {
            $entityMetadata = $ORMmanager->getClassMetadata($options['data_class']);
        }
        catch (\Exception $e) {
            throw EntityNotFoundException::fromClassNameAndIdentifier($options['data_class'], array());
        }

        // Add defaults data_class
        $this->resolver->setDefaults(
            array(
                'data_class' => $options['data_class'],
            ));

        // Add fields
        foreach ($entityMetadata->getFieldNames() as $fieldName) {
            if ($entityMetadata->isIdentifier($fieldName) && $entityMetadata->isIdGeneratorIdentity()) {
                continue;
            }
            if (array_key_exists($fieldName,
                                 $options['fixed_values']) && !is_null($options['fixed_values'][$fieldName])
            ) {
                $builder->add($fieldName,
                              'text',
                              array(
                                  'data' => $options['fixed_values'][$fieldName],
                                  'read_only' => true,
                              ));
                continue;
            }
            if ($entityMetadata->getTypeOfField($fieldName) == 'url') {
                $builder->add($fieldName, 'url');
                continue;
            }
            $builder->add($fieldName);
        }

        // Add associations fields
        foreach ($entityMetadata->getAssociationNames() as $associationName) {
            $targetClass = $entityMetadata->getAssociationTargetClass($associationName);
            if (array_key_exists($associationName,
                                 $options['fixed_values']) && !is_null($options['fixed_values'][$associationName])
            ) {
                $builder->add($associationName,
                              'entity',
                              array(
                                  'data' => $options['fixed_values'][$associationName],
                                  'disabled' => true,
                                  'class' => $targetClass,
                              ));
                continue;
            }
            if ($entityMetadata->isCollectionValuedAssociation($associationName)) {
                $builder->add($associationName);
                continue;
            }
            elseif ($entityMetadata->isSingleValuedAssociation($associationName)) {
                $builder->add($associationName);
                continue;
            }
            $builder->add($associationName,
                          'collection',
                          array(
                              'type' => new self($this->doctrine),
                              'allow_add' => true,
                              'allow_delete' => true,
                              'options' => array('data_class' => $targetClass),
                              'by_reference' => false,
                          ));
        }

        if (!empty($options['fixed_values'])) {
            $builder->addEventListener(
                FormEvents::POST_SUBMIT,
                function (FormEvent $event) use ($options) {
                    $data = $event->getData();
                    foreach ($options['fixed_values'] as $name => $value) {
                        call_user_func(array($data, 'set' . $name), $value);
                    }
                    $event->setData($data);
                }
            );
        }
    }

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

}


text:
hutts\_verification\.image\_preprocessing package
=================================================

Submodules
----------

hutts\_verification\.image\_preprocessing\.blur\_manager module
---------------------------------------------------------------

.. automodule:: hutts_verification.image_preprocessing.blur_manager
    :members:
    :undoc-members:
    :show-inheritance:

hutts\_verification\.image\_preprocessing\.build\_director module
-----------------------------------------------------------------

.. automodule:: hutts_verification.image_preprocessing.build_director
    :members:
    :undoc-members:
    :show-inheritance:

hutts\_verification\.image\_preprocessing\.color\_manager module
----------------------------------------------------------------

.. automodule:: hutts_verification.image_preprocessing.color_manager
    :members:
    :undoc-members:
    :show-inheritance:

hutts\_verification\.image\_preprocessing\.face\_manager module
---------------------------------------------------------------

.. automodule:: hutts_verification.image_preprocessing.face_manager
    :members:
    :undoc-members:
    :show-inheritance:

hutts\_verification\.image\_preprocessing\.pipeline module
----------------------------------------------------------

.. automodule:: hutts_verification.image_preprocessing.pipeline
    :members:
    :undoc-members:
    :show-inheritance:

hutts\_verification\.image\_preprocessing\.pipeline\_builder module
-------------------------------------------------------------------

.. automodule:: hutts_verification.image_preprocessing.pipeline_builder
    :members:
    :undoc-members:
    :show-inheritance:

hutts\_verification\.image\_preprocessing\.template\_matching module
--------------------------------------------------------------------

.. automodule:: hutts_verification.image_preprocessing.template_matching
    :members:
    :undoc-members:
    :show-inheritance:

hutts\_verification\.image\_preprocessing\.thresholding\_manager module
-----------------------------------------------------------------------

.. automodule:: hutts_verification.image_preprocessing.thresholding_manager
    :members:
    :undoc-members:
    :show-inheritance:

Module contents
---------------

.. automodule:: hutts_verification.image_preprocessing
    :members:
    :undoc-members:
    :show-inheritance:


text:
require "rails"

module TitanControl
  class Engine < Rails::Engine
    isolate_namespace TitanControl
  end
end


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=constant.CL_EXEC_KERNEL.html">

Redirecting to constant.CL_EXEC_KERNEL.html...


text:
using DevExpress.Diagram.Core;
using DevExpress.XtraDiagram;

namespace CIIP.Module.Win.Editors
{
    public class DiagramControllerEx : DiagramController
    {
        public DiagramControllerEx(DiagramControl diagram)
            : base(diagram)
        {

        }
        protected override void OnItemAdded(IDiagramItem item)
        {

            base.OnItemAdded(item);

        }

        protected override void OnItemRemoved(IDiagramItem item)
        {
            base.OnItemRemoved(item);
        }

    }
}


text:
const process = require('process')
const execpe = require('./build/Release/execpe.node').execpe

function realExecpe (path, args, env) {
  var realenv = []
  args = args || []
  env = env || process.env
  Object.keys(env)
    .forEach(function (key) {
      realenv.push(key + '=' + env[key])
    })
  return execpe(path, args, realenv)
}

module.exports = realExecpe


text:
namespace Bands.Validation
{
    /// <summary>
    /// Defines an object capable of validating another object of type <typeparamref name="TValidatable"/>.
    /// </summary>
    /// <typeparam name="TValidatable">Type of validatable object</typeparam>
    public interface IValidator<TValidatable> where TValidatable : IValidatable
    {
        /// <summary>
        /// Validates object <paramref name="validatable"/>.
        /// </summary>
        /// <param name="validatable">A validatable object of type <typeparamref name="TValidatable"/>.</param>
        /// <returns>True if <param name="validatable" /> is valid.</returns>
        bool Validate(TValidatable validatable);
    }
}


text:
using jgshort.SqlDom.Expressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using jgshort.SqlDom.Expressions.Predicates;

namespace jgshort.SqlDom.Tests
{

    ///
    ///This is a test class for Expression and is intended to contain all Expression Unit Tests
    ///
    [TestClass()]
    public class ExpressionTest
    {
        private TestContext testContextInstance;

        ///
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///
        public TestContext TestContext
        {
            get { return testContextInstance; }
            set { testContextInstance = value; }
        }

        ///
        ///A test for And
        ///
        [TestMethod()]
        public void AndTest()
        {
            Comparison(PredicateOperators.And);
        }
        ///
        ///A test for Equal
        ///
        [TestMethod()]
        public void EqualTest()
        {
            Comparison(PredicateOperators.Equals);
        }

        ///
        ///A test for GreaterThan
        ///
        [TestMethod()]
        public void GreaterThanTest()
        {
            Comparison(PredicateOperators.GreaterThan);
        }

        ///
        ///A test for GreaterThanOrEqual
        ///
        [TestMethod()]
        public void GreaterThanOrEqualTest()
        {
            Comparison(PredicateOperators.GreaterThanOrEquals);
        }

        ///
        ///A test for IsNull
        ///
        [TestMethod()]
        public void IsNullTest()
        {
            // TODO: Verify IsNull expression.
            var expression = new ConstantTypes.Integer(0);
            var expected = new Null(expression);
            var actual = expression.IsNull();
            Assert.AreEqual(expected.Left, actual.Left);
            Assert.AreEqual(((Null)actual).Not, ((Null)expected).Not);
        }
        ///
        ///A test for LessThan
        ///
        [TestMethod()]
        public void LessThanTest()
        {
            Comparison(PredicateOperators.LessThan);
        }

        ///
        ///A test for LessThanOrEqual
        ///
        [TestMethod()]
        public void LessThanOrEqualTest()
        {
            Comparison(PredicateOperators.LessThanOrEquals);
        }

        ///
        ///A test for Like
        ///
        [TestMethod()]
        public void LikeTest()
        {
            Comparison(PredicateOperators.Like);
        }

        ///
        ///A test for NotEqual
        ///
        [TestMethod()]
        public void NotEqualTest()
        {
            Comparison(PredicateOperators.NotEquals);
        }

        ///
        ///A test for NotGreaterThan
        ///
        [TestMethod()]
        public void NotGreaterThanTest()
        {
            Comparison(PredicateOperators.NotGreaterThan);
        }

        ///
        ///A test for NotLessThan
        ///
        [TestMethod()]
        public void NotLessThanTest()
        {
            Comparison(PredicateOperators.NotLessThan);
        }
        ///
        ///A test for Or
        ///
        [TestMethod()]
        public void OrTest()
        {
            Comparison(PredicateOperators.Or);
        }
        private static void Comparison(PredicateOperators op)
        {
            Expression target = new ConstantTypes.Integer(0);
            Expression right = new ConstantTypes.Integer(0);
            Predicate actual = null;
            switch (op)
            {
                case PredicateOperators.And:
                    actual = target.And(right);
                    break;
                case PredicateOperators.Equals:
                    actual = target.Equal(right);
                    break;
                case PredicateOperators.GreaterThan:
                    actual = target.GreaterThan(right);
                    break;
                case PredicateOperators.GreaterThanOrEquals:
                    actual = target.GreaterThanOrEqual(right);
                    break;
                case PredicateOperators.In:
                    actual = target.In(right);
                    break;
                case PredicateOperators.LessThan:
                    actual = target.LessThan(right);
                    break;
                case PredicateOperators.LessThanOrEquals:
                    actual = target.LessThanOrEqual(right);
                    break;
                case PredicateOperators.Like:
                    actual = target.Like(right);
                    break;
                case PredicateOperators.NotEquals:
                    actual = target.NotEqual(right);
                    break;
                case PredicateOperators.NotGreaterThan:
                    actual = target.NotGreaterThan(right);
                    break;
                case PredicateOperators.NotLessThan:
                    actual = target.NotLessThan(right);
                    break;
                case PredicateOperators.Or:
                    actual = target.Or(right);
                    break;
            }
            Assert.IsNotNull(actual);
            Predicate expected = new Comparison(target, op, right);
            Assert.AreEqual(expected.Left, actual.Left);
            Assert.AreEqual(((Comparison)expected).Right, ((Comparison)actual).Right);
            Assert.AreEqual(((Comparison)expected).Operator, ((Comparison)actual).Operator);
        }

        // TODO: If we ever flesh out lambda expressions in the expression class, re-enable and complete these checks:
#if LAMBDA_ENABLED
        ///
        ///A test for Lambda
        ///
        public void LambdaTestHelper<T>()
        {
            System.Linq.Expressions.Expression<Func<T>> lambda = null; // TODO: Initialize to an appropriate value
            Expression expected = null; // TODO: Initialize to an appropriate value
            Expression actual;
            actual = Expression.Lambda<T>(lambda);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }

        [TestMethod()]
        public void LambdaTest()
        {
            LambdaTestHelper<GenericParameterHelper>();
        }

        ///
        ///A test for Lambda
        ///
        public void LambdaTest1Helper<T>()
        {
            System.Linq.Expressions.Expression<Func<T, T, T, T>> lambda = null; // TODO: Initialize to an appropriate value
            Expression expected = null; // TODO: Initialize to an appropriate value
            Expression actual;
            actual = Expression.Lambda<T>(lambda);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }

        [TestMethod()]
        public void LambdaTest1()
        {
            LambdaTest1Helper<GenericParameterHelper>();
        }

        ///
        ///A test for Lambda
        ///
        public void LambdaTest2Helper<T>()
        {
            System.Linq.Expressions.Expression<Func<T, T>> lambda = null; // TODO: Initialize to an appropriate value
            Expression expected = null; // TODO: Initialize to an appropriate value
            Expression actual;
            actual = Expression.Lambda<T>(lambda);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }

        [TestMethod()]
        public void LambdaTest2()
        {
            LambdaTest2Helper<GenericParameterHelper>();
        }

        ///
        ///A test for Lambda
        ///
        public void LambdaTest3Helper<T>()
        {
            System.Linq.Expressions.Expression<Func<T, T, T, T, T>> lambda = null; // TODO: Initialize to an appropriate value
            Expression expected = null; // TODO: Initialize to an appropriate value
            Expression actual;
            actual = Expression.Lambda<T>(lambda);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }

        [TestMethod()]
        public void LambdaTest3()
        {
            LambdaTest3Helper<GenericParameterHelper>();
        }

        ///
        ///A test for Lambda
        ///
        public void LambdaTest4Helper<T>()
        {
            System.Linq.Expressions.Expression<Func<T, T, T>> lambda = null; // TODO: Initialize to an appropriate value
            Expression expected = null; // TODO: Initialize to an appropriate value
            Expression actual;
            actual = Expression.Lambda<T>(lambda);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }

        [TestMethod()]
        public void LambdaTest4()
        {
            LambdaTest4Helper<GenericParameterHelper>();
        }

        ///
        ///A test for Lambda
        ///
        public void LambdaTest5Helper<T>()
        {
            Func<T> f = null; // TODO: Initialize to an appropriate value
            Expression expected = null; // TODO: Initialize to an appropriate value
            Expression actual;
            actual = Expression.Lambda<T>(f);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }

        [TestMethod()]
        public void LambdaTest5()
        {
            LambdaTest5Helper<GenericParameterHelper>();
        }

        ///
        ///A test for LambdaToExpression
        ///
        [TestMethod()]
        [DeploymentItem("jgshort.SqlDom.dll")]
        public void LambdaToExpressionTest()
        {
            object lambda = null; // TODO: Initialize to an appropriate value
            Expression expected = null; // TODO: Initialize to an appropriate value
            Expression actual;
            actual = Expression_Accessor.LambdaToExpression(lambda);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }

        ///
        ///A test for op_Implicit
        ///
        [TestMethod()]
        public void op_ImplicitTest()
        {
            string s = string.Empty; // TODO: Initialize to an appropriate value
            Expression expected = null; // TODO: Initialize to an appropriate value
            Expression actual;
            actual = s;
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
#endif

    }
}


text:
/*
this file shows how to configure a static setup
it must be linked from the head of a page like:
<link rel="stylesheet" type="text/css" href="chili/recipes.css"/>
*/

.html .php    { color: red; font-weight: bold; }
.html .tag    { color: navy; font-weight: bold; }
.html .aname  { color: purple; }
.html .avalue { color: fuchsia; }
.html .mlcom  { color: green; }
.html .entity { color: teal; }

.javascript .mlcom    { color: #4040c2; }
.javascript .com      { color: green; }
.javascript .regexp   { color: maroon; }
.javascript .string   { color: teal; }
.javascript .keywords { color: navy; font-weight: bold; }
.javascript .global   { color: blue; }
.javascript .numbers  { color: red; }

.mysql .function  { color: #e17100; }
.mysql .keyword   { color: navy; font-weight: bold; }
.mysql .mlcom     { color: gray; }
.mysql .com       { color: green; }
.mysql .number    { color: red; }
.mysql .hexnum    { color: red; font-weight: bold; }
.mysql .string    { color: purple; }
.mysql .quid      { color: fuchsia; }
.mysql .id        { color: maroon; }
.mysql .value     { color: gray; font-weight: bold; }
.mysql .variable  { color: #4040c2; }

.php .com       { color: green; }
.php .const1    { color: red; }
.php .const2    { color: red; }
.php .func      { color: #e17100; }
.php .global    { color: red; }
.php .keyword   { color: navy; font-weight: bold; }
.php .mlcom     { color: gray; }
.php .name      { color: maroon; }
.php .number    { color: red; }
.php .string1   { color: purple; }
.php .string2   { color: fuchsia; }
.php .value     { color: gray; font-weight: bold; }
.php .variable  { color: #4040c2; }

.css .mlcom  { color: #4040c2; }
.css .color  { color: green; }
.css .string { color: teal; }
.css .attrib { color: navy; font-weight: bold; }
.css .value  { color: blue; }
.css .number { color: red; }

/*
===============================================================================
Chili is the jQuery code highlighter plugin
...............................................................................
                                               Copyright 2007 / Andrea Ercolino
-------------------------------------------------------------------------------
LICENSE: http://www.opensource.org/licenses/mit-license.php
WEBSITE: http://noteslog.com/chili/
===============================================================================
*/

.javascript .mlcom    { color: #4040c2; }
.javascript .com      { color: green; }
.javascript .regexp   { color: maroon; }
.javascript .string   { color: teal; }
.javascript .keywords { color: navy; font-weight: bold; }
.javascript .global   { color: blue; }
.javascript .numbers  { color: red; }

.javascript .jquery .object       { color: red; font-weight: bold; }
.javascript .jquery .private      { background-color: #CCCC99; }
.javascript .jquery .attributes   { background-color: #CCCC00; }
.javascript .jquery .traversing   { background-color: #CCCC00; }
.javascript .jquery .manipulation { background-color: #CCCC00; }
.javascript .jquery .utilities    { background-color: #CCCCFF; }
.javascript .jquery .core         { background-color: #7F7FFF; color: white; }
.javascript .jquery .ajax         { background-color: #7F7FFF; color: #FFD400; }
.javascript .jquery .css          { background-color: #999900; color: white; }
.javascript .jquery .effects      { background-color: #FFAA00; }
.javascript .jquery .events       { background-color: #FFD400; }


text:
=begin

= V3::EntityDAO

  - Goggles framework vers.:  4.00.819
  - author: Steve A.

 DAO class for a generic entity resulting from the parsing of a data-import text
 token.

=end
class V3::EntityDAO

  attr_reader   :id,                                # unique integer ID for this entity
                :name,                              # Symbol representing the entity field key, as defined in the parser defs.
                :parent_context                     # Parent ContextDAO (when defined) or nil

  attr_accessor :text_token,                        # text buffer used for the parsing, initially empty (i.e.: "SL", stroke_types.code)
                :parsed_value,                      # result value from the actual parsing (i.e.: 1, stroke_types.id - filled only during later phases of the data-import procedure)
                :destination_class                  # destination Class for the result value (i.e.: StrokeType - filled only during later phases of the data-import procedure)
  #-- -------------------------------------------------------------------------
  #++

  # Builds a new instance, specifying the unique ID and the field name for which
  # this entitiy will hold the parsed value.
  #
  # - id should be allocated by an external factory, keeping track of all
  #   the instantiated contexts.
  #
  # - name should correspond to the key used to parse the context group from
  #   the parsed text token (which typically may comprise several rows of text).
  #
  # - parent_context can either be +nil+ or an instance of ContextDAO.
  #
  def initialize( id, name, parent_context = nil )
    @id = id
    @name = name
    @text_token = ''
    @parsed_value = nil
    @parent_context = parent_context
    @destination_class = nil
  end
  #-- -------------------------------------------------------------------------
  #++

  # Checks if two instances are the same
  #
  def ==( other_object )
    return false unless other_object.respond_to?(:id) && other_object.respond_to?(:name) &&
                        other_object.respond_to?(:parent_context) &&
                        other_object.respond_to?(:text_token) && other_object.respond_to?(:parsed_value) &&
                        other_object.respond_to?(:destination_class)
    (
      ( self.id == other_object.id ) &&
      ( self.name == other_object.name ) &&
      ( self.parent_context == other_object.parent_context ) &&
      ( self.text_token == other_object.text_token ) &&
      ( self.parsed_value == other_object.parsed_value ) &&
      ( self.destination_class == other_object.destination_class )
    )
  end

  # Convert the current instance to a readable string
  def to_s
    "[V3::EntityDAO: ID: #{@id}, #{@name}, value: #{@parsed_value}" +
    ( @parent_context ? ", parent: '#{@parent_context.name}'" : '' ) +
    ", text_token: #{@text_token}]"
  end
  #-- -------------------------------------------------------------------------
  #++
end


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingBottom="8dp"
    android:paddingTop="8dp"
    android:paddingLeft="2dp"
    android:paddingRight="2dp"
    android:background="@drawable/item_selector"
    >

    <TextView
        android:id="@+id/title_Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#666666"
        android:gravity="center"
        android:textSize="16sp"
        />

</RelativeLayout>


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

var ip = require('../../../index.js').connect.middleware.ip;

describe('ip middleware', function() {

	it('takes the ip from the tcp connection and stick it in request.ip', function (done) {
		var mockRequest = {
			connection: {
				remoteAddress: '192.168.3.1'
			}
		};

		var middleware = ip();

		middleware(mockRequest, null, done);

		assert.strictEqual(mockRequest.ip, '192.168.3.1');
	});

	describe('takes the ip from xfowardedfor header if instructed', function () {

		it('uses xfowardedfor header if it exists and takes the last ip', function (done) {
			var mockRequest = {
				headers: {
					'x-forwarded-for': '192.168.5.1, 1.2.3.4'
				}
			}

			var middleware = ip({ useXforwardedFor: true });

			middleware(mockRequest, null, done);

			assert.strictEqual(mockRequest.ip, '1.2.3.4');
		});

		it('takes the ip from the tcp connection if xff header is missing', function (done) {
			var mockRequest = {
				connection: {
					remoteAddress: '192.168.3.1'
				},
				headers: {}
			};

			var middleware = ip();

			middleware(mockRequest, null, done);

			assert.strictEqual(mockRequest.ip, '192.168.3.1');
		});

		it('takes the ip from the tcp connection if xff header is malformed', function (done) {
			var mockRequest = {
				connection: {
					remoteAddress: '192.168.3.1'
				},
				headers: {
					'x-forwarded-for': '192.168.5.1, '
				}
			};

			var middleware = ip();

			middleware(mockRequest, null, done);

			assert.strictEqual(mockRequest.ip, '192.168.3.1');
		});

		it('handles headers with one non malformed ip in them', function (done) {
			var mockRequest = {
				connection: {
					remoteAddress: '192.168.3.1'
				},
				headers: {
					'x-forwarded-for': '192.168.5.1, '
				}
			};

			var middleware = ip();

			middleware(mockRequest, null, done);

			assert.strictEqual(mockRequest.ip, '192.168.3.1');
		});

	});

});


text:
<?php

namespace Daana\UserBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class DaanaUserBundle extends Bundle
{
}


text:
post '/favourites/:product_id/new' do
  new_favourite = current_user.favourites.new(product_id: params[:product_id])
  new_favourite.save
  redirect to '/'
end

delete '/favourites/:product_id' do
  Favourite.find_by_product_id(params[:product_id]).destroy
  redirect to '/'
end

get '/users/:user_id/favorites' do
  @products = Product.where(id: current_user.favourites.pluck(:product_id))
  erb :"users/favourites"
end

get '/users/products/favourited' do
  @products = Product.where(id: Favourite.where.not(user_id: current_user.id).pluck(:product_id), user_id: current_user.id)
  erb :"users/favourited"
end


text:
<?php

namespace Dannehl\Shipcloud\Api\Response;

/**
 * Class Package
 *
 * @package Dannehl\Shipcloud\Api
 */
class Packages {

    /** @var   */
    private $_id;

    /** @var number $_width */
    private $_width;

    /** @var number $_height */
    private $_height;

    /** @var number $_length */
    private $_length;

    /** @var number $_weight */
    private $_weight;

    /** @var DeclaredValue $_declared_value */
    private $_declared_value;

    /** @var string $_package_type */
    private $_package_type;

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

    /**
     * @param mixed $id
     * @return $this
     */
    public function setId($id)
    {
        $this->_id = $id;
        return $this;
    }

    /**
     * @return number
     */
    public function getWidth()
    {
        return $this->_width;
    }

    /**
     * @param number $width
     * @return $this
     */
    public function setWidth($width)
    {
        $this->_width = $width;
        return $this;
    }

    /**
     * @return number
     */
    public function getHeight()
    {
        return $this->_height;
    }

    /**
     * @param number $height
     * @return $this
     */
    public function setHeight($height)
    {
        $this->_height = $height;
        return $this;
    }

    /**
     * @return number
     */
    public function getLength()
    {
        return $this->_length;
    }

    /**
     * @param number $length
     * @return $this
     */
    public function setLength($length)
    {
        $this->_length = $length;
        return $this;
    }

    /**
     * @return number
     */
    public function getWeight()
    {
        return $this->_weight;
    }

    /**
     * @param number $weight
     * @return $this
     */
    public function setWeight($weight)
    {
        $this->_weight = $weight;
        return $this;
    }

}