text:
current = 1
previous = 1
seqNo = 1

while ((len(str(current))) < 1000):
  nextNum = previous + current;
  previous = current;
  current = nextNum;
  seqNo = seqNo+1

print seqNo

# My method uses a standard fibannacci sequence (from Euler 2) while loop implementing python's string length function (after converting the# current number to a string). It prins out the sequence number of the first element with over 1000 digits


text:
<?php

namespace ItBlaster\CheckboxListBundle\Form\Type;

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

/**
 * Виджет "Список чекбоксов"
 *
 * Class CheckboxListType
 * @package ItBlaster\CheckboxListBundle\Form\Type
 */
class CheckboxListType extends AbstractType
{
    protected $choices = array();
    protected $name = 'checkbox_list';

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {

    }

    /**
     * Дефолтные значения
     *
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setOptional(array(
            'filter_add_foreign_object',
            'foreign_objects',
            'foreign_object_model',
            'bundle_alias'
        ));

        $resolver->setDefaults(array(
            'required'  => false,
            'multiple'  => true,
            'expanded'  => true,
        ));
    }

    /**
     * Инициализация переменных для шаблона виджета
     *
     * @param FormView $view
     * @param FormInterface $form
     * @param array $options
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['foreign_objects'] = $options['foreign_objects'];
        $view->vars['filter_add_foreign_object'] = $options['filter_add_foreign_object'];
        $view->vars['foreign_object_model'] = $options['foreign_object_model'];
        $bundle = $options['bundle_alias'];
        $foreign_alias = str_replace('_', '', $options['foreign_object_model']);
        $view->vars['foreign_object_link_add'] = 'admin_'.$bundle.'_'.$foreign_alias.'_create';
        $view->vars['foreign_object_link_edit'] = 'admin_'.$bundle.'_'.$foreign_alias.'_edit';
    }

    /**
     * Родительский виджет
     *
     * @return null|string|\Symfony\Component\Form\FormTypeInterface
     */
    public function getParent()
    {
        return 'choice';
    }

    /**
     * Имя виджета
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.isis.core.metamodel.facets.value.integer;

import org.apache.isis.core.metamodel.facetapi.FacetHolder;
import org.apache.isis.core.metamodel.facets.object.value.vsp.ValueFacetUsingSemanticsProviderFactory;

public class IntWrapperValueFacetUsingSemanticsProviderFactory extends ValueFacetUsingSemanticsProviderFactory<Integer> {

    public IntWrapperValueFacetUsingSemanticsProviderFactory() {
        super();
    }

    @Override
    public void process(final ProcessClassContext processClassContext) {
        final Class<?> type = processClassContext.getCls();
        final FacetHolder holder = processClassContext.getFacetHolder();

        if (type != Integer.class) {
            return;
        }
        addFacets(new IntWrapperValueSemanticsProvider(holder, getConfiguration(), getContext()));
    }

}


text:
class AddCoverPhotoToEvent < ActiveRecord::Migration
  def change
    add_column :events, :cover_photo, :string
  end
end


text:
#ifndef BOOST_MSM_INTERNAL_ROW_HPP
#define BOOST_MSM_INTERNAL_ROW_HPP

#include <boost/type_traits/is_base_of.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/fusion/include/at_key.hpp>
#include <boost/msm/row_tags.hpp>
#include <boost/msm/front/detail/row2_helper.hpp>

namespace boost { namespace msm { namespace front
{
    template<
        class Event
        , typename CalledForAction
        , void (CalledForAction::*action)(Event const&)
    >
    struct a_internal
    {
        typedef sm_a_i_row_tag row_type_tag;
        typedef Event Evt;
        template <class FSM,class SourceState,class TargetState,class AllStates>
        static void action_call(FSM& fsm,Event const& evt,SourceState& src,TargetState& tgt,
                                AllStates& all_states)
        {
            // in this front-end, we don't need to know source and target states
            ::boost::msm::front::detail::row2_action_helper<CalledForAction,Event,action>::call_helper
                (fsm,evt,src,tgt,all_states,
                ::boost::mpl::bool_< ::boost::is_base_of<CalledForAction,FSM>::type::value>());
        }
    };

    template<
        class Event
        , typename CalledForAction
        , void (CalledForAction::*action)(Event const&)
        , typename CalledForGuard
        , bool (CalledForGuard::*guard)(Event const&)
    >
    struct internal
    {
        typedef sm_i_row_tag row_type_tag;
        typedef Event Evt;
        template <class FSM,class SourceState,class TargetState,class AllStates>
        static void action_call(FSM& fsm,Event const& evt,SourceState& src,TargetState& tgt,
                                AllStates& all_states)
        {
            // in this front-end, we don't need to know source and target states
            ::boost::msm::front::detail::row2_action_helper<CalledForAction,Event,action>::call_helper
                (fsm,evt,src,tgt,all_states,
                ::boost::mpl::bool_< ::boost::is_base_of<CalledForAction,FSM>::type::value>());
        }
        template <class FSM,class SourceState,class TargetState,class AllStates>
        static bool guard_call(FSM& fsm,Event const& evt,SourceState& src,TargetState& tgt,
                               AllStates& all_states)
        {
            // in this front-end, we don't need to know source and target states
            return ::boost::msm::front::detail::row2_guard_helper<CalledForGuard,Event,guard>::call_helper
                (fsm,evt,src,tgt,all_states,
                ::boost::mpl::bool_< ::boost::is_base_of<CalledForGuard,FSM>::type::value>());
        }
    };
    template<
        class Event
        , typename CalledForGuard
        , bool (CalledForGuard::*guard)(Event const&)
    >
    struct g_internal
    {
        typedef sm_g_i_row_tag row_type_tag;
        typedef Event Evt;
        template <class FSM,class SourceState,class TargetState,class AllStates>
        static bool guard_call(FSM& fsm,Event const& evt,SourceState& src,TargetState& tgt,
                               AllStates& all_states)
        {
            // in this front-end, we don't need to know source and target states
            return ::boost::msm::front::detail::row2_guard_helper<CalledForGuard,Event,guard>::call_helper
                (fsm,evt,src,tgt,all_states,
                ::boost::mpl::bool_< ::boost::is_base_of<CalledForGuard,FSM>::type::value>());
        }
    };
    template<
        class Event
    >
    struct _internal
    {
        typedef sm__i_row_tag row_type_tag;
        typedef Event Evt;
    };
}}}

#endif //BOOST_MSM_INTERNAL_ROW_HPP


text:
package org.ev3dev.hardware;

//-----------------------------------------------------------------------------
//~autogen autogen-header

//~autogen
//-----------------------------------------------------------------------------

import java.io.IOException;

import org.ev3dev.exception.EV3LibraryException;

import org.ev3dev.hardware.ports.LegoPort;
import org.ev3dev.io.Sysfs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This is the base class that handles control tasks for a single port or index. The class must chose one device out of the available ports to control. Given an IO port (in the constructor), an implementation should:

- If the specified port is blank or unspecified/undefined/null, the available devices should be enumerated until a suitable device is found. Any device is suitable when it's type is known to be compatible with the controlling class, and it meets any other requirements specified by the caller.

- If the specified port name is not blank, the available devices should be enumerated until a device is found that is plugged in to the specified port. The supplied port name should be compared directly to the value from the file, so that advanced port strings will match, such as in1:mux3.

- If an error occurs after the initial connection, an exception should be thrown by the binding informing the caller of what went wrong. Unless the error is fatal to the application, no other actions should be taken.

 * @author Anthony
 *
 */
public abstract class Device {

    private static final Logger logger = LoggerFactory.getLogger(Device.class);

	private String className;

	private String classNamePrefix = null;

	private String address;

	private String classFullName = null;

	private LegoPort port;

	private boolean connected = false;

	/***
	 * Generic way to create a device
	 * @param className The Sysfs Class name
	 */
	public Device(String className){
	    logger.trace("Device Constructor starts - generic");
	    logger.debug("className="+ className);
		this.port = null;
		this.className = className;
		logger.trace("Device Constructor ends - generic");
	}

	/**
	 * Create a new device with a LegoPort, ClassName, classNamePrefix
	 * @param port A LegoPort delared before.
	 * @param className Sysfs class name
	 * @param classNamePrefix The filename prefix inside the "Sysfs class" (e.g. motor[n], which "motor" is the prefix)
	 * @throws EV3LibraryException If I/O goes wrong
	 */
	public Device(LegoPort port, String className, String classNamePrefix) throws EV3LibraryException{
	    logger.trace("Device Constructor starts");
		this.port = port;
		this.className = className;
		this.classNamePrefix = classNamePrefix;

		address = port.getAddress();

        logger.debug("port.getAddress()=" + address);
        logger.debug("c");

		connected = checkIsConnected();
		if (!connected){
			logger.info(className + "-" + this.hashCode() + ": No port connected. Searching until port \"" + address + "\" connected...");

			while (!connected){
				connected = checkIsConnected();
			}

			logger.info(className + "-" + this.hashCode() + ": Connected to " + address);
		}

        logger.trace("Device Constructor ends");
	}

	public abstract String getAddress() throws EV3LibraryException;

	public abstract String getDriverName() throws EV3LibraryException;

	/**
	 * Set the Sysfs class name (location) of this Device
	 * @param className The Sysfs class name located in /sys/class
	 */
	public void setClassName(String className){
		this.className = className;
	}

	/**
	 * Set the Sysfs class full name (including prefix if any)
	 * @param classFullName The Sysfs class name located in /sys/class/[className]
	 */
	public void setClassFullname(String classFullName){
		this.classFullName = classFullName;
	}

	/**
	 * Set the filename prefix inside the Sysfs class (prefix (e.g. motor)) of this Device
	 * @param classNamePrefix The filename inside the Sysfs class (e.g. "/sys/class/motor/motor0" motor is a prefix)
	 */
	public void setClassNamePrefix(String classNamePrefix){
		this.classNamePrefix = classNamePrefix;
	}

	/**
	 * If a valid device is found while enumerating the ports, the connected variable is set to true (by default, it should be false). If connected is false when an attempt is made to read from or write to a property file, an error should be thrown (except while in the consructor).
	 * @return Whether the device is ready.
	 */
	public boolean isConnected(){
		return connected;
	}

	/**
	 * Returns the LegoPort connected with this Device
	 * @return LegoPort object
	 */
	public LegoPort getPort(){
		return port;
	}

	/**
	 * Get the filename prefix inside the Sysfs class (prefix (e.g. motor)) of this Device
	 * @return The filename inside the Sysfs class (e.g. "/sys/class/motor/motor0" motor is a prefix)
	 */
	public String getClassNamePrefix(){
		return classNamePrefix;
	}

	/**
	 * Get the full filename (not prefix) inside the Sysfs class of this Device. This must be already searched by the checkIsConnected() method
	 * @return The filename inside the Sysfs class (e.g. "/sys/class/motor/motor0" motor0 is the full name)
	 */
	public String getClassFullName(){
		return classNamePrefix;
	}

	/***
	 * Reads the property specified.
	 * @param property The property name
	 * @return The value of the property
	 */
	public final String getAttribute(String property) throws EV3LibraryException{
		try {
			String str = Sysfs.getAttribute(className, classFullName, property);
			connected = true;
			return str;
		} catch (IOException e){
			connected = false;
			throw new EV3LibraryException("Get device attribute failed: " + property, e);
		}
	}

	/***
	 * Writes the property specified.
	 * @param property The property name
	 * @param new_value The new value of the property
	 */
	public final void setAttribute(String property, String new_value) throws EV3LibraryException{
		try {
			Sysfs.setAttribute(className, classFullName, property, new_value);
			connected = true;
		} catch (IOException e){
			connected = false;
			throw new EV3LibraryException("Set device attribute failed: " + property, e);
		}
	}

	private boolean checkIsConnected(){
		try {
			classFullName = Sysfs.searchClassFullName(className, classNamePrefix, address);
		} catch (Exception ignore){
			classFullName = null;
			return false;
		}
		return classFullName != null;
	}
}


text:
export {default as Container} from './Container'
export {default as Line} from './LineBreak'
export {default as Modal} from './Modal'
export {default as Scrollable} from './Scrollable'
export {default as Tabs} from './Tabs'
export * as Parallax from './Parallax'


text:
<?php

namespace AppBundle\Controller;

use AppBundle\Exception\FieldDoesNotExistException;
use AppBundle\Field\FieldProvider;
use AppBundle\Service\AdventureSearch;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class ApiController extends Controller
{
    /**
     * @Route("/autocomplete/field/{fieldName}", name="api_autocomplete_field")
     * @Method("GET")
     *
     * @param Request $request
     * @param FieldProvider $fieldProvider
     * @param AdventureSearch $adventureSearch
     * @param string $fieldName
     * @return JsonResponse
     */
    public function autocompleteFieldValueAction(Request $request, FieldProvider $fieldProvider, AdventureSearch $adventureSearch, string $fieldName)
    {
        try {
            $field = $fieldProvider->getField($fieldName);
        } catch (FieldDoesNotExistException $e) {
            throw new NotFoundHttpException();
        }

        $q = $request->query->get('q');
        $results = $adventureSearch->autocompleteFieldContent($field, $q);

        return new JsonResponse($results);
    }

    /**
     * @Route("/autocomplete/similar-titles", name="similar_titles_search")
     * @Method("GET")
     *
     * @param Request $request
     * @param AdventureSearch $adventureSearch
     * @return JsonResponse
     */
    public function findSimilarTitlesAction(Request $request, AdventureSearch $adventureSearch)
    {
        $q = $request->query->get('q', false);
        if ($q === false) {
            throw new NotFoundHttpException();
        }

        return new JsonResponse($adventureSearch->similarTitles($q));
    }
}


text:
#pragma once

#include <QtCore/QList>
#include <QtCore/QObject>
#include <QtWidgets/QAction>

#include <qrgui/plugins/toolPluginInterface/actionInfo.h>
#include <qrgui/plugins/toolPluginInterface/hotKeyActionInfo.h>
#include <qrgui/plugins/toolPluginInterface/usedInterfaces/mainWindowInterpretersInterface.h>

#include "interpreterCore/managers/kitPluginManager.h"
#include "interpreterCore/managers/robotModelManager.h"

namespace interpreterCore {

/// Class that initializes, holds and keeps up-to-date actions added to toolbar and into user menus.
class ActionsManager : public QObject
{
	Q_OBJECT

public:
	/// Constructor.
	/// @param kitPluginManager - information about currently loaded kit plugins.
	/// @param robotModelManager - needed to be able to switch models directly from ActionsManager.
	/// @todo: Get rid of RobotModelManager dependence
	ActionsManager(KitPluginManager &kitPluginManager, RobotModelManager &robotModelManager);

	/// Initializes this manager and sets "enabled" status for its actions.
	void init(qReal::gui::MainWindowInterpretersInterface *mainWindowInterpretersInterface);

	/// Returns list of currently available actions (including kit- and model-specific).
	QList<qReal::ActionInfo> actions();

	/// Returns hotkeys for available actions.
	/// @todo Why we can't store hotkey information inside ActionInfo?
	QList<qReal::HotKeyActionInfo> hotKeyActionInfos();

	/// Start interpretation action.
	/// @todo Does nothing on real TRIK model, need to connect it to corresponding generator action somehow.
	QAction &runAction();

	/// Stop interpretation.
	/// @todo Also confusingly has nothing to do with "stop robot" generator action on TRIK.
	QAction &stopRobotAction();

	/// Action for establishing connection to a robot.
	QAction &connectToRobotAction();

	/// Action that shows settings page with "robots" tab selected.
	QAction &robotSettingsAction();

	/// Action that allows to save current model as an exercise with different limitations, such as inability to
	/// change world in 2d model or configuration of robot sensors.
	QAction &exportExerciseAction();

	/// Action that changes current UI mode to debug: hides palette, property editor and so on,
	/// opens variable values dock and maybe 2D model dock.
	QAction &debugModeAction();

	/// Action that changes current UI mode to edit: show palette and property editor if we are
	/// editing diagram or variables list if we are editing the code.
	/// Closes variable values dock and maybe 2D model dock.
	QAction &editModeAction();

	/// Action that opens first robot behaviour diagram in current model or start page if no save opened.
	QAction &homeAction();

	/// Provides a possibility to transfer hotkey configurer to engine.
	void appendHotKey(const QString &actionId, const QString &label, QAction &action);

public slots:
	/// Reacts to selection of another robot model.
	/// @param model - newly selected robot model.
	void onRobotModelChanged(kitBase::robotModel::RobotModelInterface &model);

	/// Reacts to selection of a new tab in main window.
	/// @param info - the information about the new active tab.
	void onActiveTabChanged(const qReal::TabInfo &info);

private slots:
	void onRobotModelActionChecked(QObject *robotModelObject);

private:
	QString kitIdOf(kitBase::robotModel::RobotModelInterface &model) const;

	/// Updates "enabled" status of plugin actions taking into account current tab, selected robot model and so on.
	void updateEnabledActions();

	/// Loads actions from kit plugins.
	void initKitPluginActions();

	/// Sets object names to actions.
	void giveObjectNames();

	/// Creates action with menu that lets switching between robot models.
	QAction *produceMenuAction(const QString &kitId, const QString &name, const QList<QAction *> &subActions) const;

	/// Plugins can have their own custom actions, we need to get them from KitPluginManager.
	KitPluginManager &mKitPluginManager;

	/// Actions may switch robot models so we need robot model manager.
	RobotModelManager &mRobotModelManager;

	/// Action that runs program
	QAction *mRunAction;  // Takes ownership, need to be stored by value after svg actions fix.

	/// Action that stops program and also stops robot motors
	QAction *mStopRobotAction;  // Takes ownership, need to be stored by value after svg actions fix.

	/// Checkable action that establishes connection to robot. If successful,
	/// action will be checked, if connection lost, it will uncheck
	QAction *mConnectToRobotAction;  // Takes ownership, need to be stored by value after svg actions fix.

	/// Action that shows robots tab in settings dialog
	QAction mRobotSettingsAction;

	/// Action that allows to save current model as an exercise with different limitations, such as inability to
	/// change world in 2d model or configuration of robot sensors.
	QAction mExportExerciseAction;

	/// Action that changes current UI mode to debug: hides palette, property editor and so on,
	/// opens variable values dock and maybe 2D model dock.
	QAction *mDebugModeAction;  // Takes ownership, need to be stored by value after svg actions fix.

	/// Action that changes current UI mode to edit: show palette and property editor if we are
	/// editing diagram or variables list if we are editing the code.
	/// Closess variable values dock and maybe 2D model dock.
	QAction *mEditModeAction;  // Takes ownership, need to be stored by value after svg actions fix.

	/// Action that opens first robot behaviour diagram in current model or start page if no save opened.
	QAction *mHomeAction;

	QAction mSeparator1;
	QAction mSeparator2;

	/// List of plugin actions, for convenient initialization. Contains all actions which already present as fields.
	QList<QAction *> mActions;  // Does not have ownership (actions already present as fields).

	/// List of actions from kit plugins.
	QList<qReal::ActionInfo> mPluginActionInfos;  // Does not have ownership over underlying QActions.

	/// Actions that are placed on the panel for quick switching between robot models.
	QMultiMap<QString, qReal::ActionInfo> mRobotModelActions;

	/// List of hotkey customizations from kit plugins.
	QList<qReal::HotKeyActionInfo> mPluginHotKeyActionInfos;  // Does not have ownership over underlying QActions.

	/// List of additional hotkey customizations obtained from external environment.
	QList<qReal::HotKeyActionInfo> mAdditionalHotKeyInfos;  // Does not have ownership over underlying QActions.

	/// Main window interface object, to ask about currently open tab and so on.
	// Does not have ownership
	qReal::gui::MainWindowInterpretersInterface *mMainWindowInterpretersInterface = nullptr;
};

}


text:
import sys
import time
import tb as traceback

from browser import console

def discover_brython_test_modules():
    # TODO : Test discovery based on file system paths
    return [
        ("Core language features", [
          ("test_suite.py", "basic test suite"),
          ("test_rmethods.py", "reflected methods"),
          ("test_bytes.py", "bytes"),
          ("test_classes.py", "classes"),
          ("test_decorators.py", "decorators"),
          ("test_descriptors.py", "descriptors"),
          ("test_dict.py", "dicts"),
          ("test_exec.py", "exec / eval"),
          ("test_generators.py", "generators"),
          ("test_import.py", "imports"),
          ("test_iterators.py", "iterators"),
          ("test_jsobjects.py", "Javascript objects"),
          ("test_list.py", "lists"),
          ("test_memoryview.py", "memoryview"),
          ("test_numbers.py", "numbers"),
          ("test_print.py", "print"),
          ("test_set.py", "sets"),
          ("test_special_methods.py", "special methods"),
          ("test_strings.py", "strings"),
          ("test_fstrings.py", "f-strings"),
          ("test_string_format.py", "string format"),
          ("test_string_methods.py", "string methods")
        ]),
        ("DOM interface", [
            ("dom.py", "DOM")
        ]),
        ("Issues", [
          ("issues_gc.py", "issues (GC)"),
          ("issues_bb.py", "issues (BB)"),
          ("issues.py", "issues")
        ]),
        ("Modules", [
          ("test_aio.py", "browser.aio"),
          ("test_binascii.py", "binascii"),
          ("test_bisect.py", "bisect"),
          ("test_code.py", "code"),
          ("test_collections.py", "collections"),
          ("test_dataclasses.py", "dataclasses"),
          ("test_datetime.py", "datetime"),
          ("test_decimals.py", "decimals"),
          ("test_functools.py", "functools"),
          ("test_hashlib.py", "hashlib"),
          ("test_itertools.py", "itertools"),
          ("test_json.py", "json"),
          ("test_math.py", "math"),
          ("test_pickle.py", "pickle"),
          ("test_random.py", "random"),
          ("test_re.py", "re"),
          ("test_storage.py", "storage"),
          ("test_struct.py", "struct"),
          ("test_sys.py", "sys"),
          ("test_types.py", "types"),
          ("test_unicodedata.py", "unicodedata"),
          ("test_unittest.py", "unittest"),
          ("test_urllib.py", "urllib"),
          #("test_indexedDB.py", "indexedDB"),
          #("test_time.py", "time"),
        ])
    ]

def populate_testmod_input(elem, selected=None):
    """Build a multiple selection control including test modules
    """
    from browser import html
    groups = discover_brython_test_modules()
    for label, options in groups:
        if selected and label not in selected:
            continue
        g = html.OPTGROUP(label=label)
        elem <= g
        for filenm, caption in options:
            if filenm == selected:
                o = html.OPTION(caption, value=filenm, selected='')
            else:
                o = html.OPTION(caption, value=filenm)
            g <= o

def run(src, file_path=None):
    t0 = time.perf_counter()
    msg = ''
    try:
        ns = {'__name__':'__main__'}
        if file_path is not None:
            ns['__file__'] = file_path
        exec(src, ns)
        state = 1
    except Exception as exc:
        msg = traceback.format_exc()
        print(msg, file=sys.stderr)
        state = 0
    t1 = time.perf_counter()
    return state, t0, t1, msg

def run_test_module(filename, base_path=''):
    if base_path and not base_path.endswith('/'):
        base_path += '/'
    file_path = base_path + filename
    src = open(file_path).read()
    return run(src, file_path)


text:
#ifdef HAVE_CONFIG_H
#include "../../ext_config.h"
#endif

#include <php.h>
#include "../../php_ext.h"
#include "../../ext.h"

#include <Zend/zend_exceptions.h>

#include "kernel/main.h"

/**
 * Phalcon\Validation\Message
 *
 * Interface for Phalcon\Validation\Message
 */
ZEPHIR_INIT_CLASS(Phalcon_Validation_MessageInterface) {

	ZEPHIR_REGISTER_INTERFACE(Phalcon\\Validation, MessageInterface, phalcon, validation_messageinterface, phalcon_validation_messageinterface_method_entry);

	return SUCCESS;

}

/**
 * Phalcon\Validation\Message constructor
 *
 * @param string message
 * @param string field
 * @param string type
 */
ZEPHIR_DOC_METHOD(Phalcon_Validation_MessageInterface, __construct);

/**
 * Sets message type
 */
ZEPHIR_DOC_METHOD(Phalcon_Validation_MessageInterface, setType);

/**
 * Returns message type
 */
ZEPHIR_DOC_METHOD(Phalcon_Validation_MessageInterface, getType);

/**
 * Sets verbose message
 */
ZEPHIR_DOC_METHOD(Phalcon_Validation_MessageInterface, setMessage);

/**
 * Returns verbose message
 *
 * @return string
 */
ZEPHIR_DOC_METHOD(Phalcon_Validation_MessageInterface, getMessage);

/**
 * Sets field name related to message
 */
ZEPHIR_DOC_METHOD(Phalcon_Validation_MessageInterface, setField);

/**
 * Returns field name related to message
 *
 * @return string
 */
ZEPHIR_DOC_METHOD(Phalcon_Validation_MessageInterface, getField);

/**
 * Magic __toString method returns verbose message
 */
ZEPHIR_DOC_METHOD(Phalcon_Validation_MessageInterface, __toString);

/**
 * Magic __set_state helps to recover messsages from serialization
 */
ZEPHIR_DOC_METHOD(Phalcon_Validation_MessageInterface, __set_state);


text:
#ifndef DFFDEVAL_H_
#define DFFDEVAL_H_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include "XMLTree.h"

// DFFDEVAL.h : header file
//

/////////////////////////////////////////////////////////////////////////////
// CDFFDEval dialog

class CDFFDEval : public CDialog
{
// Construction
public:
	CDFFDEval(CXmlTree::CElt *pp, signed char parent_type, CWnd* pParent = NULL);   // standard constructor
	virtual ~CDFFDEval();

	bool IsModified() const { return modified_; }
	void SetModified(bool mm = true) { modified_ = mm; }
	void GetPosition(CPoint &pp) const { pp.x = pos_.x; pp.y = pos_.y; }
	void SetPosition(CPoint pp, CPoint oo = CPoint(-1,-1))
	{
		pos_ = pp;
		if (oo == CPoint(-1,-1))
			orig_ = pp, first_ = true;
		else
			orig_ = oo;
	}

// Dialog Data
	//{{AFX_DATA(CDFFDEval)
	enum { IDD = IDD_DFFD_EVAL };
	CButton ctl_prev_;
	CButton ctl_next_;
	CString expr_;
	int     display_result_;
	int     display_error_;
	CString comment_;
	//}}AFX_DATA
	CEdit ctl_expr_;
	CMFCMenuButton ctl_expr_var_;

// Overrides
	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CDFFDEval)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:

	// Generated message map functions
	//{{AFX_MSG(CDFFDEval)
	afx_msg void OnNext();
	afx_msg void OnPrev();
	virtual void OnOK();
	virtual BOOL OnInitDialog();
	afx_msg void OnChange();
	virtual void OnCancel();
	afx_msg BOOL OnHelpInfo(HELPINFO* pHelpInfo);
	//}}AFX_MSG
	afx_msg void OnContextMenu(CWnd* pWnd, CPoint point);
	afx_msg LRESULT OnKickIdle(WPARAM, LPARAM);
	afx_msg void OnHelp();
	afx_msg void OnGetExprVar();
	DECLARE_MESSAGE_MAP()

	CXmlTree::CElt *pelt_;      // The EVAL element we are editing
	CXmlTree::CFrag saved_;     // Saved copy of the children (before editing) in case Cancel pressed
	bool saved_mod_flag_;       // If dialog cancelled then we have to restore the modified status
	bool show_prev_next_;       // Show the << and >> buttons (parent is STRUCT)
	CPoint pos_;                // Position of this dialog
	CPoint orig_;               // Position of the first dialog opened
	bool modified_;             // Have any of the values been changed?
	bool first_;                // Is this the first dialog called (since any DFFD dialog can call any other)
	signed char parent_type_;   // Type of container of this element
	CMenu *pexpr_menu_;         // Menu displaying all availbale vars for "expr"

	void            load_data();
	bool            check_data();
	void            save_data();
};

#endif


text:
Structural Variant Prediction Viewer
------------------------------------
SVPV enables visualisation of predicted structural variant regions in paired-end whole genome sequencing alignments, and
allows comparison of calls from differenct structural variant prediction algorithms. Statistics related to structural
variants are presented in a form that allows users to visually identify false postive calls. Input is a set alignment
files (SAM/BAM/CRAM format) along with a set of structural variant predictions on these alignments (VCF files). Output
is a set of pdf files of structural variant regions. Please see the [wiki](https://github.com/VCCRI/SVPV/wiki/Home) for
examples of SVPV plots of different structural variant categories.

SVPV supports VCF structural variant types deletion (DEL), duplication (DUP), copy number variation (CNV), inversion (INV),
insertion (INS) and breakend ('BND'). Delly2-style translocations (TRA) are also supported.

### Requirements
**Command Line Mode**
* Python 2.7.+ and NumPy
* R v3.+
* [SAMtools and BCFtools](https://github.com/samtools) (version 1.3)
* Linux environment, or access to linux via ssh

**Note:** SAMtools and BCFtools must be executable by typing 'samtools' and 'bcftools' into the terminal.

**GUI Mode**
* All command line mode requirements, and:
* X11 if running over ssh
* python 2.7 tkinter
* Recommended: [GraphicsMagick](http://www.graphicsmagick.org/README.html) or ImageMagick ('display')
  * GraphicsMagick build w/ --enable-magick-compat
  * Note: any other X11 capable pdf viewer specified by '-disp' will work
  * alternatively users can navigate to plot directory and open the file with a local pdf viewer

### Installation
* Navigate to desired install directory and clone this repository.

  `git clone https://github.com/VCCRI/SVPV.git SVPV`
* Ensure that requirements are met. For convenience shell scripts are provided for Ubuntu and CentOS.

  `sudo sh ./SVPV/set_up/Ubuntu_set_up.sh`
* Test that SVPV is working. If you get any error messages at this point it is likely that some requirements aren't met.

  `python ./SVPV/SVPV -example`
* Test the gui is working

  `python ./SVPV/SVPV -example -gui`
* all done!

### Non-linux users
* The easiest way to get SVPV running on your Windows or Mac is to run a virtual machine in software such as
 [Oracle VM Virtual Box](https://www.virtualbox.org/).
* You can download an Ubuntu 16.04 image at [osboxes.org](http://www.osboxes.org/ubuntu/)
* After your Ubuntu image is running follow the installation instructions above

### Usage
Running in GUI mode allows users to select and view individual structural variant calls on some subset of the supplied
samples. Running in batch mode (i.e. not GUI mode) will generates plots for each call with the suplied set of samples,
matching the supplied filter arguments.

|Run args:            | Description                                                                | Notes    |
|---------------------|----------------------------------------------------------------------------|----------|
|-vcf1     | Comma separated list of structural variant prediction VCF/BCF files        | required |
|-o                   | Output directory                                                           | required |
|-aln                 | Comma separated list of alignment files (indexed BAM/CRAM)                 | required 2
|-samples             | Comma separated list of samples to view, names must be the same as in VCF  | required 2
|-gui                 | run in gui mode                                                            | optional |
|-ref_vcf1 | Reference structural variant vcf/bcf file for annotation                   | optional |
|-ref_gene            | Refseq genes regene table file for annotation3                  | optional |
|-manifest            | Whitespace delimited file, first column sample names,
 second column alignment file path. Overrides '-samples' and '-aln' if also given.                                                     | optional |
|-ped                 | Tab separated pedigree file (GUI only)                                     | optional |
|-fam                 | Restrict to this family id only. Requires '-ped'.                          | optional |
|-separate_plots      | Plot each sample separately                                                | optional |
|-l_svs               | show SVs extending beyond the current plot area.                           | optional |
|-disp                | PDF viewer command. GUI mode only. Default: "display"                      | optional |
|-rd_len              | sequencing read length, optimises window size. Default: 100                | optional |
|-exp                 | window expansion, proportion of SV len added to each side. Default: 1      | optional |
|-bkpt_win            | breakpoint window, number of read lengths to set windows around breakpoints
 Default:5                                                                                | optional |
|-n_bins              | target number of bins for plot window. Default: 100                        | optional |

1vcfs may be specified by a file (e.g. '-vcf /path/to/file.vcf') or by a name and a file
(e.g. '-vcf delly:/path/to/file'). If not specified names will be 'vcf 1', 'vcf 2', etc and 'reference' by default.

2'-samples' and '-aln' not required if '-manifest' is supplied.

3Availble for a variety of reference genomes at [UCSC Table Browser](https://genome.ucsc.edu/cgi-bin/hgTables)

|Filter args: | Description                                     | Example                          |
------------- |-------------------------------------------------|----------------------------------|
| -max_len    | maximum length of structural variants (bp)      |                                  |
| -min_len    | minimum length of structural variants (bp)      |                                  |
| -af         | Allele frequency threshold                      | -af <0.1                         |
| -gts        | Specify genotypes of given samples              | sample1:0/1,1/1;sample2:1/1      |
| -chrom      | Restrict to comma separated list of chromosomes |                                  |
| -svtype     | Restrict to given SV type (DEL/DUP/CNV/INV)     |                                  |
| -rgi        | Restrict to SVs that intersect refGenes,
'-ref_gene' must be supplied          |
| -exonic     | Restrict to SVs that intersect exons of refGenes,
'-ref_gene' must be supplied |

|Plot args: | Default | Description                                             |
|-----------|---------|---------------------------------------------------------|
|-d         | 1       | force sequencing depth plot on or off                   |
|-or        | 1       | force orphaned reads plot on or off                     |
|-v         | 1       | force inverted pairs plot on or off                     |
|-ss        | 1       | force same strand pairs plot on or off                  |
|-cl        | 1       | force clipped reads plot on or off                      |
|-se        | 0       | force SAM 'secondary alignment' plot on or off          |
|-su        | 0       | force SAM 'supplementary alignment' plot on or off      |
|-dm        | 0       | force mate different molecule alignment plot on or off  |
|-i         | 1       | force inferred insert size plot on or off               |
|-r         | 1       | force refgenes plot on or off                           |
|-af        | 1       | force allele frequency plot on or off                   |
|-l         | 1       | force plot legend on or off                             |

**Usage example:**
```
python SVPV -gui -o ./example/output/ -vcf delly:./example/delly.vcf,cnvnator:./example/cnvnator.vcf -manifest
/example/example.manifest -ref_gene ./example/hg38.refgene.partial.txt -ref_vcf 1000G:./example/1000G.vcf
```
**Advance usage example:**
```
python SVPV -vcf caller1_svs.vcf,caller2_svs.vcf -samples sample1,sample2,sample3 -aln s1.bam,s2.bam,s3.bam
-o /out/directory/ -ref_vcf 1000_genomes_svs.vcf -ref_gene hg38.refgene.txt -max_len 100000 -af <0.25 -gts
sample1:1/1,0/1;sample3:0/0 -svtype DEL -exonic -ss 0 -se 1
```

###  VCF Field Requirements:

SV Type         | Required VCF Fields
----------------|------------------------------------------------|
All Types       | CHROM, POS, SVTYPE1, GT2 |
DEL/DUP/CNV/INV | SVLEN or END                                   |
INS             | SVLEN or INSLEN\*                              |
BND             | ALT, ID, MATEID/PAIRID/EVENTID                 |
TRA\*           | CHR2, END                                      |

1If SVTYPE is not found then ALT is parsed for symbolic alternate alleles.
These should match one of DEL, DUP, CNV, INS, INV, BND or TRA or the call will be ignored.

2For reference VCF only, GT is not required if AF is present.

*Included for compatibility with Delly2

Please see the [VCF specifications](http://samtools.github.io/hts-specs/VCFv4.3.pdf) for further details.

### SVPV Plot Window Sizing and Types
* Please see the [wiki](https://github.com/VCCRI/SVPV/wiki/SVPV-Plot-Windows)

### Citation
Jacob E. Munro, Sally L. Dunwoodie, Eleni Giannoulatou; SVPV: a structural variant prediction viewer for paired-end sequencing datasets. Bioinformatics 2017; 33 (13): 2032-2033. doi: 10.1093/bioinformatics/btx117


text:
#ifndef _EAS_DATA_H
#define _EAS_DATA_H

#include "eas_types.h"
#include "eas_synthcfg.h"
#include "eas.h"
#include "eas_audioconst.h"
#include "eas_sndlib.h"
#include "eas_pcm.h"
#include "eas_pcmdata.h"
#include "eas_synth.h"
#include "eas_miditypes.h"
#include "eas_effects.h"

#ifdef AUX_MIXER
#include "eas_auxmixdata.h"
#endif

#ifdef JET_INTERFACE
#include "jet.h"
#endif

#ifdef _METRICS_ENABLED
#include "eas_perf.h"
#endif

#ifndef MAX_NUMBER_STREAMS
#define MAX_NUMBER_STREAMS          4
#endif

/* flags for S_EAS_STREAM */
#define STREAM_FLAGS_PARSED         1
#define STREAM_FLAGS_PAUSE          2
#define STREAM_FLAGS_LOCATE         4
#define STREAM_FLAGS_RESUME         8

/* structure for parsing a stream */
typedef struct s_eas_stream_tag
{
    void                            *pParserModule;
    EAS_U32                         time;
    EAS_U32                         frameLength;
    EAS_I32                         repeatCount;
    EAS_VOID_PTR                    handle;
    EAS_U8                          volume;
    EAS_BOOL8                       streamFlags;
} S_EAS_STREAM;

/* default master volume is -10dB */
#define DEFAULT_VOLUME              90
#define DEFAULT_STREAM_VOLUME       100
#define DEFAULT_STREAM_GAIN         14622

/* 10 dB of boost available for individual parsers */
#define STREAM_VOLUME_HEADROOM      10

/* amalgamated persistent data type */
typedef struct s_eas_data_tag
{
#ifdef _CHECKED_BUILD
    EAS_U32                         handleCheck;
#endif
    EAS_HW_DATA_HANDLE              hwInstData;

    S_EFFECTS_MODULE                effectsModules[NUM_EFFECTS_MODULES];

#ifdef _METRICS_ENABLED
    S_METRICS_INTERFACE             *pMetricsModule;
    EAS_VOID_PTR                    pMetricsData;
#endif

    EAS_I32                         *pMixBuffer;
    EAS_PCM                         *pOutputAudioBuffer;

#ifdef AUX_MIXER
    S_EAS_AUX_MIXER                 auxMixer;
#endif

#ifdef _MAXIMIZER_ENABLED
    EAS_VOID_PTR                    pMaximizerData;
#endif

    S_EAS_STREAM                    streams[MAX_NUMBER_STREAMS];

    S_PCM_STATE                     *pPCMStreams;

    S_VOICE_MGR                     *pVoiceMgr;

#ifdef JET_INTERFACE
    JET_DATA_HANDLE                 jetHandle;
#endif

    EAS_U32                         renderTime;
    EAS_I16                         masterGain;
    EAS_U8                          masterVolume;
    EAS_BOOL8                       staticMemoryModel;
    EAS_BOOL8                       searchHeaderFlag;
} S_EAS_DATA;

#endif


text:
package storm.trident.state.map;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class MicroBatchIBackingMap<T> implements IBackingMap<T> {
    IBackingMap<T> _delegate;
    Options _options;

    public static class Options implements Serializable {
        public int maxMultiGetBatchSize = 0; // 0 means delegate batch size = trident batch size.
        public int maxMultiPutBatchSize = 0;
    }

    public MicroBatchIBackingMap(final Options options, final IBackingMap<T> delegate) {
        _options = options;
        _delegate = delegate;
        assert options.maxMultiPutBatchSize >= 0;
        assert options.maxMultiGetBatchSize >= 0;
    }

    @Override
    public void multiPut(final List<List<Object>> keys, final List<T> values) {
        int thisBatchSize;
        if(_options.maxMultiPutBatchSize == 0) { thisBatchSize = keys.size(); }
        else { thisBatchSize = _options.maxMultiPutBatchSize; }

        LinkedList<List<Object>> keysTodo = new LinkedList<List<Object>>(keys);
        LinkedList<T> valuesTodo = new LinkedList<T>(values);

        while(!keysTodo.isEmpty()) {
            List<List<Object>> keysBatch = new ArrayList<List<Object>>(thisBatchSize);
            List<T> valuesBatch = new ArrayList<T>(thisBatchSize);
            for(int i=0; i<thisBatchSize && !keysTodo.isEmpty(); i++) {
                keysBatch.add(keysTodo.removeFirst());
                valuesBatch.add(valuesTodo.removeFirst());
            }

            _delegate.multiPut(keysBatch, valuesBatch);
        }
    }

    @Override
    public List<T> multiGet(final List<List<Object>> keys) {
        int thisBatchSize;
        if(_options.maxMultiGetBatchSize == 0) { thisBatchSize = keys.size(); }
        else { thisBatchSize = _options.maxMultiGetBatchSize; }

        LinkedList<List<Object>> keysTodo = new LinkedList<List<Object>>(keys);

        List<T> ret = new ArrayList<T>(keys.size());

        while(!keysTodo.isEmpty()) {
            List<List<Object>> keysBatch = new ArrayList<List<Object>>(thisBatchSize);
            for(int i=0; i<thisBatchSize && !keysTodo.isEmpty(); i++) {
                keysBatch.add(keysTodo.removeFirst());
            }

            List<T> retSubset = _delegate.multiGet(keysBatch);
            ret.addAll(retSubset);
        }

        return ret;
    }
}


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe DependencyCondition do
  it "should have a list of operators" do
    %w(== != < > <= >=).each do |operator|
      DependencyCondition.operators.include?(operator).should be_true
    end
  end

  describe "instance" do
    before(:each) do
      @dependency_condition = DependencyCondition.new(
        :dependency_id => 1, :question_id => 45, :operator => "==",
        :answer_id => 23, :rule_key => "A")
    end

    it "should be valid" do
      @dependency_condition.should be_valid
    end

    it "should be invalid without a parent dependency_id, question_id" do
      # this causes issues with building and saving
      # @dependency_condition.dependency_id = nil
      # @dependency_condition.should have(1).errors_on(:dependency_id)
      # @dependency_condition.question_id = nil
      # @dependency_condition.should have(1).errors_on(:question_id)
    end

    it "should be invalid without an operator" do
      @dependency_condition.operator = nil
      @dependency_condition.should have(2).errors_on(:operator)
    end

    it "should be invalid without a rule_key" do
      @dependency_condition.should be_valid
      @dependency_condition.rule_key = nil
      @dependency_condition.should_not be_valid
      @dependency_condition.should have(1).errors_on(:rule_key)
    end

    it "should have unique rule_key within the context of a dependency" do
      @dependency_condition.should be_valid
      DependencyCondition.create(
        :dependency_id => 2, :question_id => 46, :operator => "==",
        :answer_id => 14, :rule_key => "B")
      @dependency_condition.rule_key = "B" # rule key uniquness is scoped by dependency_id
      @dependency_condition.dependency_id = 2
      @dependency_condition.should_not be_valid
      @dependency_condition.should have(1).errors_on(:rule_key)
    end

    it "should have an operator in DependencyCondition.operators" do
      DependencyCondition.operators.each do |o|
        @dependency_condition.operator = o
        @dependency_condition.should have(0).errors_on(:operator)
      end
      @dependency_condition.operator = "#"
      @dependency_condition.should have(1).error_on(:operator)
    end
    it "should have a properly formed count operator" do
      %w(count>1 count<1 count>=1 count<=1 count==1 count!=1).each do |o|
        @dependency_condition.operator = o
        @dependency_condition.should have(0).errors_on(:operator)
      end
      %w(count> count< count>= count<= count== count!=).each do |o|
        @dependency_condition.operator = o
        @dependency_condition.should have(1).errors_on(:operator)
      end
      %w(count=1 count><1 count<>1 count!1 count!!1 count=>1 count=<1).each do |o|
        @dependency_condition.operator = o
        @dependency_condition.should have(1).errors_on(:operator)
      end
      %w(count= count>< count<> count! count!! count=> count=< count> count< count>= count<= count== count!=).each do |o|
        @dependency_condition.operator = o
        @dependency_condition.should have(1).errors_on(:operator)
      end
    end

    it "should protect timestamps" do
      saved_attrs = @dependency_condition.attributes
      if defined? ActiveModel::MassAssignmentSecurity::Error
        lambda {@dependency_condition.update_attributes(:created_at => 3.days.ago, :updated_at => 3.hours.ago)}.should raise_error(ActiveModel::MassAssignmentSecurity::Error)
      else
        @dependency_condition.attributes = {:created_at => 3.days.ago, :updated_at => 3.hours.ago} # automatically protected by Rails
      end
      @dependency_condition.attributes.should == saved_attrs
    end

  end

  it "returns true for != with no responses" do
    question = Factory(:question)
    dependency_condition = Factory(:dependency_condition, :rule_key => "C", :question => question)
    rs = Factory(:response_set)
    dependency_condition.to_hash(rs).should == {:C => false}
  end

  it "should not assume that Response#as is not nil" do
    # q_HEIGHT_FT "Portion of height in whole feet (e.g., 5)",
    # :pick=>:one
    # a :integer
    # a_neg_1 "Refused"
    # a_neg_2 "Don't know"
    # label "Provided value is outside of the suggested range (4 to 7 feet). This value is admissible, but you may wish to verify."
    # dependency :rule=>"A or B"
    # condition_A :q_HEIGHT_FT, "<", {:integer_value => "4"}
    # condition_B :q_HEIGHT_FT, ">", {:integer_value => "7"}

    answer = Factory(:answer, :response_class => :integer)
    @dependency_condition = DependencyCondition.new(
      :dependency => Factory(:dependency),
      :question => answer.question,
      :answer => answer,
      :operator => ">",
      :integer_value => 4,
      :rule_key => "A")

    response = Factory(:response, :answer => answer, :question => answer.question)
    response_set = response.response_set
    response.integer_value.should == nil

    @dependency_condition.to_hash(response_set).should == {:A => false}
  end

  describe "evaluate '==' operator" do
    before(:each) do
      @a = Factory(:answer, :response_class => "answer")
      @b = Factory(:answer, :question => @a.question)
      @r = Factory(:response, :question => @a.question, :answer => @a)
      @rs = @r.response_set
      @dc = Factory(:dependency_condition, :question => @a.question, :answer => @a, :operator => "==", :rule_key => "D")
      @dc.as(:answer).should == @r.as(:answer)
    end

    it "with checkbox/radio type response" do
      @dc.to_hash(@rs).should == {:D => true}
      @dc.answer = @b
      @dc.to_hash(@rs).should == {:D => false}
    end

    it "with string value response" do
      @a.update_attributes(:response_class => "string")
      @r.update_attributes(:string_value => "hello123")
      @dc.string_value = "hello123"
      @dc.to_hash(@rs).should == {:D => true}
      @r.update_attributes(:string_value => "foo_abc")
      @dc.to_hash(@rs).should == {:D => false}
    end

    it "with a text value response" do
      @a.update_attributes(:response_class => "text")
      @r.update_attributes(:text_value => "hello this is some text for comparison")
      @dc.text_value = "hello this is some text for comparison"
      @dc.to_hash(@rs).should == {:D => true}
      @r.update_attributes(:text_value => "Not the same text")
      @dc.to_hash(@rs).should == {:D => false}
    end

    it "with an integer value response" do
      @a.update_attributes(:response_class => "integer")
      @r.update_attributes(:integer_value => 10045)
      @dc.integer_value = 10045
      @dc.to_hash(@rs).should == {:D => true}
      @r.update_attributes(:integer_value => 421)
      @dc.to_hash(@rs).should == {:D => false}
    end

    it "with a float value response" do
      @a.update_attributes(:response_class => "float")
      @r.update_attributes(:float_value => 121.1)
      @dc.float_value = 121.1
      @dc.to_hash(@rs).should == {:D => true}
      @r.update_attributes(:float_value => 130.123)
      @dc.to_hash(@rs).should == {:D => false}
    end
  end

  describe "evaluate '!=' operator" do
    before(:each) do
      @a = Factory(:answer)
      @b = Factory(:answer, :question => @a.question)
      @r = Factory(:response, :question => @a.question, :answer => @a)
      @rs = @r.response_set
      @dc = Factory(:dependency_condition, :question => @a.question, :answer => @a, :operator => "!=", :rule_key => "E")
      @dc.as(:answer).should == @r.as(:answer)
    end

    it "with checkbox/radio type response" do
      @dc.to_hash(@rs).should == {:E => false}
      @dc.answer_id = @a.id.to_i+1
      @dc.to_hash(@rs).should == {:E => true}
    end

    it "with string value response" do
      @a.update_attributes(:response_class => "string")
      @r.update_attributes(:string_value => "hello123")
      @dc.string_value = "hello123"
      @dc.to_hash(@rs).should == {:E => false}
      @r.update_attributes(:string_value => "foo_abc")
      @dc.to_hash(@rs).should == {:E => true}
    end

    it "with a text value response" do
      @a.update_attributes(:response_class => "text")
      @r.update_attributes(:text_value => "hello this is some text for comparison")
      @dc.text_value = "hello this is some text for comparison"
      @dc.to_hash(@rs).should == {:E => false}
      @r.update_attributes(:text_value => "Not the same text")
      @dc.to_hash(@rs).should == {:E => true}
    end

    it "with an integer value response" do
      @a.update_attributes(:response_class => "integer")
      @r.update_attributes(:integer_value => 10045)
      @dc.integer_value = 10045
      @dc.to_hash(@rs).should == {:E => false}
      @r.update_attributes(:integer_value => 421)
      @dc.to_hash(@rs).should == {:E => true}
    end

    it "with a float value response" do
      @a.update_attributes(:response_class => "float")
      @r.update_attributes(:float_value => 121.1)
      @dc.float_value = 121.1
      @dc.to_hash(@rs).should == {:E => false}
      @r.update_attributes(:float_value => 130.123)
      @dc.to_hash(@rs).should == {:E => true}
    end
  end

  describe "evaluate the '<' operator" do
    before(:each) do
      @a = Factory(:answer)
      @b = Factory(:answer, :question => @a.question)
      @r = Factory(:response, :question => @a.question, :answer => @a)
      @rs = @r.response_set
      @dc = Factory(:dependency_condition, :question => @a.question, :answer => @a, :operator => "<", :rule_key => "F")
      @dc.as(:answer).should == @r.as(:answer)
    end

    it "with an integer value response" do
      @a.update_attributes(:response_class => "integer")
      @r.update_attributes(:integer_value => 50)
      @dc.integer_value = 100
      @dc.to_hash(@rs).should == {:F => true}
      @r.update_attributes(:integer_value => 421)
      @dc.to_hash(@rs).should == {:F => false}
    end

    it "with a float value response" do
      @a.update_attributes(:response_class => "float")
      @r.update_attributes(:float_value => 5.1)
      @dc.float_value = 121.1
      @dc.to_hash(@rs).should == {:F => true}
      @r.update_attributes(:float_value => 130.123)
      @dc.to_hash(@rs).should == {:F => false}
    end
  end

  describe "evaluate the '<=' operator" do
    before(:each) do
      @a = Factory(:answer)
      @b = Factory(:answer, :question => @a.question)
      @r = Factory(:response, :question => @a.question, :answer => @a)
      @rs = @r.response_set
      @dc = Factory(:dependency_condition, :question => @a.question, :answer => @a, :operator => "<=", :rule_key => "G")
      @dc.as(:answer).should == @r.as(:answer)
    end

    it "with an integer value response" do
      @a.update_attributes(:response_class => "integer")
      @r.update_attributes(:integer_value => 50)
      @dc.integer_value = 100
      @dc.to_hash(@rs).should == {:G => true}
      @r.update_attributes(:integer_value => 100)
      @dc.to_hash(@rs).should == {:G => true}
      @r.update_attributes(:integer_value => 421)
      @dc.to_hash(@rs).should == {:G => false}
    end

    it "with a float value response" do
      @a.update_attributes(:response_class => "float")
      @r.update_attributes(:float_value => 5.1)
      @dc.float_value = 121.1
      @dc.to_hash(@rs).should == {:G => true}
      @r.update_attributes(:float_value => 121.1)
      @dc.to_hash(@rs).should == {:G => true}
      @r.update_attributes(:float_value => 130.123)
      @dc.to_hash(@rs).should == {:G => false}
    end

  end

  describe "evaluate the '>' operator" do
    before(:each) do
      @a = Factory(:answer)
      @b = Factory(:answer, :question => @a.question)
      @r = Factory(:response, :question => @a.question, :answer => @a)
      @rs = @r.response_set
      @dc = Factory(:dependency_condition, :question => @a.question, :answer => @a, :operator => ">", :rule_key => "H")
      @dc.as(:answer).should == @r.as(:answer)
    end

    it "with an integer value response" do
      @a.update_attributes(:response_class => "integer")
      @r.update_attributes(:integer_value => 50)
      @dc.integer_value = 100
      @dc.to_hash(@rs).should == {:H => false}
      @r.update_attributes(:integer_value => 421)
      @dc.to_hash(@rs).should == {:H => true}
    end

    it "with a float value response" do
      @a.update_attributes(:response_class => "float")
      @r.update_attributes(:float_value => 5.1)
      @dc.float_value = 121.1
      @dc.to_hash(@rs).should == {:H => false}
      @r.update_attributes(:float_value => 130.123)
      @dc.to_hash(@rs).should == {:H => true}
    end
  end

  describe "evaluate the '>=' operator" do
    before(:each) do
      @a = Factory(:answer)
      @b = Factory(:answer, :question => @a.question)
      @r = Factory(:response, :question => @a.question, :answer => @a)
      @rs = @r.response_set
      @dc = Factory(:dependency_condition, :question => @a.question, :answer => @a, :operator => ">=", :rule_key => "I")
      @dc.as(:answer).should == @r.as(:answer)
    end

    it "with an integer value response" do
      @a.update_attributes(:response_class => "integer")
      @r.update_attributes(:integer_value => 50)
      @dc.integer_value = 100
      @dc.to_hash(@rs).should == {:I => false}
      @r.update_attributes(:integer_value => 100)
      @dc.to_hash(@rs).should == {:I => true}
      @r.update_attributes(:integer_value => 421)
      @dc.to_hash(@rs).should == {:I => true}
    end

    it "with a float value response" do
      @a.update_attributes(:response_class => "float")
      @r.update_attributes(:float_value => 5.1)
      @dc.float_value = 121.1
      @dc.to_hash(@rs).should == {:I => false}
      @r.update_attributes(:float_value => 121.1)
      @dc.to_hash(@rs).should == {:I => true}
      @r.update_attributes(:float_value => 130.123)
      @dc.to_hash(@rs).should == {:I => true}
    end
  end

  describe "evaluating with response_class string" do
    it "should compare answer ids when the dependency condition string_value is nil" do
      @a = Factory(:answer, :response_class => "string")
      @b = Factory(:answer, :question => @a.question)
      @r = Factory(:response, :question => @a.question, :answer => @a, :string_value => "")
      @rs = @r.response_set
      @dc = Factory(:dependency_condition, :question => @a.question, :answer => @a, :operator => "==", :rule_key => "J")
      @dc.to_hash(@rs).should == {:J => true}
    end

    it "should compare strings when the dependency condition string_value is not nil, even if it is blank" do
      @a = Factory(:answer, :response_class => "string")
      @b = Factory(:answer, :question => @a.question)
      @r = Factory(:response, :question => @a.question, :answer => @a, :string_value => "foo")
      @rs = @r.response_set
      @dc = Factory(:dependency_condition, :question => @a.question, :answer => @a, :operator => "==", :rule_key => "K", :string_value => "foo")
      @dc.to_hash(@rs).should == {:K => true}

      @r.update_attributes(:string_value => "")
      @dc.string_value = ""
      @dc.to_hash(@rs).should == {:K => true}
    end
  end

  describe "evaluate 'count' operator" do
    before(:each) do
      @q = Factory(:question)
      @dc = DependencyCondition.new(:operator => "count>2", :rule_key => "M", :question => @q)
      @as = []
      3.times do
        @as << Factory(:answer, :question => @q, :response_class => "answer")
      end
      @rs = Factory(:response_set)
      @as.slice(0,2).each do |a|
        Factory(:response, :question => @q, :answer => a, :response_set => @rs)
      end
      @rs.save
    end

    it "with operator with >" do
      @dc.to_hash(@rs).should == {:M => false}
      Factory(:response, :question => @q, :answer => @as.last, :response_set => @rs)
      @rs.reload.responses.count.should == 3
      @dc.to_hash(@rs.reload).should == {:M => true}
    end

    it "with operator with <" do
      @dc.operator = "count<2"
      @dc.to_hash(@rs).should == {:M => false}
      @dc.operator = "count<3"
      @dc.to_hash(@rs).should == {:M => true}
    end

    it "with operator with <=" do
      @dc.operator = "count<=1"
      @dc.to_hash(@rs).should == {:M => false}
      @dc.operator = "count<=2"
      @dc.to_hash(@rs).should == {:M => true}
      @dc.operator = "count<=3"
      @dc.to_hash(@rs).should == {:M => true}
    end

    it "with operator with >=" do
      @dc.operator = "count>=1"
      @dc.to_hash(@rs).should == {:M => true}
      @dc.operator = "count>=2"
      @dc.to_hash(@rs).should == {:M => true}
      @dc.operator = "count>=3"
      @dc.to_hash(@rs).should == {:M => false}
    end

    it "with operator with !=" do
      @dc.operator = "count!=1"
      @dc.to_hash(@rs).should == {:M => true}
      @dc.operator = "count!=2"
      @dc.to_hash(@rs).should == {:M => false}
      @dc.operator = "count!=3"
      @dc.to_hash(@rs).should == {:M => true}
    end
  end

end


text:
// Functions to help with displaying the data that we collected Note that this
// assumes that there is an SVG tag called "chart" which is where we want to
// display our pie chart

// This function converts data from the format returned by our API, which is of the form:
// { key1: value1, key2: value2, ... keyn: valuen}
// for example:
// { "walk": "40", "drive": "10", "bike": 10, "bus": 30}
// However, NVD3 prefers the data to be in the format
// [{ "label: "walk", "value": "40"}, ...}]
// So we convert it before passing it on
// Note also that we might be able to do this through clever jiggering of the
// data in the x() and y() functions, but we need to see what format the data is in for that

var cfc = cfc || {};
cfc.display = cfc.display || {};

cfc.display.convert = function(data) {
  var result = [];
  for (var key in data) {
    if (data.hasOwnProperty(key)) {
      var currEntry = {}
      currEntry['key'] = key;
      currEntry['value'] = data[key];
      result.push(currEntry);
    }
  }
  return result;
}

cfc.display.convertAndDisplayHeatMap = function(data, weightLabel) {
  if ('weightedLoc' in data) {
    convertedData = cfc.display.convertWeightedHeatMap(data['weightedLoc'], weightLabel);
    cfc.display.displayWeightedHeatMap(convertedData);
  }
  if ('latlng' in data) {
    convertedData = cfc.display.convertHeatMapPoints(data['latlng']);
    cfc.display.displayHeatMap(convertedData);
  }
}

cfc.display.convertWeightedHeatMap = function(data, label) {
  retArray = [];
  for (var i = 0; i < data.length; i++) {
    entry = data[i];
    entryLoc = entry['loc'];
    latlng = new google.maps.LatLng(entryLoc[0], entryLoc[1]);
    weightedLoc = {
      location: latlng,
      weight: entry[label]
    };
    retArray.push(weightedLoc);
  }
  return retArray;
}

cfc.display.convertHeatMapPoints = function(data) {
  retArray = [];
  for (var i = 0; i < data.length; i++) {
    entry = data[i];
    // Points are in GeoJSON format, i.e. (lng, lat)
    latlng = new google.maps.LatLng(entry[1], entry[0]);
    retArray.push(latlng);
  }
  return retArray;
}

cfc.display.sortLabels = function(a,b) {
  if (b['key'] == a['key']) {
    return 0;
  } else if (b['key'] < a['key']) {
    return 1;
  } else {
    return -1;
  }
}

cfc.display.prepChart = function() {
  $("#chart").empty();
  $("#mapcanvas").hide();
  $("#chart").show();
}

cfc.display.prepMap = function() {
  $("#mapcanvas").show();
  $("#chart").hide();
}

cfc.display.displayWeightedHeatMap = function(data) {
  var map, pointarray, heatmap;
  var mapOptions = {
    zoom: 13,
    center: new google.maps.LatLng(37.872186, -122.257984),
    // mapTypeId: google.maps.MapTypeId.SATELLITE
  };
  map = new google.maps.Map(document.getElementById('mapcanvas'),
      mapOptions);
  var pointArray = new google.maps.MVCArray(data);
  heatmap = new google.maps.visualization.HeatmapLayer({
    data: pointArray
  });
  heatmap.setMap(map);
  heatmap.set('radius', 75);
  heatmap.set('opacity', 0.8);
}

cfc.display.displayHeatMap = function(data) {
  var map, pointarray, heatmap;
  var mapOptions = {
    zoom: 13,
    center: new google.maps.LatLng(37.872186, -122.257984),
    // mapTypeId: google.maps.MapTypeId.SATELLITE
  };
  map = new google.maps.Map(document.getElementById('mapcanvas'),
      mapOptions);
  var pointArray = new google.maps.MVCArray(data);
  heatmap = new google.maps.visualization.HeatmapLayer({
    data: pointArray
  });
  heatmap.setMap(map);
  heatmap.set('dissipating', true);
  heatmap.set('opacity', 1.0);
}

cfc.display.pieChart = function(data, title) {
  nv.addGraph(function() {
      var width = nv.utils.windowSize().width - 5,
          height = nv.utils.windowSize().height - 5;

      var chart = nv.models.pieChart()
          .x(function(d) { return d.key })
          .y(function(d) { return d.value })
          .width(width)
          .height(height)
          .showLabels(true);

      chart.legend
        .margin({top:0, right:0, bottom: 0, left: 0})
        .width(width)
        .height(10);

      d3.select("#chart")
          .append("svg")
          .datum(data)
          .transition().duration(1200)
          .attr('width', width)
          .attr('height', height)
          .call(chart);

      chart.dispatch.on('stateChange', function(e) { nv.log('New State:', JSON.stringify(e)); });
      return chart;
  });
}

cfc.display.multiBarChart = function(data) {
  var chart;

  nv.addGraph(function() {
    var width = nv.utils.windowSize().width - 5,
        height = nv.utils.windowSize().height - 100;

    chart = nv.models.multiBarChart()
        .x(function(d) { return d.key })
        .y(function(d) { return d.value })
        .width(width)
        .height(height)
        //.margin({top: 30, right: 20, bottom: 50, left: 175})
        //.showValues(true)
        //.tooltips(false)
        .staggerLabels(true)    //Too many bars and not enough room? Try staggering labels.
        .barColor(d3.scale.category20().range())
        .transitionDuration(250)
        .stacked(false)
        .staggerLabels(true)    //Too many bars and not enough room? Try staggering labels.
        .showControls(false);

    chart.legend
      .margin({top:0, right:0, bottom: 0, left: 0})
      .width(width)
      .height(10);

    chart.yAxis
        .tickFormat(d3.format(',2d'));

    d3.select('#chart')
        .append("svg")
        .datum(data)
        .attr('width', width)
        .attr('height', height)
        .call(chart);

    // nv.utils.windowResize(chart.update);
    chart.dispatch.on('stateChange', function(e) { nv.log('New State:', JSON.stringify(e)); });
    return chart;
  });
}

cfc.display.barChart = function(data, yAxisLabel) {

  nv.addGraph(function() {
    var width = nv.utils.windowSize().width - 10,
        height = nv.utils.windowSize().height - 150;

    var chart = nv.models.discreteBarChart()
        .x(function(d) { return d.key })    //Specify the data accessors.
        .y(function(d) { return d.value })
        .width(width)
        .height(height)
        .staggerLabels(true)    //Too many bars and not enough room? Try staggering labels.
        .tooltips(true)        //Don't show tooltips
        .showValues(true)       //...instead, show the bar value right on top of each bar.
        .transitionDuration(350)
        ;

    chart.yAxis
      .axisLabel(yAxisLabel)
      .axisLabelDistance(40);

    d3.select('#chart')
        .append("svg")
        .datum(data)
        .attr('width', width)
        .attr('height', height)
        .call(chart);

    nv.utils.windowResize(chart.update);
    return chart;
  });
}

cfc.display.bulletChart = function(data) {
    /*
    var width = nv.utils.windowSize().height - 5,
        height = 100;
    */

    var margin = {top: 10, right: 40, bottom: 10, left: 80};
    var width = 80,
        height = nv.utils.windowSize().height - 50 - margin.top - margin.bottom;

/*
    var chart = nv.models.bulletChart()
                  .width(width)
                  .height(height)

    var vis = d3.select("#chart")
                .append("svg")
                .data(data)
                .attr("class", "bullet nvd3")
                .attr("width", width)
                .attr("height", height);

    // var wrap = vis.selectAll("g.nv-wrap.nv-bullet");
    vis.attr("transform", "rotate(90)");
    console.log(vis, vis.attr("transform"))

    vis.transition().duration(1000).call(chart);
*/

    var chart = d3.bullet()
      .orient("bottom")
      .width(width)
      .height(height);

    var svg = d3.select("#chart")
        .append("svg")
        .data(data)
        .attr("class", "bullet")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
        .call(chart);

    var title = svg.append("g")
        .style("text-anchor", "end")
        .attr("transform", "translate(" + width + "," + (height + 20) + ")");

    title.append("text")
        .attr("class", "title")
        .text(function(d) { return d.title; });

    title.append("text")
        .attr("class", "subtitle")
        .attr("dy", "1em")
        .text(function(d) { return d.subtitle; });
}


text:
<?php

namespace DmMailer\Manager;

use DmMailer\Entity\Template as Entity;

/**
 * Class Template
 *
 * @package DmMailer\Manager
 *
 * @method \DmMailer\Form\TemplateForm getForm
 */
class Template extends Base
{
    /**
     * @param Entity $entity
     *
     * @return bool
     */
    public function handlePost(Entity $entity)
    {
        $form = $this->getForm();

        if ($this->request->isPost()) {
            $form->setData($this->request->getPost());

            if ($form->isValid()) {
                $entity->populate($form->getData());

                return $this->saveEntity($entity);
            }
        }

        $form->bind($entity);

        return false;
    }
}


text:
package anki

import (
	"testing"

	"github.com/flimzy/diff"
	"github.com/gopherjs/gopherjs/js"
)

func TestAnkiBasicConvertQueryJS(t *testing.T) {
	expected := &basicQuery{
		Submit:       "foo",
		TypedAnswers: map[string]string{"foo": "bar"},
	}
	query := js.Global.Get("Object").New()
	query.Set("type:foo", "bar")
	query.Set("ignore", "baz")
	query.Set("submit", "foo")
	result := convertQuery(query)
	if d := diff.Interface(expected, result); d != nil {
		t.Error(d)
	}
}


text:
using System;
using System.Xml.Serialization;
using ZuoraMagic.ORM.BaseRequestTemplates;

namespace ZuoraMagic.SoapApi.RequestTemplates
{
    [Serializable]
    public class LoginRequestTemplate
    {
        public LoginRequestTemplate()
        {
        }

        public LoginRequestTemplate(string username, string password)
        {
            Username = username;
            Password = password;
        }

        [XmlElement("username", Namespace = ZuoraNamespaces.Request)]
        public string Username { get; set; }

        [XmlElement("password", Namespace = ZuoraNamespaces.Request)]
        public string Password { get; set; }
    }
}


text:
@interface RZCrossFadAnimationController : NSObject <RZAnimationControllerProtocol>

@end


text:
package controllers;

import models.User;
import play.Logger;
import play.libs.F;
import play.libs.F.Promise;
import play.mvc.Action;
import play.mvc.Http.Context;
import play.mvc.Result;
import play.mvc.Http.HeaderNames;
import uk.bl.api.PasswordHash;
import uk.bl.api.Base64;

public class SecuredAction extends Action.Simple {

	@Override
	public Promise<Result> call(Context ctx) throws Throwable {

    	String[] authorization = ctx.request().headers().get(HeaderNames.AUTHORIZATION);

    	if (authorization == null) {
    		return F.Promise.pure((Result) unauthorized("unauthorized"));
    	}
    	String auth = authorization[0].substring(6);
    	Logger.trace("SecuredAction auth: " + auth);

        final byte[] decodedAuth = Base64.decode(auth);
        final String[] credentials = new String(decodedAuth, "UTF-8").split(":");

        if (credentials == null || credentials.length != 2) {
    		return F.Promise.pure((Result) unauthorized("unauthorized"));
        }

        String email = credentials[0];
        String password = credentials[1];

		Logger.trace("SecuredAction credentials: "+email+" "+password);

		if( Logger.isTraceEnabled() ){
			for( User u : User.findAll() ) {
				Logger.info("U: "+u);
			}
		}

        User user = User.findByEmail(email.toLowerCase());
		String userPassword = null;
		if( user != null ) userPassword = user.password;
		// And is the PW okay?
		boolean result = false;
		if( userPassword != null ) {
			result = PasswordHash.validatePassword(password, userPassword);
		}

		Logger.trace("SecuredAction result: " + result);
		if (result) {
            ctx.request().setUsername(user.email);
			return delegate.call(ctx);
		}
		return F.Promise.pure((Result) unauthorized("unauthorized"));
	}
}


text:
<!DOCTYPE html>

<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
<title>Samuel 9 (ASV)</title>
<link href="../../../build/mobile.css" rel="stylesheet" />

American Standard VersionSamuel 9<
=
>

9

1 And David said, Is there yet any that is left of the house of Saul, that I may show him kindness for Jonathan's sake?
2 And there was of the house of Saul a servant whose name was Ziba, and they called him unto David; and the king said unto him, Art thou Ziba? And he said, Thy servant is he.
3 And the king said, Is there not yet any of the house of Saul, that I may show the kindness of God unto him? And Ziba said unto the king, Jonathan hath yet a son, who is lame of his feet.
4 And the king said unto him, Where is he? And Ziba said unto the king, Behold, he is in the house of Machir the son of Ammiel, in Lo-debar.
5 Then king David sent, and fetched him out of the house of Machir the son of Ammiel, from Lo-debar.
6 And Mephibosheth, the son of Jonathan, the son of Saul, came unto David, and fell on his face, and did obeisance. And David said, Mephibosheth. And he answered, Behold, thy servant!
7 And David said unto him, Fear not; for I will surely show thee kindness for Jonathan thy father's sake, and will restore thee all the land of Saul thy father; and thou shalt eat bread at my table continually.
8 And he did obeisance, and said, What is thy servant, that thou shouldest look upon such a dead dog as I am?

9 Then the king called to Ziba, Saul's servant, and said unto him, All that pertained to Saul and to all his house have I given unto thy master's son.
10 And thou shalt till the land for him, thou, and thy sons, and thy servants; and thou shalt bring in the fruits, that thy master's son may have bread to eat: but Mephibosheth thy master's son shall eat bread alway at my table. Now Ziba had fifteen sons and twenty servants.
11 Then said Ziba unto the king, According to all that my lord the king commandeth his servant, so shall thy servant do. As for Mephibosheth, said the king, he shall eat at my table, as one of the king's sons.
12 And Mephibosheth had a young son, whose name was Mica. And all that dwelt in the house of Ziba were servants unto Mephibosheth.
13 So Mephibosheth dwelt in Jerusalem; for he did eat continually at the king's table. And he was lame in both his feet.

<
=
>


text:
package goesl

import (
	"github.com/op/go-logging"
	"os"
)

var (
	log = logging.MustGetLogger("goes")

	// Example format string. Everything except the message has a custom color
	// which is dependent on the log level. Many fields have a custom output
	// formatting too, eg. the time returns the hour down to the milli second.
	format = logging.MustStringFormatter(
		"%{color}%{time:15:04:05.000} %{shortfunc} ▶ %{level:.8s}%{color:reset} %{message}",
	)
)

func Debug(message string, args ...interface{}) {
	log.Debug(message, args...)
}

func Error(message string, args ...interface{}) {
	log.Error(message, args...)
}

func Notice(message string, args ...interface{}) {
	log.Notice(message, args...)
}

func Info(message string, args ...interface{}) {
	log.Info(message, args...)
}

func Warning(message string, args ...interface{}) {
	log.Warning(message, args...)
}

func init() {
	backend := logging.NewLogBackend(os.Stderr, "", 0)
	formatter := logging.NewBackendFormatter(backend, format)
	logging.SetBackend(formatter)
}


text:
import type { ActionType as AuthAction } from './auth/actions';
import type { ActionType as BoardsAction } from './boards/actions';
import type { ActionType as CardListsAction } from './cardLists/actions';
import type { ActionType as CardsAction } from './cards/actions';
import type { ActionType as CommonAction } from './common/actions';
import type { ActionType as ProjectsAction } from './projects/actions';
import type { ActionType as QualityIndicatorsAction } from './qualityIndicators/actions';
import type { ActionType as SprintsAction } from './sprints/actions';
import type { ActionType as SyncAction } from './sync/actions';
import type { ActionType as TipsAction } from './tips/actions';
import type { ActionType as UsersAction } from './users/actions';

export type ActionType =
  | AuthAction
  | BoardsAction
  | CardListsAction
  | CardsAction
  | CommonAction
  | ProjectsAction
  | QualityIndicatorsAction
  | SprintsAction
  | SyncAction
  | TipsAction
  | UsersAction;


text:
slug: kisui-berlin
name: Kisui Berlin
---


text:
Meteor.startup(function(){

  Meteor.methods({
    addFalseHourlyRecords: function(sensor_id, maxRange, minRange){
      for(var i = 0; i < 30; i++){
        HourlyAverage.insert({
          sensor_id: sensor_id,
          time: moment().startOf('hour').subtract(i, 'hours').valueOf(),
          value: minRange + (((maxRange - minRange) / 30) * i)
        });
      }
    }
  })
});


text:
from django.contrib.auth.models import User, AnonymousUser
from django.core.urlresolvers import reverse
from django.db import DatabaseError
import json
from mock import patch
from rest_framework.test import APIClient
from django.test import TestCase, Client

class BuildDetailsAPITestCase(TestCase):

    def setUp(self):
        self.c = Client()
        self.build = Build.record(1, 'project', 'repo', [], [])
        url = reverse("build-detail", args = (self.build.pk,))
        self.response = self.c.get(url)

    def test_retrieve_build_200_ok(self):

        assert self.response.status_code == 200

    def test_has_expected_fields(self):

        expected_fields = ['build_number', 'repo', 'metrics', 'booleans']

        for field in expected_fields:
            data = self.response.json()
            assert data.get(field, None) is not None, \
                'Expected {} to exist. Actual result: {}' . format (field, data)

class ListBuildsTestCase(TestCase):

    def setUp(self):
        self.c = Client()

    def list_builds(self):
        url = reverse("build-list")
        response = self.c.post(url)

        assert response.status_code == 200, \
            'Expected 200OK. Got: {}' . format (response.content)

class SuccessfullyCreateNewBuildTestCase(TestCase):

    def setUp(self):
        self.c = Client()
        self.repo_name = "UserService"
        self.project_name = "Tangent MicroServices"
        data = {
            "build_number": 1,
            "repo": {
                "name": self.repo_name,
                "project": {
                    "name": self.project_name
                }
            },
            "metrics": [{
                "key": "remediation",
                "value": "100",
                "type": "default"
            },
            {
                "key": "issues",
                "value": "10",
                "type": "default"
            }],
            "booleans": [{
                "key": "build_passed",
                "value": True
            }]
        }
        url = reverse("build-list")
        self.response = self.c.post(url, data=json.dumps(data), content_type='application/json')

        self.build = Build.objects.get(build_number=1)

    def test_response_is_201_created(self):
        assert self.response.status_code == 201

    def test_create_build_creates_repository(self):

        assert self.build.repo.name == self.repo_name

    def test_create_build_creates_project(self):

        assert self.build.repo.project.name == self.project_name

    def test_metrics_are_recorded(self):

        assert self.build.metrics.count() == 2

    def test_creates_booleans(self):
        bool_count = self.build.booleans.count()
        assert bool_count == 1, \
            'Expected 1 boolean. Got: {}' . format (bool_count)

from api.models import Project, Repo, Build

class ProjectModelTestCase(TestCase):

    def test_quick_create(self):
        assert Project.objects.count() == 0
        project = Project.quick_create()

        assert Project.objects.count() == 1
        assert project.__str__() == 'Some Project'

class BuildModelTestCase(TestCase):

    def test_unicode(self):

        build = Build.record(1, 'sample-project', 'sample-repo')
        print(build)

    def test_build_record(self):

        metrics = [
            ("metric.coverage", 78),
            ("metric.loc", 1234),
            ("metric.static_analysis_issues", 1),
        ]
        booleans = [
            ("boolean.build_status", True),
            ("boolean.tests_run", False),
            ("boolean.tests_passed", True),
            ("boolean.codeclimate_run", False),
        ]

        build = Build.record(1, 'sample-project', 'sample-repo', metrics, booleans)

        assert build.build_number == 1

        assert len(Project.objects.filter(name='sample-project')) == 1, \
            'Expect a new project to have been created'
        assert len(Repo.objects.filter(name='sample-repo')) == 1, \
            'Expect a new repo to have been created'

from api.serializers import MetricSerializer, BuildSerializer

class BuildSerializerTestCase(TestCase):
    pass

class HealthTestCase(TestCase):
    def setUp(self):
        self.c = APIClient()
        self.status_fields = ['db', 'status']

    def test_health_endpoint_ok(self):
        url = reverse('health-list')
        response = self.c.get(url)
        assert response.status_code == 200, \
            "Expect 200 OK. got: {}" . format (response.status_code)

        expected_fields = ["db", "status"]

        for field in self.status_fields:
            assert response.json().get("status", {}).get(field, None) == "up", \
                "Expected field {} to exist" . format (field)

    @patch.object(User.objects, 'first')
    def test_determine_db_status(self, mock_query):
        """Health should not be ok if it cannot connect to the db"""

        mock_query.side_effect = DatabaseError()
        url = reverse('health-list')
        response = self.c.get(url)

        status = response.json().get("status", {})
        db_status = status.get('db')
        assert db_status == 'down', \
            'Expect DB to be down. Got: {}' . format (db_status)

        status = status.get('status')
        assert status == 'down', \
            'Expect status to be down. Got: {}' . format (status)


text:
package com.asksunny.schema;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Schema extends HashMap<String, Entity> {

	public static final Schema EMPTY_SCHEMA = new Schema();

	public Schema() {
		super();
	}

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Schema(String name) {
		super();
		this.name = name;
	}

	public Entity addEntity(Entity arg0) {
		return put(arg0.getName(), arg0);
	}

	public List<Entity> getAllEntities() {
		List<Entity> entities = new ArrayList<Entity>(this.values());
		Collections.sort(entities, new EntityOrderComparator());
		return entities;
	}

	@Override
	public Entity get(Object arg0) {
		return super.get(arg0.toString().toUpperCase());
	}

	@Override
	public Entity put(String arg0, Entity arg1) {
		return super.put(arg0.toUpperCase(), arg1);
	}

	@Override
	public void putAll(Map<? extends String, ? extends Entity> arg0) {
		Set<? extends String> keys = arg0.keySet();
		for (String string : keys) {
			super.put(string.toUpperCase(), arg0.get(string));
		}
	}

	/**
	 * We start with all independent entities that does reference other entity
	 * (foreign key relationship)
	 *
	 * @return
	 */
	public List<Entity> getIndependentEntities() {
		List<Entity> entities = new ArrayList<Entity>();
		for (Iterator<Entity> iterator = this.values().iterator(); iterator.hasNext();) {
			Entity entity = iterator.next();
			if (!entity.hasReference()) {
				entities.add(entity);
			}
		}
		return entities;
	}

	public void buildRelationship() {
		List<Entity> entities = new ArrayList<Entity>(this.values());
		for (Entity entity : entities) {
			List<Field> refColumns = entity.getAllReferences();
			if (refColumns != null && refColumns.size() > 0) {
				for (Field refField : refColumns) {
					Entity referenceEntity = null;
					if (refField.getContainer().getFields() == null
							|| refField.getContainer().getFields().size() == 0) {
						referenceEntity = this.get(refField.getContainer().getName());
						refField.setContainer(referenceEntity);
					} else {
						referenceEntity = refField.getContainer();
					}
				}

			}

		}

	}

}


text:
<?php

	require_once('../config.php');

	if ((int)$_SERVER['CONTENT_LENGTH'] > $max_file_size_in_bytes) {
	    header("HTTP/1.1 500 Internal Server Error"); // This will trigger an uploadError event in SWFUpload
	    HandleError("POST exceeded maximum allowed size.");
	    exit(0);
	}

	// Settings
	$save_path = DOCUMENTROOT . rawurldecode($_POST["uploadpath"]); //The path were we will save the file (getcwd() may not be reliable and should be tested in your environment)

	$upload_name = "Filedata";

	// Other variables
	$MAX_FILENAME_LENGTH = 260;
	$file_name = "";
	$file_extension = "";
	$uploadErrors = array(
        0=>"There is no error, the file uploaded with success",
        1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
        2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
        3=>"The uploaded file was only partially uploaded",
        4=>"No file was uploaded",
        6=>"Missing a temporary folder"
	);

	// Validate the upload
	if (!isset($_FILES[$upload_name])) {
		HandleError("No upload found in \$_FILES for " . $upload_name);
		exit(0);
	} else if (isset($_FILES[$upload_name]["error"]) && $_FILES[$upload_name]["error"] != 0) {
		HandleError($uploadErrors[$_FILES[$upload_name]["error"]]);
		exit(0);
	} else if (!isset($_FILES[$upload_name]["tmp_name"]) || !@is_uploaded_file($_FILES[$upload_name]["tmp_name"])) {
		HandleError("Upload failed is_uploaded_file test.");
		exit(0);
	} else if (!isset($_FILES[$upload_name]['name'])) {
		HandleError("File has no name.");
		exit(0);
	}

	// Validate the file size (Warning: the largest files supported by this code is 2GB)
	$file_size = @filesize($_FILES[$upload_name]["tmp_name"]);
	if (!$file_size || $file_size > $max_file_size_in_bytes) {
		HandleError("File exceeds the maximum allowed size");
		exit(0);
	}

	if ($file_size <= 0) {
		HandleError("File size outside allowed lower bound");
		exit(0);
	}

	// Validate file name (for our purposes we'll just remove invalid characters)
	$file_name = preg_replace('/[^'.$valid_chars_regex.']|\.+$/i', "", basename($_FILES[$upload_name]['name']));
	if (strlen($file_name) == 0 || strlen($file_name) > $MAX_FILENAME_LENGTH) {
		HandleError("Invalid file name");
		exit(0);
	}

	// Validate that we won't over-write an existing file
	if (file_exists($save_path . $file_name)) {
		HandleError("File with this name already exists");
		exit(0);
	}

	// Validate file extension
	$path_info = pathinfo($_FILES[$upload_name]['name']);
	$file_extension = $path_info["extension"];

	$is_valid_extension = false;
	$allowedExtensions = explode(',', $extension_whitelist);

	foreach ($allowedExtensions as $extension) {
		if (strcasecmp($file_extension, str_replace(' ', '', $extension)) == 0) {
			$is_valid_extension = true;
			break;
		}
	}

	if (!$is_valid_extension) {
		HandleError("Invalid file extension");
		exit(0);
	}

	// Validate file contents (extension and mime-type can't be trusted)
	/*
		Validating the file contents is OS and web server configuration dependant.  Also, it may not be reliable.
		See the comments on this page: http://us2.php.net/fileinfo

		Also see http://72.14.253.104/search?q=cache:3YGZfcnKDrYJ:www.scanit.be/uploads/php-file-upload.pdf+php+file+command&hl=en&ct=clnk&cd=8&gl=us&client=firefox-a
		 which describes how a PHP script can be embedded within a GIF image file.

		Therefore, no sample code will be provided here.  Research the issue, decide how much security is
		 needed, and implement a solution that meets the needs.
	*/

	// Process the file
	/*
		At this point we are ready to process the valid file. This sample code shows how to save the file. Other tasks
		 could be done such as creating an entry in a database or generating a thumbnail.

		Depending on your server OS and needs you may need to set the Security Permissions on the file after it has
		been saved.
	*/
	if (!@move_uploaded_file($_FILES[$upload_name]["tmp_name"], $save_path.$file_name)) {
		HandleError("File could not be saved.");
		exit(0);
	}

	exit(0);

/* Handles the error output. This error message will be sent to the uploadSuccess event handler.  The event handler
will have to check for any error messages and react as needed. */
function HandleError($message) {
	echo $message;
}
?>


text:
'use strict';

/**
 * Keys where we send our local storage values to
 */
var seenItKey = 'seen-it-ndpkdkckdhfanagkhmjicjhdlmfaacmb';
var skipsKey = seenItKey + '-skips';
var storeKey = seenItKey + '-storing';

/**
 * Handler for messages passed to background.js
 * @param  {Object} msg           The message payload object passed
 * @param  {[type]} sender        Who the message is coming from
 * @param  {[type]} sendResponse) Chrome's sendResponse param
 */
chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
  switch (msg.action) {
    case 'enableSkips':
      onEnableSkips();
      break;
    case 'disableSkips':
      onDisableSkips();
      break;
    case 'enableStoring':
      onEnableStoring();
      break;
    case 'disableStoring':
      onDisableStoring();
      break;
    case 'clearSkips':
      onClearSkips();
      break;
    case 'log':
      onLog(msg.log);
      break;
    default:
      console.warn('Unrecognized message: ' + msg.action);
  }
});

/**
 * Checks if the tab is on Imgur to decide whether to load the page action
 * @param  {String} tabId      chrome.tabs.onUpdate's tabId param
 * @param  {Object} changeInfo chrome.tabs.onUpdate's changeInfo param
 * @param  {Object} tab        chrome.tabs.onUpdate's tab param
 */
function checkForImgurUrl(tabId, changeInfo, tab) {
  if (changeInfo.status === 'complete') {
    if (tab.url.indexOf('http://imgur.com') === 0) {
      chrome.pageAction.show(tabId);
      processUrl(tab.url);
    } else {
      chrome.pageAction.hide(tabId);
    }
  }
}

/**
 * Handles logic for what to do with the current image URL
 * @param  {String} url The current URL of the Imgur page
 */
function processUrl(url) {
  // Don't process the URL if it isn't a gallery link
  // Gallery links are in the form '*/gallery/imageId'
  if (url.indexOf('gallery') === -1) {
    return;
  }

  // Get the image's ID from the URL
  var idStart = url.lastIndexOf('/') + 1;
  var imageId = url.substring(idStart);
  var images = getImageObj();

  // Store the image if it hasn't been seen and storing is enabled
  if (!images[imageId]) {
    if (storingIsEnabled()) {
      console.log('storing image: ' + imageId);
      images[imageId] = Date.now();
      localStorage.setItem(seenItKey, JSON.stringify(images));
    }
  }
  // Otherwise skip the image if it has been seen and skipping is enabled
  else if (skippingIsEnabled()) {
    console.log('skipping image: ' + imageId);
    skipImage();
  }
}

/**
 * Passes a message to the content script to skip the image
 */
function skipImage() {
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {
      action: 'skip',
      history: getImageObj()
    }, function(response) {
      // put response from message here if needed
    });
  });
}

/**
 * Helper function to get the object of imageIds saved in local storage
 * @return {Object} Object with imageIds as fields and unix timstamps as values
 */
function getImageObj() {
  var imageString = localStorage.getItem(seenItKey);
  return imageString ? JSON.parse(imageString) : {};
}

function storingIsEnabled() {
  return localStorage.getItem(storeKey) === 'true';
}

function skippingIsEnabled() {
  return localStorage.getItem(skipsKey) === 'true';
}

/**
 * Enables skipping images
 */
function onEnableSkips() {
  console.log('enable skips');
  localStorage.setItem(skipsKey, 'true');
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    processUrl(tabs[0].url);
  });
}

/**
 * Disables skipping images
 */
function onDisableSkips() {
  console.log('disable skips');
  localStorage.setItem(skipsKey, 'false');
}

/**
 * Enables storing images that are being seen
 */
function onEnableStoring() {
  console.log('enable storing');
  localStorage.setItem(storeKey, 'true');
}

/**
 * Disables storing images that are being seen
 */
function onDisableStoring() {
  console.log('disable storing');
  localStorage.setItem(storeKey, 'false');
}

/**
 * Clears all images currently stored in local storage
 */
function onClearSkips() {
  console.log('clear skips');
  localStorage.removeItem(seenItKey);
}

/**
 * Helper function to log out statements. Other files can pass background.js a
 * message with `type: log` and `log: thingToLog`
 * @param  {Any} log The content to log
 */
function onLog(log) {
  console.log(log);
}

function init() {
  var skipsEnabled = localStorage.getItem(skipsKey);
  var storeEnabled = localStorage.getItem(storeKey);
  if (skipsEnabled === null) {
    localStorage.setItem(skipsKey, 'true');
  }
  if (storeEnabled === null) {
    localStorage.setItem(storeKey, 'true');
  }
}

chrome.tabs.onUpdated.addListener(checkForImgurUrl);
init();


text:
<v1:xo version="1.0" xmlns:v1="http://buschmais.com/xo/schema/v1.0">
    <xo-unit name="traceProvider">
        <url>file:target/json/store</url>
        <provider>com.buschmais.xo.test.trace.api.TraceDatastoreProvider</provider>
        <types>
            <type>com.buschmais.xo.test.trace.test.bootstrap.composite.A</type>
        </types>
        <properties>
            <property name="com.buschmais.xo.test.trace.api.DelegateProvider" value="com.buschmais.xo.json.api.JsonFileStoreProvider"/>
        </properties>
    </xo-unit>
</v1:xo>


text:
package org.apache.ignite.cache;

import java.io.Serializable;
import javax.cache.event.CacheEntryEventFilter;

/**
 * This filter adds {@link Serializable} interface to {@link javax.cache.event.CacheEntryEventFilter} object.
 */
public interface CacheEntryEventSerializableFilter<K, V> extends CacheEntryEventFilter<K, V>, Serializable {
    // No-op.
}


text:
<?php

namespace App\Services\FixtureLoader;

use App\Entity\State;
use App\Services\DataProviderInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Output\OutputInterface;

class StateFixtureLoader extends AbstractFixtureLoader implements FixtureLoaderInterface
{
    public function __construct(EntityManagerInterface $entityManager, DataProviderInterface $dataProvider)
    {
        parent::__construct($entityManager, $dataProvider);
    }

    protected function getEntityClass(): string
    {
        return State::class;
    }

    public function load(?OutputInterface $output = null): void
    {
        if ($output) {
            $output->writeln('Migrating states ...');
        }

        $currentEntity = '';

        foreach ($this->data as $name) {
            $entity = explode('-', $name, 2)[0];

            if ($currentEntity !== $entity) {
                $currentEntity = $entity;

                if ($output) {
                    $output->writeln([
                        '',
                        $currentEntity,
                    ]);
                }
            }

            if ($output) {
                $output->write("  " . '<comment>' . $name . '</comment> ...');
            }

            $entity = $this->repository->findOneBy([
                'name' => $name,
            ]);

            if (!$entity) {
                if ($output) {
                    $output->write(' <fg=cyan>creating</>');
                }

                $entity = State::create($name);
                $this->entityManager->persist($entity);
                $this->entityManager->flush();
            }

            if ($output) {
                $output->writeln(' <info>✓</info>');
            }
        }

        if ($output) {
            $output->writeln('');
        }
    }
}


text:
The default constructor.

```csharp
public Builder()
```

## See Also

* class [Builder<TRequest,TResponse>](../HttpMethodMapping-2.Builder-2.md)
* namespace [Facility.Core.Http](../../Facility.Core.md)

<!-- DO NOT EDIT: generated by xmldocmd for Facility.Core.dll -->


text:
FactoryGirl.define do
  factory :delegation do
    issue
    truster { FactoryGirl.create :member }
    trustee { FactoryGirl.create :member }
  end
end