text:
<?php
namespace Lead\Net\Mime;

use InvalidArgumentException;
use Lead\Set\Set;

/**
 * MIME-compliant email messages class.
 */
class Message
{
    /**
     * Class dependencies.
     *
     * @var array
     */
    protected $_classes = [];

    /**
     * MIME protocol version number
     *
     * @var string
     */
    protected $_version = '1.0';

    /**
     * The client hostname.
     *
     * @var string
     */
    protected $_client = 'localhost.localdomain';

    /**
     * The word wrap.
     *
     * @var boolean
     */
    protected $_wordWrap = true;

    /**
     * Multipart inlines attachment
     *
     * @var array
     */
    protected $_inlines = [];

    /**
     * Multipart attachments
     *
     * @var array
     */
    protected $_attachments = [];

    /**
     * Alt body message
     *
     * @var string
     */
    protected $_altBody = null;

    /**
     * From email
     *
     * @var string
     */
    protected $_from = null;

    /**
     * Return Path email
     *
     * @var string
     */
    protected $_returnPath = null;

    /**
     * Return Path email
     *
     * @var array
     */
    protected $_recipients = null;

    /**
     * Adds config values to the public properties when a new object is created.
     *
     * @param array $config Configuration options. Possible values are:
     *                      - `'version'`  _string_ : MIME version (defaults `'1.0'`).
     *                      - `'classes'`  _array_  : class dependencies.
     */
    public function __construct($config = [])
    {
        $defaults = [
            'version'   => '1.0',
            'client'    => 'localhost.localdomain',
            'mime'      => null,
            'charset'   => null,
            'body'      => '',
            'altBody'   => '',
            'headers'   => [],
            'classes'   => [
                'address'   => 'Lead\Net\Mime\Address',
                'addresses' => 'Lead\Net\Mime\Header\Addresses'
            ]
        ];
        $config = Set::merge($defaults, $config);

        $this->_classes = $config['classes'];

        $addresses = $this->_classes['addresses'];
        $this->_recipients = new $addresses();

        $this->body($config['body']);
        $this->altBody($config['body']);

        $this->_stream = new MixedPart(['headers' => $config['headers']]);

        $this->version($config['version']);
        $this->client($config['client']);
    }

    /**
     * Gets/sets the MIME protocol version number.
     *
     * @param  string      The version number.
     * @return string|self
     */
    public function version($version = null)
    {
        if (func_num_args() === 0) {
            return $this->_version;
        }
        $headers = $this->headers();
        $headers->prepend('MIME-Version', $version);
        $this->_version = $version;
        return $this;
    }

    /**
     * Get/set the client hostname.
     *
     * @param  string      $client The client hostname
     * @return string|self
     */
    public function client($client = null)
    {
        if (!func_num_args()) {
            return $this->_client;
        }
        $this->_client = $client;
        return $this;
    }

    /**
     * Get/set the headers instance
     *
     * @param  string $headers The headers instance
     * @return string
     */
    public function headers($headers = null)
    {
        if (!func_num_args()) {
            return $this->_stream->headers();
        }
        $this->_stream->headers($headers);
        return $this;
    }

    /**
     * Get/set the mime.
     *
     * @param  string $mime
     * @return string           The mime.
     */
    public function mime($mime = null)
    {
        if (!func_num_args()) {
            return $this->_stream->mime();
        }
        $this->_stream->mime($mime);
        return $this;
    }

    /**
     * Get/set the charset.
     *
     * @param  string $charset
     * @return string           The charset.
     */
    public function charset($charset = null)
    {
        if (!func_num_args()) {
            return $this->_stream->charset();
        }
        $this->_stream->charset($charset);
        return $this;
    }

    /**
     * Get/set the encoding.
     *
     * @param  string $encoding
     * @return string           The encoding.
     */
    public function encoding($encoding = null)
    {
        if (!func_num_args()) {
            return $this->_stream->encoding();
        }
        $this->_stream->encoding($encoding);
        return $this;
    }

    /**
     * Get/set email priority.
     *
     * @param  integer $priority.
     * @return mixed
     */
    public function priority($priority = null)
    {
        $headers = $this->headers();
        if (!func_num_args()) {
            return $headers['X-Priority'];
        }
        $headers['X-Priority'] = (string) $priority;
        return $this;
    }

    /**
     * Get/set the word wrap mode.
     *
     * @param  boolean      $wordWrap Enabling or not the word wrapping
     * @return boolean|self
     */
    public function wordWrap($wordWrap = null)
    {
        if (!func_num_args()) {
            return $this->_wordWrap;
        }
        $this->_wordWrap = !!$wordWrap;
        return $this;
    }

    /**
     * Get/Set the sender email.
     *
     * @param  string $address The sender email address.
     * @param  mixed  $name    The sender name.
     * @return self
     */
    public function from($address = null, $name = null)
    {
        if (!func_num_args()) {
            return $this->_from;
        }
        $class = $this->_classes['address'];
        $this->_from = new $class($address, $name);

        $headers = $this->headers();
        $headers['From'] = $this->_from->toString();
        return $this;
    }

    /**
     * Get/Set the subject of the message.
     *
     * @param  string $subject The subject.
     * @return self
     */
    public function subject($subject = null)
    {
        $headers = $this->headers();
        if (!func_num_args()) {
            return $headers['Subject'];
        }
        $headers['Subject'] = Mime::encodeValue($subject, 998, "\r\n ");
        return $this;
    }

    /**
     * Get/set the Return-Path header of the message.
     *
     * @param  string $returnPath The sender email address.
     * @return mixed
     */
    public function returnPath($returnPath = null)
    {
        if (!func_num_args()) {
            return $this->_returnPath;
        }
        $this->_returnPath = $returnPath;
        $headers = $this->headers();
        $headers['Return-Path'] = '<' . Mime::encodeEmail($returnPath) .'>';
        return $this;
    }

    /**
     * Add a reply-to address.
     *
     * @param  string $address The email address.
     * @param  mixed  $name    The name.
     * @return self
     */
    public function addReplyTo($address, $name = null)
    {
        $this->_addRecipient('Reply-To', $address, $name);
        return $this;
    }

    /**
     * Add an email recipient.
     *
     * @param  string $address The email address.
     * @param  mixed  $name    The name.
     * @return self
     */
    public function addTo($address, $name = null)
    {
        $address = $this->_addRecipient('To', $address, $name);
        $this->_recipients[$address->email()] = $address;
        return $this;
    }

    /**
     * Adds carbon copy email recipient.
     *
     * @param  string $address The email address.
     * @param  mixed  $name    The name.
     * @return self
     */
    public function addCc($address, $name = null)
    {
        $address = $this->_addRecipient('Cc', $address, $name);
        $this->_recipients[$address->email()] = $address;
        return $this;
    }

    /**
     * Adds blind carbon copy email recipient.
     *
     * @param  string $address The sender email address.
     * @param  mixed  $name    The sender name.
     * @return self
     */
    public function addBcc($address, $name = null)
    {
        $class = $this->_classes['address'];
        $bcc = new $class($address, $name);
        $this->_recipients[$bcc->email()] = $bcc;
        return $this;
    }

    /**
     * Add a recipient to a specific type section.
     *
     * @param  string $type    The type of recipient.
     * @param  string $address The email address.
     * @param  mixed  $name    The name.
     * @return objedt          The created address.
     */
    protected function _addRecipient($type, $address, $name = null)
    {
        $classes = $this->_classes;
        $headers = $this->headers();
        if (!isset($headers[$type])) {
            $addresses = $classes['addresses'];
            $headers[$type] = new $addresses();
        }
        $class = $classes['address'];
        $value = new $class($address, $name);
        $headers[$type][] = $value;
        return $value;
    }

    /**
     * Return recipients
     *
     * @return array
     */
    public function recipients()
    {
        return $this->_recipients;
    }

    /**
     * Return inlines
     *
     * @return object
     */
    public function inlines()
    {
        return $this->_inlines;
    }

    /**
     * Return attachments
     *
     * @return object
     */
    public function attachments()
    {
        return $this->_attachments;
    }

    /**
     * Add an embedded file.
     */
    public function addInline($path, $name = null, $mime = true, $encoding = true)
    {
        $cid = static::generateId($this->client());
        $filename = basename($path);
        $this->_inlines[$path] = [
            'filename'    => $name ?: $filename,
            'disposition' => 'attachment',
            'mime'        => $mime,
            'headers'     => ['Content-ID: ' . $cid]
        ];
        return $cid;
    }

    /**
     * Add an attachment.
     */
    public function addAttachment($path, $name = null, $mime = true, $encoding = true)
    {
        $cid = static::generateId($this->client());
        $filename = basename($path);
        $this->_attachments[$path] = [
            'filename'    => $name ?: $filename,
            'disposition' => 'attachment',
            'mime'        => $mime,
            'headers'     => ['Content-ID: ' . $cid]
        ];
        return $cid;
    }

    /**
     * Get/set the alt body message.
     *
     * @param  string      $value.
     * @return string|self
     */
    public function body($value = null)
    {
        if (!func_num_args()) {
            return $this->_body;
        }
        $this->_body = (string) $value;
        return $this;
    }

    /**
     * Get/set the alt body message.
     *
     * @param  string      $value.
     * @return string|self
     */
    public function altBody($value = null)
    {
        if (!func_num_args()) {
            return $this->_altBody;
        }
        $this->_altBody = (string) $value;
        return $this;
    }

    /**
     * Set the HTML body message with an optionnal alternative body.
     *
     * @param  string      $body    The HTML body message.
     * @param  string      $altBody The alt body.
     * @return string|self
     */
    public function html($body, $basePath = null)
    {
        if (!func_num_args()) {
            return $this->_body;
        }

        if ($basePath) {
            $cids = [];
            $hasInline = preg_match_all('~
                (<img[^<>]*\s src\s*=\s*
                |<body[^<>]*\s background\s*=\s*
                |<[^<>]+\s style\s*=\s* ["\'][^"\'>]+[:\s] url\(
                |<style[^>]*>[^<]+ [:\s] url\()
                (["\']?)(?![a-z]+:|[/#])([^"\'>)\s]+)
                |\[\[ ([\w()+./@\\~-]+) \]\]
            ~ix', $body, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
            if ($hasInline) {

                foreach (array_reverse($matches) as $m) {
                    $file = rtrim($basePath, '/\\') . '/' . (isset($m[4]) ? $m[4][0] : urldecode($m[3][0]));
                    if (!isset($cids[$file])) {
                        $cids[$file] = substr($this->addInline($file), 1, -1);
                    }
                    $body = substr_replace($body, "{$m[1][0]}{$m[2][0]}cid:{$cids[$file]}", $m[0][1], strlen($m[0][0]));
                }
            }
        }

        $this->body($body);
        $this->mime('text/html');
        $this->charset(Mime::optimalCharset($body));

        $this->_altBody = static::stripTags($this->_body);
        return $this;
    }

    /**
     * Get message stream.
     *
     * @return object
     */
    public function stream()
    {
        return $this->_stream;
    }

    /**
     * Magic method to convert the instance into an HTTP message string.
     *
     * @return string
     */
    public function toMessage()
    {
        $message = clone $this;

        $altBody = $message->altBody();
        $attachments = $message->attachments();
        $inlines = $message->inlines();

        $root = $cursor = $message->stream();

        $body = $message->body();
        $bodyMime = $cursor->mime() ?: 'text/plain';
        $bodyCharset = $cursor->charset() ?: Mime::optimalCharset($body);

        if (count($attachments)) {
            $cursor->mime('multipart/mixed');
            $current = $cursor->add(new MixedPart());
            foreach ($attachments as $path => $attachment) {
                $cursor->add(fopen($path, 'r'), $attachment);
            }
            $cursor = $current;
        }

        if ($altBody || count($inlines)) {
            $cursor->mime('multipart/alternative');
        }

        if ($altBody) {
            $cursor->add($altBody, [
                'mime'     => 'text/plain',
                'charset'  => Mime::optimalCharset($altBody),
                'encoding' => Mime::optimalEncoding($altBody)
            ]);
        }

        if ($body) {
            $options = [
                'mime'     => $bodyMime,
                'charset'  => $bodyCharset,
                'encoding' => Mime::optimalEncoding($body)
            ];

            if ($inlines) {
                $current = $cursor->add(new MixedPart(['mime' => 'multipart/related']));
                $current->add($body, $options);
                foreach ($inlines as $path => $inline) {
                    $current->add(fopen($path, 'r'), $inline);
                }
            } else {
                $cursor->add($body, $options);
            }
        }

        $headers = $root->headers();
        $headers['Date'] = date('r');
        $headers['Message-ID'] = static::generateId($this->client());
        return $root->toMessage();
    }

    public function _buildMixed($message)
    {
        $attachments = $message->attachments();
        if (!$attachments) {
            return;
        }

        foreach ($attachments as $path => $attachment) {
            $mimeMixed->add(fopen($path, 'r'), $attachment);
        }
        return $mimeMixed;
    }

    public function _buildRelated($message)
    {
        $inlines = $message->inlines();
        if (!$inlines) {
            return;
        }
        $mimeRelated = new MimeStream(['mime' => 'multipart/related']);

        return $mimeRelated;
    }

    /**
     * Clone the message.
     */
    public function __clone()
    {
        $this->_stream = clone $this->_stream;
    }

    /**
     * Unique ID Generator.
     *
     * @param  string $client The client host name.
     * @return string
     */
    public static function generateId($client)
    {
        return sprintf('<%s@%s>', md5(uniqid(time())), $client);
    }

    /**
     * Strip HTML tags
     *
     * @param  string $html The html content
     * @return string
     */
    public static function stripTags($html, $charset = 'UTF-8')
    {
        $patterns = [
            '~<(style|script|head).*</\\1>~Uis' => '',
            '~<t[dh][ >]~i' => ' $0',
            '~<a\s[^>]*href=(?|"([^"]+)"|\'([^\']+)\')[^>]*>(.*?)</a>~is' => '$2 <$1>',
            '~[\r\n ]+~' => ' ',
            '~<(/?p|/?h\d|li|br|/tr)[ >/]~i' => "\n$0",
        ];

        $text = preg_replace(array_keys($patterns), array_values($patterns), $html);
        $text = html_entity_decode(strip_tags($text), ENT_QUOTES, $charset);
        $text = preg_replace('~[ \t]+~', ' ', $text);
        return trim($text);
    }
}


text:
import {Component} from '@angular/core';
import {AbstractMapComponent} from "../../../ac-abstract-map-component/abstract-map-component.component";
import {cesiumPolylineInputs} from "../../../../constants/cesium-inputs.constants";
import {MapService} from "../../../../services/core/map.service";
import {CesiumEntityHolder} from "../../../../services/entity.service";
import {PolylinesGraphicsService} from "../../../../services/drawers/graphics/polyline-graphics.service";

@Component({
  moduleId: module.id,
  selector: 'ac-polyline-graphics',
  template: ``,
  inputs: cesiumPolylineInputs
})
export class AngularCesiumPolylineGraphics extends AbstractMapComponent {

  constructor(mapService: MapService, polylinesGraphicsService: PolylinesGraphicsService, entityService:CesiumEntityHolder) {
    super(mapService, polylinesGraphicsService, cesiumPolylineInputs, entityService);
  }

}

redpajama_set_name: RedPajamaGithub


text:
#include "config.h"
#include "SVGTextPathElement.h"

#include "RenderSVGResource.h"
#include "RenderSVGTextPath.h"
#include "SVGNames.h"
#include "XLinkNames.h"
#include <wtf/NeverDestroyed.h>

namespace WebCore {

// Animated property definitions
DEFINE_ANIMATED_LENGTH(SVGTextPathElement, SVGNames::startOffsetAttr, StartOffset, startOffset)
DEFINE_ANIMATED_ENUMERATION(SVGTextPathElement, SVGNames::methodAttr, Method, method, SVGTextPathMethodType)
DEFINE_ANIMATED_ENUMERATION(SVGTextPathElement, SVGNames::spacingAttr, Spacing, spacing, SVGTextPathSpacingType)
DEFINE_ANIMATED_STRING(SVGTextPathElement, XLinkNames::hrefAttr, Href, href)

BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGTextPathElement)
    REGISTER_LOCAL_ANIMATED_PROPERTY(startOffset)
    REGISTER_LOCAL_ANIMATED_PROPERTY(method)
    REGISTER_LOCAL_ANIMATED_PROPERTY(spacing)
    REGISTER_LOCAL_ANIMATED_PROPERTY(href)
    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTextContentElement)
END_REGISTER_ANIMATED_PROPERTIES

inline SVGTextPathElement::SVGTextPathElement(const QualifiedName& tagName, Document& document)
    : SVGTextContentElement(tagName, document)
    , m_startOffset(LengthModeOther)
    , m_method(SVGTextPathMethodAlign)
    , m_spacing(SVGTextPathSpacingExact)
{
    ASSERT(hasTagName(SVGNames::textPathTag));
    registerAnimatedPropertiesForSVGTextPathElement();
}

Ref<SVGTextPathElement> SVGTextPathElement::create(const QualifiedName& tagName, Document& document)
{
    return adoptRef(*new SVGTextPathElement(tagName, document));
}

SVGTextPathElement::~SVGTextPathElement()
{
    clearResourceReferences();
}

void SVGTextPathElement::clearResourceReferences()
{
    document().accessSVGExtensions().removeAllTargetReferencesForElement(this);
}

bool SVGTextPathElement::isSupportedAttribute(const QualifiedName& attrName)
{
    static NeverDestroyed<HashSet<QualifiedName>> supportedAttributes;
    if (supportedAttributes.get().isEmpty()) {
        SVGURIReference::addSupportedAttributes(supportedAttributes);
        supportedAttributes.get().add(SVGNames::startOffsetAttr);
        supportedAttributes.get().add(SVGNames::methodAttr);
        supportedAttributes.get().add(SVGNames::spacingAttr);
    }
    return supportedAttributes.get().contains<SVGAttributeHashTranslator>(attrName);
}

void SVGTextPathElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
    SVGParsingError parseError = NoError;

    if (name == SVGNames::startOffsetAttr)
        setStartOffsetBaseValue(SVGLength::construct(LengthModeOther, value, parseError));
    else if (name == SVGNames::methodAttr) {
        SVGTextPathMethodType propertyValue = SVGPropertyTraits<SVGTextPathMethodType>::fromString(value);
        if (propertyValue > 0)
            setMethodBaseValue(propertyValue);
    } else if (name == SVGNames::spacingAttr) {
        SVGTextPathSpacingType propertyValue = SVGPropertyTraits<SVGTextPathSpacingType>::fromString(value);
        if (propertyValue > 0)
            setSpacingBaseValue(propertyValue);
    }

    reportAttributeParsingError(parseError, name, value);

    SVGTextContentElement::parseAttribute(name, value);
    SVGURIReference::parseAttribute(name, value);
}

void SVGTextPathElement::svgAttributeChanged(const QualifiedName& attrName)
{
    if (!isSupportedAttribute(attrName)) {
        SVGTextContentElement::svgAttributeChanged(attrName);
        return;
    }

    InstanceInvalidationGuard guard(*this);

    if (SVGURIReference::isKnownAttribute(attrName)) {
        buildPendingResource();
        return;
    }

    if (attrName == SVGNames::startOffsetAttr)
        updateRelativeLengthsInformation();

    if (auto renderer = this->renderer())
        RenderSVGResource::markForLayoutAndParentResourceInvalidation(*renderer);
}

RenderPtr<RenderElement> SVGTextPathElement::createElementRenderer(RenderStyle&& style, const RenderTreePosition&)
{
    return createRenderer<RenderSVGTextPath>(*this, WTFMove(style));
}

bool SVGTextPathElement::childShouldCreateRenderer(const Node& child) const
{
    if (child.isTextNode()
        || child.hasTagName(SVGNames::aTag)
        || child.hasTagName(SVGNames::trefTag)
        || child.hasTagName(SVGNames::tspanTag))
        return true;

    return false;
}

bool SVGTextPathElement::rendererIsNeeded(const RenderStyle& style)
{
    if (parentNode()
        && (parentNode()->hasTagName(SVGNames::aTag)
            || parentNode()->hasTagName(SVGNames::textTag)))
        return StyledElement::rendererIsNeeded(style);

    return false;
}

void SVGTextPathElement::buildPendingResource()
{
    clearResourceReferences();
    if (!inDocument())
        return;

    String id;
    Element* target = SVGURIReference::targetElementFromIRIString(href(), document(), &id);
    if (!target) {
        // Do not register as pending if we are already pending this resource.
        if (document().accessSVGExtensions().isPendingResource(this, id))
            return;

        if (!id.isEmpty()) {
            document().accessSVGExtensions().addPendingResource(id, this);
            ASSERT(hasPendingResources());
        }
    } else if (target->hasTagName(SVGNames::pathTag)) {
        // Register us with the target in the dependencies map. Any change of hrefElement
        // that leads to relayout/repainting now informs us, so we can react to it.
        document().accessSVGExtensions().addElementReferencingTarget(this, downcast<SVGElement>(target));
    }
}

Node::InsertionNotificationRequest SVGTextPathElement::insertedInto(ContainerNode& rootParent)
{
    SVGTextContentElement::insertedInto(rootParent);
    return InsertionShouldCallFinishedInsertingSubtree;
}

void SVGTextPathElement::finishedInsertingSubtree()
{
    buildPendingResource();
}

void SVGTextPathElement::removedFrom(ContainerNode& rootParent)
{
    SVGTextContentElement::removedFrom(rootParent);
    if (rootParent.inDocument())
        clearResourceReferences();
}

bool SVGTextPathElement::selfHasRelativeLengths() const
{
    return startOffset().isRelative()
        || SVGTextContentElement::selfHasRelativeLengths();
}

}


text:
<?php
// Paginador por defecto
echo '';
echo '';
echo '';
echo '';
echo '';
echo '';
?>


text:
using FtApp.Fischertechnik;
using FtApp.Fischertechnik.Txt.Events;
using System;

namespace TXTCommunication.Fischertechnik
{
    public interface IFtInterface : IDisposable
    {
        ConnectionStatus Connection { get; set; }

        /// <summary>
        /// This function tries to connect to an interface with the given address.
        /// </summary>
        /// <param name="address">For the TXT Controller it is an ip address and for the TX Controller it is the mac address</param>
        void Connect(string address);

        /// <summary>
        /// This function closes the connection
        /// </summary>
        void Disconnect();

        /// <summary>
        /// This function starts the online mode. Then the inputs can be read and the outputs can be set
        /// </summary>
        void StartOnlineMode();

        /// <summary>
        /// This functions stops the online mode. Then I/O commands should not be sent anymore
        /// </summary>
        void StopOnlineMode();

        /// <summary>
        /// Checks if commands (like set an output value) can be sent
        /// </summary>
        bool CanSendCommand();

        /// <summary>
        /// Reads the version code of the interface firmware
        /// </summary>
        /// <returns>The firmware version</returns>
        string GetInterfaceVersionCode();

        /// <summary>
        /// Reads the name of the interface
        /// </summary>
        /// <returns>The interface name</returns>
        string GetInterfaceName();

        /// <summary>
        /// Returns the numberof universal inputs
        /// </summary>
        /// <returns>The number of universal inputs</returns>
        int GetInputCount();

        /// <summary>
        /// Returns the number of output ports. Note: The output ports can either be a single output or two ports together as one motor output
        /// </summary>
        /// <returns>The number of output ports</returns>
        int GetOutputCount();

        /// <summary>
        /// Returns the number of motor ports. Note: The motor ports can either be a single output or two ports together as one motor output
        /// </summary>
        /// <returns>The number of motor ports</returns>
        int GetMotorCount();

        /// <summary>
        /// Returns the maximal output value. The TX Controller and TXT Controller support from 0 to 512
        /// </summary>
        /// <returns>The maximal output value</returns>
        int GetMaxOutputValue();

        /// <summary>
        /// Returns the type of the controller protocol implementation
        /// </summary>
        /// <returns>the type of the interface</returns>
        ControllerType GetControllerType();

        /// <summary>
        /// Reads the controller name without the need of connecting and disconnecting (This is done internally)
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        string RequestControllerName(string address);

        /// <summary>
        /// Checks if the interface at the given address is valid
        /// </summary>
        /// <param name="address">The address to ckeck</param>
        /// <returns>true, when the interface is valid otherwise false</returns>
        bool IsValidInterface(string address);

        /// <summary>
        /// Returns the index of the motor port. Output 5 => M3; Output 2 => M1
        /// </summary>
        /// <param name="outputIndex">The index of the output port</param>
        /// <returns>The index of the motor port</returns>
        int GetMotorIndex(int outputIndex);

        /// <summary>
        /// This function sets a output port to the given value. The value is updated when UpdateValues() is called.
        /// </summary>
        /// <param name="outputIndex">The index of the port.</param>
        /// <param name="value">The value to set between 0 and 512</param>
        /// <param name="extension">The extension where the value should be set</param>
        /// ReSharper disable once UnusedParameter.Global
        void SetOutputValue(int outputIndex, int value, int extension = 0);

        /// <summary>
        /// This function sets a motor to the given speed and direction. The value is updated when UpdateValues() is called.
        /// </summary>
        /// <param name="motorIndex">The index of the motor.</param>
        /// <param name="value">The value to set between 0 and 512</param>
        /// <param name="direction">The direction</param>
        /// <param name="extension">The extension where the value should be set</param>
        /// ReSharper disable once UnusedParameter.Global
        void SetMotorValue(int motorIndex, int value, MotorDirection direction, int extension = 0);

        /// <summary>
        /// Configures a given output port. If <paramref name="isMotor"/> is true, the output ports are set to motor ports
        /// </summary>
        /// <param name="outputIndex">The index of the output port</param>
        /// <param name="isMotor">Specifies whether the output port is a motor</param>
        /// <param name="extension">The extension where the value should be set</param>
        /// ReSharper disable once UnusedParameter.Global
        void ConfigureOutputMode(int outputIndex, bool isMotor, int extension = 0);

        /// <summary>
        /// Returns the value of an input port.
        /// </summary>
        /// <param name="index">The index of the input port</param>
        /// <param name="extension">The extension where the value should be read</param>
        /// ReSharper disable once UnusedParameter.Global
        int GetInputValue(int index, int extension = 0);

        /// <summary>
        /// Configures the input mode of a given port.
        /// </summary>
        /// <param name="inputIndex">The index of the input port</param>
        /// <param name="inputMode">The input mode of the port</param>
        /// <param name="digital">Specifies whether the port is digital or analog</param>
        /// <param name="extension">The extension where the value should be set</param>
        /// ReSharper disable once UnusedParameter.Global
        void ConfigureInputMode(int inputIndex, InputMode inputMode, bool digital, int extension = 0);

        /// <summary>
        /// This event is fired when the input valus have changed
        /// </summary>
        event InputValueChangedEventHandler InputValueChanged;

        /// <summary>
        /// This event is fired when the interface is connected successfully
        /// </summary>
        event ConnectedEventHandler Connected;

        /// <summary>
        /// This event is fired when the connection to the interface is lost
        /// </summary>
        event ConnectionLostEventHandler ConnectionLost;

        /// <summary>
        /// This event is fired when the interface is disconnected
        /// </summary>
        event DisconnectedEventHandler Disconnected;

        /// <summary>
        /// This event is fired when the online mode started
        /// </summary>
        event OnlineStartedEventHandler OnlineStarted;

        /// <summary>
        /// This event is fired when the online mode stopped
        /// </summary>
        event OnlineStoppedEventHandler OnlineStopped;
    }

    public enum MotorDirection
    {
        Left,
        Right
    }

    /// <summary>
    /// This enumeration contains the connection states
    /// </summary>
    public enum ConnectionStatus
    {
        /// <summary>
        /// Connected means that the connection is established but not in online mode
        /// </summary>
        Connected,

        /// <summary>
        /// The online mode is enabled
        /// </summary>
        Online,

        /// <summary>
        /// No interface is connected
        /// </summary>
        NotConnected,

        /// <summary>
        /// The connection is invalid most likely because of an timeout
        /// </summary>
        Invalid
    }

    /// <summary>
    /// These are the input modes which the TX Controller and the TXT Controller use
    /// </summary>
    public enum InputMode
    {
        /// <summary>
        /// ModeU measures the voltage. Often used for the trail sensor (digital) and color sensor (analog)
        /// </summary>
        ModeU = 0,

        /// <summary>
        /// ModeR measures the resistance. This mode is used for simple digital switches or an analog NTC
        /// </summary>
        ModeR,
        ModeR2,

        /// <summary>
        /// ModeUltrasonic is a special mode. It is used for an ultrasonic sensor
        /// </summary>
        ModeUltrasonic,
        ModeInvalid
    }

    public delegate void InputValueChangedEventHandler(object sender, InputValueChangedEventArgs e);
    public delegate void ConnectedEventHandler(object sender, EventArgs e);
    public delegate void ConnectionLostEventHandler(object sender, EventArgs e);
    public delegate void DisconnectedEventHandler(object sender, EventArgs e);
    public delegate void OnlineStartedEventHandler(object sender, EventArgs e);
    public delegate void OnlineStoppedEventHandler(object sender, EventArgs e);
}


text:
/***********************************************************************************************************
 * com.oclib.javascript.math.events.20070204.NumeralSystem
 * Location: http://www.oclib.com/library/com/oclib/javascript/math/NumeralSystem.js
 * Version Location: http://www.oclib.com/library/com/oclib/javascript/math/numeralSystem/20070204/.js
 * Index Version Location: http://www.oclib.com/library/com/oclib/javascript/math/numeralSystem/20070204/index.html
 * © Open Class Library (http://www.oclib.com/)
 * See Also http://en.wikipedia.org/wiki/Numeral
 * See Also http://netzreport.googlepages.com/online_converter_for_numerals.html
 * See Also http://netzreport.googlepages.com/online_converter_for_dec_roman.html
***********************************************************************************************************/
if (typeof com == "undefined") {com = {};};
if (typeof com.oclib == "undefined") {com.oclib = {};};
if (typeof com.oclib.javascript == "undefined") {com.oclib.javascript = {};};
if (typeof com.oclib.javascript.math == "undefined") {com.oclib.javascript.math = {};};

if (typeof com.oclib.javascript.math.NumeralSystem == "undefined") {
 com.oclib.javascript.math.NumeralSystem = function() {}
 com.oclib.javascript.math.NumeralSystem.prototype = new  com.oclib.javascript.lang.Root();

 com.oclib.javascript.math.NumeralSystem.prototype.className = "NumeralSystem";
 com.oclib.javascript.math.NumeralSystem.prototype.classNamespace = "com.oclib.javascript.math.NumeralSystem";
 com.oclib.javascript.math.NumeralSystem.prototype.classCreated = "20070204";
 com.oclib.javascript.math.NumeralSystem.prototype.classCreator = "http://www.oclib.com/";
 com.oclib.javascript.math.NumeralSystem.prototype.classLocation = "http://www.oclib.com/library/com/oclib/javascript/math/NumeralSystem.js";
 com.oclib.javascript.math.NumeralSystem.prototype.classIndexLocation = "http://www.oclib.com/library/com/oclib/javascript/math/events/";
 com.oclib.javascript.math.NumeralSystem.prototype.classVersion = "20070204";
 com.oclib.javascript.math.NumeralSystem.prototype.classVersionLocation = "http://www.oclib.com/library/com/oclib/javascript/math/events/20070204/NumeralSystem.js";
 com.oclib.javascript.math.NumeralSystem.prototype.classVersionIndexLocation = "http://www.oclib.com/library/com/oclib/javascript/math/events/20070204/";

 com.oclib.javascript.math.NumeralSystem.prototype.decimalNumerals = "0123456789";
  com.oclib.javascript.math.NumeralSystem.prototype.getDecimalNumerals = function () {return this.decimalNumerals;};
  com.oclib.javascript.math.NumeralSystem.prototype.setDecimalNumerals = function (decimalNumerals) {this.decimalNumerals = decimalNumerals; return 1;};
 com.oclib.javascript.math.NumeralSystem.prototype.fromNumerals = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  com.oclib.javascript.math.NumeralSystem.prototype.getFromNumerals = function () {return this.fromNumerals;};
  com.oclib.javascript.math.NumeralSystem.prototype.setFromNumerals = function (fromNumerals) {this.fromNumerals = fromNumerals; return 1;};
 com.oclib.javascript.math.NumeralSystem.prototype.maxDecimal = 9999;
  com.oclib.javascript.math.NumeralSystem.prototype.getMaxDecimal = function () {return this.maxDecimal;};
  com.oclib.javascript.math.NumeralSystem.prototype.setMaxDecimal = function (maxDecimal) {this.maxDecimal = maxDecimal; return 1;};
 com.oclib.javascript.math.NumeralSystem.prototype.romanNumerals = "IVXLCDM";
  com.oclib.javascript.math.NumeralSystem.prototype.getRomanNumerals = function () {return this.romanNumerals;};
  com.oclib.javascript.math.NumeralSystem.prototype.setRomanNumerals = function (romanNumerals) {this.romanNumerals = romanNumerals; return 1;};
 com.oclib.javascript.math.NumeralSystem.prototype.maxRoman = 21; // largest Roman representation of a decimal numeral smaller than 10000 (MMMMMMMMMDCCCLXXXVIII = 9888)
  com.oclib.javascript.math.NumeralSystem.prototype.getMaxRoman = function () {return this.maxRoman;};
  com.oclib.javascript.math.NumeralSystem.prototype.setMaxRoman = function (maxRoman) {this.maxRoman = maxRoman; return 1;};
 com.oclib.javascript.math.NumeralSystem.prototype.simpleNumerals = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  com.oclib.javascript.math.NumeralSystem.prototype.getSimpleNumerals = function () {return this.simpleNumerals;};
  com.oclib.javascript.math.NumeralSystem.prototype.setSimpleNumerals = function (simpleNumerals) {this.simpleNumerals = simpleNumerals; return 1;};
 com.oclib.javascript.math.NumeralSystem.prototype.toNumerals = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  com.oclib.javascript.math.NumeralSystem.prototype.getToNumerals = function () {return this.toNumerals;};
  com.oclib.javascript.math.NumeralSystem.prototype.setToNumerals = function (toNumerals) {this.toNumerals = toNumerals; return 1;};

 // fromRadix, toRadix is decimal
 com.oclib.javascript.math.NumeralSystem.prototype.convert = function(fromNumber, fromRadix, toRadix) {
  if(this.mustTrace()) {this.getLog().println("NumeralSystem.convert is runing...");};
  return this.convertFromDecimal(this.convertToDecimal(fromNumber, fromRadix), toRadix);
 };

 // fromRadix, toRadix = 2..36 and is decimal
 // fromNumber embody only this.numerals
 com.oclib.javascript.math.NumeralSystem.prototype.convert36 = function(fromNumber, fromRadix, toRadix) {
  if(this.mustTrace()) {this.getLog().println("NumeralSystem.convert36 is runing...");};
  if(!fromNumber || !fromRadix || !toRadix) {return -1;};
  // Remove spaces from beginning and end of string:
  fromNumber = "" + fromNumber;
  fromRadix = "" + fromRadix;
  toRadix = "" + toRadix;
  fromNumber = fromNumber.replace(/^ */g,"");
  fromRadix = fromRadix.replace(/^ */g,"");
  toRadix = toRadix.replace(/^ */g,"");
  fromNumber = fromNumber.replace(/ *$/g,"");
  fromRadix = fromRadix.replace(/ *$/g,"");
  toRadix = toRadix.replace(/ *$/g,"");
  // Remove zeros from beginning of string:
  fromNumber = fromNumber.replace(/^0*/,"");
  fromRadix = fromRadix.replace(/^0*/,"");
  toRadix = toRadix.replace(/^0*/,"");
  if(fromRadix == toRadix) {return fromNumber;};
  if(fromNumber == "" || fromRadix == "" || toRadix == "") {return -2;};
  if(fromRadix < 2 || fromRadix > 36 || toRadix < 2 || toRadix > 36 ) {return -3;};
  // Check if input is a legal numeral:
  fromNumber = fromNumber.toUpperCase();
  var legalNumerals = this.simpleNumerals.substring(0, fromRadix);
  for (var i = 0; i < fromNumber.length; i++) {
   if (legalNumerals.indexOf(fromNumber.charAt(i)) == -1) {
    return -4;
   };
  };
  var toNumber = "";
  // Convert to other numeral systems:
  // Get decimal value of input:
  var inputdecimal = parseInt(fromNumber, fromRadix);
  // Convert:
  return inputdecimal.toString(toRadix).toUpperCase();
 };

 com.oclib.javascript.math.NumeralSystem.prototype.convertDecimalToRoman = function(decimalNumber) {
  if(this.mustTrace()) {this.getLog().println("NumeralSystem.convertDecimalToRoman is runing... for decimalNumber = "+decimalNumber);};
  if(!decimalNumber) {return -1};
  // We are generous and allow unorthodox ways to write a decimal numeral:
  // Remove spaces from beginning and end of string:
  decimalNumber = "" + decimalNumber;
  decimalNumber = decimalNumber.replace(/^ */,"");
  decimalNumber = decimalNumber.replace(/ *$/,"");
  // Remove zeros from beginning of string:
  decimalNumber = decimalNumber.replace(/^0*/,"");
  if(decimalNumber == "") {return -2;};
  // Check if input is a legal decimal numeral:
  for (var i = 0; i < decimalNumber.length; i++) {
   if (this.decimalNumerals.indexOf(decimalNumber.charAt(i)) == -1) {return -3;};
  };
  // Check if decimal numeral is not too large:
  if (decimalNumber > this.maxDecimal) {return -4;};
  // Convert decimal to Roman numeral:
  var i = decimalNumber.length - 1; // now decimalNumber.charAt(i) gives us the last digit of decinput
  var romanNumber = "";
  // Now we convert the decimal numeral from right to left:
  while (i >= 0 ) {
    romanNumber = this.getRoman((decimalNumber.length - i), decimalNumber.charAt(i)) + romanNumber;
    i--;
  };
  return romanNumber;
 };

 // number and radix is decimal!
 com.oclib.javascript.math.NumeralSystem.prototype.convertFromDecimal = function(number, radix) {
  if(this.mustTrace()) {this.getLog().println("NumeralSystem.convertFromDecimal is runing... for number = "+number+"; radix = "+radix);};
  if(!number || !radix) {return -1};
  number = "" + number;
  radix = "" + radix;
  number = number.replace(/^ */g,"");
  radix = radix.replace(/^ */g,"");
  number = number.replace(/ *$/g,"");
  radix = radix.replace(/ *$/g,"");
  number = number.replace(/^0*/g,"");
  radix = radix.replace(/^0*/g,"");
  if(number == "" || radix == "") {return -2;};
  if(radix == 10) {return number;};
  for (var i = 0; i < number.length; i++) {
   if (this.decimalNumerals.indexOf(number.charAt(i)) == -1) {return -4;};
  };
  for (var i = 0; i < radix.length; i++) {
   if (this.decimalNumerals.indexOf(radix.charAt(i)) == -1) {return -4;};
  };
  var toNumerals = this.toNumerals.substring(0, radix);
  var radixNumber = "";
  while(number != 0) {
   var residue = number%radix;
   number = (number - residue)/radix;
   radixNumber = "" + toNumerals.charAt(residue) + radixNumber;
  };
  return radixNumber;
 };

 com.oclib.javascript.math.NumeralSystem.prototype.convertRomanToDecimal = function(romanNumber) {
  if(this.mustTrace()) {this.getLog().println("NumeralSystem.convertRomanToDecimal is runing... for romanNumber = "+romanNumber);};
  if(!romanNumber) {return -1};
  // Generosity again! We remove empty spaces:
  romanNumber = romanNumber.replace(/ /g,"");
  if(romanNumber == "") {return -2;};
  // Check if input is a legal Roman numeral:
  romanNumber = romanNumber.toUpperCase();
  for (var i = 0; i < romanNumber.length; i++) {
   if (this.romanNumerals.indexOf(romanNumber.charAt(i)) == -1) {return -3;};
  };
  // Check if Roman numeral is not too large:
  if (romanNumber.length > this.maxRoman) {return -4;};
  // Convert Roman to decimal numeral:
  var decimalNumber = 0;
  var i = romanNumber.length - 1; // now romanNumber.charAt(i) shows us the last char of romanNumber
  while (i >= 0 ) {
   // Is subtractive notation used?:
   if (this.getDecimal(romanNumber.charAt(i)) < this.getDecimal(romanNumber.charAt(i+1))) {
    // Now we are verifying if sorting is correctly used with the subtractive notation.
    // The current character rominput.charAt(i) is put into brackets in the following comments:
    // Strings like [X]CC should be written as CXC:
    if ((i+2) <= (romanNumber.length - 1)) {  // is there a character two characters to the right?
     if (romanNumber.charAt(i+1) == romanNumber.charAt(i+2) ) {return -5;};
    };
    // Strings like [X]CIC should be written as ICXC:
    if ((i+3) <= (romanNumber.length - 1)) {  // is there a character three characters to the right?
     if (romanNumber.charAt(i+1) == romanNumber.charAt(i+3) ) {
      if (this.getDecimal(romanNumber.charAt(i)) > this.getDecimal(romanNumber.charAt(i+2))) {return -6;};
     };
    };
    // Strings like X[I]C should be written as ICX:
    if ((i-1) >= 0) {  // is there a character to the left?
     if (this.getDecimal(romanNumber.charAt(i-1)) < this.getDecimal(romanNumber.charAt(i+1))) {return -7;};
    };
    decimalNumber = decimalNumber - this.getDecimal(romanNumber.charAt(i));
   } else {
    decimalNumber = decimalNumber + this.getDecimal(romanNumber.charAt(i));
   };
   i--;
  };

  return decimalNumber;
 };

 // radix is decimal!
 com.oclib.javascript.math.NumeralSystem.prototype.convertToDecimal = function(number, radix) {
  if(this.mustTrace()) {this.getLog().println("NumeralSystem.convertToDecimal is runing... for number = "+number+"; radix = "+radix);};
  if(!number || !radix) {return -1};
  number = "" + number;
  radix = "" + radix;
  number = number.replace(/^ */g,"");
  radix = radix.replace(/^ */g,"");
  number = number.replace(/ *$/g,"");
  radix = radix.replace(/ *$/g,"");
  number = number.replace(/^0*/g,"");
  radix = radix.replace(/^0*/g,"");
  if(number == "" || radix == "") {return -2;};
  if(radix == 10) {return number;};
  var fromNumerals = this.fromNumerals.substring(0, radix);
  for (var i = 0; i < number.length; i++) {
   if (fromNumerals.indexOf(number.charAt(i)) == -1) {return -3;};
  };
  for (var i = 0; i < radix.length; i++) {
   if (this.decimalNumerals.indexOf(radix.charAt(i)) == -1) {return -4;};
  };
  var decimalNumber = 0;
  for(var i = 0; i < number.length; i++) {
   if(this.mustDebug()) {this.getLog().println("NumeralSystem.convertToDecimal decimalNumber = "+decimalNumber);};
   if(this.mustDebug()) {this.getLog().println("NumeralSystem.convertToDecimal decimalNumber += "+fromNumerals.indexOf(number.charAt(i))+"*Math.pow("+radix+","+number.length-i-1)+")";};
   decimalNumber += fromNumerals.indexOf(number.charAt(i))*Math.pow(radix,number.length-i-1);
  };
  return decimalNumber;
 };

 // Determine decimal value of a Roman numeral:
 com.oclib.javascript.math.NumeralSystem.prototype.getDecimal = function(roman) {
  if (roman == "I") return 1;
  if (roman == "V") return 5;
  if (roman == "X") return 10;
  if (roman == "L") return 50;
  if (roman == "C") return 100;
  if (roman == "D") return 500;
  if (roman == "M") return 1000;
  return 0;
 };

 com.oclib.javascript.math.NumeralSystem.prototype.getRoman = function(position, digit) {
  if(this.mustTrace()) {this.getLog().println("NumeralSystem.getRoman is runing...");};
  if (position == 1) {
   if (digit == 0) return "";
   if (digit == 1) return "I";
   if (digit == 2) return "II";
   if (digit == 3) return "III";
   if (digit == 4) return "IV";
   if (digit == 5) return "V";
   if (digit == 6) return "VI";
   if (digit == 7) return "VII";
   if (digit == 8) return "VIII";
   if (digit == 9) return "IX";
  };
  if (position == 2) {
   if (digit == 0) return "";
   if (digit == 1) return "X";
   if (digit == 2) return "XX";
   if (digit == 3) return "XXX";
   if (digit == 4) return "XL";
   if (digit == 5) return "L";
   if (digit == 6) return "LX";
   if (digit == 7) return "LXX";
   if (digit == 8) return "LXXX";
   if (digit == 9) return "XC";
  };
  if (position == 3) {
   if (digit == 0) return "";
   if (digit == 1) return "C";
   if (digit == 2) return "CC";
   if (digit == 3) return "CCC";
   if (digit == 4) return "CD";
   if (digit == 5) return "D";
   if (digit == 6) return "DC";
   if (digit == 7) return "DCC";
   if (digit == 8) return "DCCC";
   if (digit == 9) return "CM";
  };
  if (position == 4) {
   var roman = "";
   for (var i = 1; i <= digit; i++) {
    roman = roman + "M";
   };
   return roman;
  };
 };
};


text:
module.exports = {
    applyButton: element.all(by.css('#apply-to-join')),
    bottomApplyButton: element.all(by.css('#bottom-apply-to-join')),
    goToMarketplaceButton: element.all(by.css('#go-to-marketplace'))
};


text:
using System;
using System.Linq;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.IO;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using System.Xml.Serialization;
using System.Globalization;

namespace CAT.Model
{
    [Serializable]
    class SProp002 : Strategy
    {
        # region Fields
        private DateTime _clse;
        private int _nStocksTrade;
        private List<Candle> _candles;
        private ConcurrentDictionary<string, Tick> _val;
        #endregion

        #region Constructor / Destructor
        public SProp002()
            : base()
        {
            this.hour = 10;
            _candles = new List<Candle>();
            _val = new ConcurrentDictionary<string, Tick>();
            this.TodayTrades = new ConcurrentDictionary<string, Trade>();
        }
        #endregion

        #region Public override functions
        public override void Run(Tick tick)
        {
            currentTime = tick.Time;

            StartOrReset();

            if (Filter(tick)) return;

            _val.AddOrUpdate(tick.Symbol, tick, (k, v) => v = tick);

            if (TodayTrades.ContainsKey(tick.Symbol))
            {
                //TrailingStop(tick, _todaytrades[tick.Symbol]);

                var action = TodayTrades[tick.Symbol].Update(_val[tick.Symbol])
                    ? 0 : -TodayTrades[tick.Symbol].Type;
                Send(TodayTrades[tick.Symbol], action);

                if (TodayTrades[tick.Symbol].IsTrading) return;

                TodayTrades.TryRemove(tick.Symbol, out trade);
                trades.Add(trade);
            }
            Indicator();
            type = TodayTrades.Count == 0 ? 0 : 1;
        }

        public override void StartOrReset()
        {
            if (_clse.Date == currentTime.Date) return;

            _nStocksTrade = string.IsNullOrWhiteSpace(setup.Parameters)
                ? 10 : int.Parse(setup.Parameters.Split(' ')[0]);

            type = 0;
            _val.Clear();
            TodayTrades.Clear();

            _clse = currentTime.Date.AddHours(9.5).Add(
                TimeZoneInfo.FindSystemTimeZoneById("E. South America Standard Time").GetUtcOffset(eodTime) -
                TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time").GetUtcOffset(eodTime));

            if (setup.DayTradeDuration > 6) eodTime = GetBell(_clse, setup.DayTradeDuration);

            GetLastEOD(currentTime);

            if (eodTime.Date == DateTime.Today)
                OnStatusChanged(setup.SetupId.ToString("Trade ID000 @ ") +
                    _clse.ToShortTimeString() + " Bell: " + eodTime.ToShortTimeString());
        }
        public override IEnumerable<Tick> Datafilter(IEnumerable<Tick> ticks)
        {
            return ticks.Where(t => t.Time > DateTime.Today || t.Time >= this.setup.OfflineStartTime);
        }
        public override void WarmUp(List<Tick> ticks)
        {
            candles = new List<Candle>();
            if (ticks.Count == 0) return;

            var files = Directory.GetFiles(DataDir, "COTAHIST" + "*xml");

            foreach (var file in files)
            {
                var year = ticks.First().Time.Year;
                if (ticks.First().Time.Month == 1) year--;
                if (year > int.Parse(new FileInfo(file).Name.Substring(10, 4))) continue;

                try
                {
                    using (var tr = new StreamReader(file))
                        candles.AddRange((List<Candle>)(new XmlSerializer(typeof(List<Candle>))).Deserialize(tr));
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    throw;
                }
            }

            //_stdLookback = int.Parse(setup.TechAnalysis.Split(' ')[1]);
            candles = candles.OrderBy(c => c.OpenTime).ThenBy(c => c.Symbol).ToList();
        }
        public override void TradableAssets(bool isonline)
        {
            base.TradableAssets();
            this.Symbols.Clear();
            this.candles.Clear();

            if (!isonline) return;

            var max = 5;

            #region Get EOD data
            try
            {
                using (var client = new System.Net.WebClient())
                {
                    _candles = new List<Candle>();

                    for (var i = 1; i <= 8 && _candles.Count == 0; i++)
                    {
                        var lastday = DateTime.Today.AddDays(-i);
                        var url = "http://www.bmfbovespa.com.br/fechamento-pregao/BuscarUltimosPregoes.aspx?" +
                            "Tipo=MercadoVistaDetalhe&Nivel=0&Ancora=A0&idioma=pt-br&Data=" + lastday.ToString("MMdd");

                        OnStatusChanged(url);

                        var result = client.DownloadString(url);

                        var index = result.IndexOf("tbody");
                        if (index < 0) continue;

                        var count = result.IndexOf("tbody", index + 1) - index;
                        result = result.Substring(index, count);

                        index = 0;

                        while ((index = result.IndexOf("<tr", index + 1)) > 0)
                        {
                            count = result.IndexOf("/tr", index) - index;

                            var idx = 0;
                            var pass = -2;
                            var candle = new Candle() { Period = "D", OpenTime = lastday.Date };
                            var line = result.Substring(index, count);

                            while ((idx = line.IndexOf("\">", idx) + 2) > 1)
                            {
                                pass++;
                                var field = line.Substring(idx, line.IndexOf("<", idx) - idx);

                                if (pass == 0) candle.Symbol = field.Replace("#", "").Trim();
                                if (pass == 2) candle.Indicators = field.Trim();
                                if (pass == 3) candle.OpenValue = decimal.Parse(field);
                                if (pass == 4) candle.MinValue = decimal.Parse(field);
                                if (pass == 5) candle.MaxValue = decimal.Parse(field);
                                if (pass == 6) candle.AveValue = decimal.Parse(field);
                                if (pass == 7) candle.CloseValue = decimal.Parse(field);
                                if (pass == 7) candle.AdjClValue = decimal.Parse(field);
                                if (pass == 11) candle.Trades = decimal.Parse(field);
                                if (pass == 12) candle.Quantity = decimal.Parse(field) / 1000;
                            }
                            if (candle.MinValue < 3 || candle.Trades < 100) continue;
                            if (!candle.Indicators.Contains("ON") && !candle.Indicators.Contains("PN")) continue;

                            _candles.Add(candle);
                        }
                    }
                }
                if (_candles.Count == 0) return;

                var symbols = new List<string>();
                var candlex = new List<Candle>();
                _candles.ForEach(c =>
                {
                    if (!symbols.Contains(c.Symbol.Substring(0, 4)))
                        symbols.Add(c.Symbol.Substring(0, 4));
                });
                symbols.ForEach(s =>
                {
                    var candlez = _candles.FindAll(c => c.Symbol.Contains(s));
                    if (candlez.Count < 2)
                        _candles.RemoveAll(c => c.Symbol.Contains(s));
                    else
                    {
                        var i = candlez.First().Trades > candlez.Last().Trades ? 0 : 1;
                        candlex.Add(candlez[i]);
                    }
                });

                symbols.Clear();
                max = Math.Min(max, candlex.Count);
                candlex = candlex.OrderByDescending(c => c.Trades).ToList().GetRange(0, max);
                candlex.ForEach(c =>
                {
                    if (!symbols.Contains(c.Symbol.Substring(0, 4)))
                        symbols.Add(c.Symbol.Substring(0, 4));
                });
                _candles.RemoveAll(c => !symbols.Contains(c.Symbol.Substring(0, 4)));

                this.Symbols = _candles.Select(c => c.Symbol).ToList();
            }
            catch (Exception e) { OnStatusChanged("SProp002: " + e.Message); return; }
            #endregion

            _candles.OrderByDescending(c => c.Symbol).ToList()
                .ForEach(c => { OnStatusChanged(c.ToString().Replace("D;", max.ToString("000") + ";").Replace(";", "\t")); max--; });

            if (currentTime > _clse) _candles.Clear();
        }
        public override bool Filter(Tick tick)
        {
            return !Symbols.Contains(tick.Symbol);
        }

        #endregion

        #region Private functions
        private bool Indicator()
        {
            var exitcode = true;
            if (_candles.Count == 0 || currentTime < _clse) return exitcode;

            foreach (var item in _val)
            {
                Candle candle;
                if ((candle = _candles.FirstOrDefault(c => c.Symbol == item.Key)) == null) continue;
                var type = candle.Symbol.Substring(4) != "3" ? -1 : 1;
                _candles.Remove(candle);

                var trade = new Trade(type, _val[candle.Symbol], setup);
                trade.CloseTime = eodTime;
                trade.IsTrading = true;
                TodayTrades.TryAdd(candle.Symbol, trade);
                Send(trade, 1);

                exitcode = false;
            }
            return exitcode;
        }
        private void TrailingStop(Tick tick, Trade trade)
        {
            if (!setup.DynamicLoss.HasValue) return;
            if (tick.Symbol != trade.Symbol) return;

            var tsl = trade.Type * (tick.Value - trade.EntryValue * (decimal?)setup.DynamicLoss * trade.Type);
            if (tsl > trade.Type * trade.StopLoss) trade.StopLoss = tsl * trade.Type;
        }
        private void GetLastEOD(DateTime today)
        {
            var max = 5;

            try
            {
                if (today.Date == DateTime.Today) { this.TradableAssets(true); return; }

                _candles = new List<Candle>();

                for (var i = 1; i <= 8 && _candles.Count == 0; i++)
                {
                    var tmpcandles = candles.FindAll(c => c.OpenTime.Date == today.AddDays(-i).Date);
                    if (tmpcandles.Count == 0) continue;
                    candles.RemoveRange(0, 1 + candles.FindIndex(c => c == tmpcandles.Last()));
                    tmpcandles.ForEach(c => _candles.Add(c));
                }
                if (_candles.Count == 0) return;

                var symbols = new List<string>();
                var candlex = new List<Candle>();
                _candles.ForEach(c =>
                {
                    if (!symbols.Contains(c.Symbol.Substring(0, 4)))
                        symbols.Add(c.Symbol.Substring(0, 4));
                });
                symbols.ForEach(s =>
                {
                    var candlez = _candles.FindAll(c => c.Symbol.Contains(s));
                    if (candlez.Count < 2)
                        _candles.RemoveAll(c => c.Symbol.Contains(s));
                    else
                    {
                        var i = candlez.First().Trades > candlez.Last().Trades ? 0 : 1;
                        candlex.Add(candlez[i]);
                    }
                });

                symbols.Clear();
                max = Math.Min(max, candlex.Count);
                candlex = candlex.OrderByDescending(c => c.Trades).ToList().GetRange(0, max);
                candlex.ForEach(c =>
                {
                    if (!symbols.Contains(c.Symbol.Substring(0, 4)))
                        symbols.Add(c.Symbol.Substring(0, 4));
                });
                _candles.RemoveAll(c => !symbols.Contains(c.Symbol.Substring(0, 4)));

                this.Symbols = _candles.Select(c => c.Symbol).ToList();
            }
            catch (Exception e) { OnStatusChanged("SProp002: " + e.Message); return; }
        }
        #endregion
    }
}


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'samplserv'

require 'minitest/autorun'


text:
<!-- Thanks for filing an issue! Please use this template to provide more context for the issue . -->

**Description of the issue**:

**Expected behavior**:

**Steps to reproduce**: <!-- Please provide a minimal and precise series of steps -->

**Environment**: <!-- OS, Maven, and other relevant environment information -->

**`skaffold-maven-plugin` Configuration:**
```xml
PASTE YOUR pom.xml CONFIGURATION HERE
```

--- OR ---

**`skaffold-gradle-plugin` Configuration:**
```xml
PASTE YOUR build.gradle CONFIGURATION HERE
```

**Log output**: <!-- If applicable, provide relevant log output -->

**Additional Information**: <!-- Any additional information that may be helpful -->

<!-- Thanks for contributing! -->


text:
using System;
using Highway.Data.Rest.Configuration.Conventions;

#endregion

namespace Highway.Data.Rest.Tests
{
    public class TestConvention : IRestConvention
    {
        public string DefaultRoute(Type type)
        {
            return "Test";
        }

        public string DefaultKey(Type type)
        {
            return "Id";
        }

        public RestActionFormat DefaultFormat()
        {
            return new RestActionFormat
            {
                Single = "{{{1}}}/{0}",
                All = "{{{1}}}"
            };
        }
    }
}


text:
<!DOCTYPE html>

<meta http-equiv="X-UA-Compatible" content="chrome=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="format-detection" content="telephone=no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<title>rtc.io</title>
<link rel="stylesheet" type="text/css" href="css/reset.css">
<link rel="stylesheet" type="text/css" href="css/main.css">

<link rel="stylesheet" media="screen and (max-width: 960px)" href="css/tablet.css">
<link rel="stylesheet" media="screen and (max-width: 710px)" href="css/phone.css">
<link rel="stylesheet" type="text/css" href="fonts/source-sans/stylesheet.css">
<link rel="stylesheet" type="text/css" href="css/code.css">

    rtc.io

About

Tutorials

Demos

Modules

Creating a simple video conferencing application

In this tutorial we will start exploring how to use the
rtc-quickconnect module to create a
simple video conferencing application.

Prior to completing this example it's recommended that you complete
the Creating a simple chat application tutorial
as it will cover some of the fundamentals of how rtc-quickconnect works.

Here is an example that captures local video and allows one or more peers to connect via video conferencing:

var quickconnect = require('rtc-quickconnect');
var media = require('rtc-media');
var crel = require('crel');

// create containers for our local and remote video
var local = crel('div', { class: 'local' });
var remote = crel('div', { class: 'remote' });
var media;
var peerMedia = {};

// capture local media
var localMedia = media();

// once media is captured, connect
localMedia.once('capture', function(stream) {
  quickconnect('http://rtc.io/switchboard/', { room: 'conftest' })
    // broadcast our captured media to other participants in the room
    .addStream(stream)
    // when a peer is connected (and active) pass it to us for use
    .on('call:started', function(id, pc, data) {
      console.log('peer connected: ', id);

      // render the remote streams
      pc.getRemoteStreams().forEach(renderRemote(id));
    })
    // when a peer leaves, remove teh media
    .on('call:ended', function(id) {
      // remove media for the target peer from the dom
      (peerMedia[id] || []).splice(0).forEach(function(el) {
        el.parentNode.removeChild(el);
      });
    })
});

// render the local media
localMedia.render(local);

// render a remote video
function renderRemote(id) {
  // create the peer media list
  peerMedia[id] = peerMedia[id] || [];

  return function(stream) {
    peerMedia[id] = peerMedia[id].concat(media(stream).render(remote));
  }
}

/* extra code to handle dynamic html and css creation */

// add some basic styling
document.head.appendChild(crel('style', [
  '.local { position: absolute;  right: 10px; }',
  '.local video { max-width: 200px; }'
].join('\n')));

// add the local and remote elements
document.body.appendChild(local);
document.body.appendChild(remote);

    © NICTA 2013 - 2014

Project source code is licensed under the Apache 2.0.


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:minWidth="300dip"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/esm_instructions"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <RatingBar
        android:id="@+id/esm_likert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:fitsSystemWindows="true" android:layout_gravity="center_horizontal"/>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/esm_min"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall" android:layout_weight="1" android:gravity="left"/>

        <TextView
            android:id="@+id/esm_max"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textAppearance="?android:attr/textAppearanceSmall" android:gravity="right"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/esm_cancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Cancel" />

        <Button
            android:id="@+id/esm_submit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_vertical|center_horizontal"
            android:text="Button" />

    </LinearLayout>

</LinearLayout>


text:
package org.esbench.elastic.stats.analyzer;

import org.elasticsearch.search.aggregations.metrics.stats.extended.ExtendedStats;
import org.esbench.elastic.stats.FieldInfo;
import org.esbench.generator.field.meta.BooleanFieldMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BooleanStatsAnalyzer implements ExtendedStatsAnalyzer<BooleanFieldMetadata> {
	private static final Logger LOGGER = LoggerFactory.getLogger(BooleanStatsAnalyzer.class);

	@Override
	public BooleanFieldMetadata parse(FieldInfo info, ExtendedStats stats, int valuesPerDocument) {
		long total = stats.getCount();
		long trueValues = (long) stats.getSum();
		long falseValues = (long) (total - stats.getSum());
		LOGGER.info("Field {} Total: {} #tokens/doc: {} True: {} False: {}", info.getFullPath(), total, valuesPerDocument, trueValues, falseValues);
		return new BooleanFieldMetadata(info.getFullPath());
	}

}


text:
const React = require('react');
const PropTypes = React.PropTypes;

const defaultPlay = ▶;
const defaultPause = ❚❚;

const playerContainerStyles = {
  display: 'block',
  width: '100%',
  position: 'relative'
};
const playPauseButtonLayoutStyles = {
  display: 'inline-block',
  marginTop: '9px',
  width: '14%',
  verticalAlign: 'top',
  cursor: 'pointer'
};
const playProgressLayoutWrapperStyles = {
  display: 'inline-block',
  width: '84%'
};
const audioProgressBarContainerStyles = () => ({
  display: 'block',
  width: '0%',
  height: '21px',
  marginTop: '8px',
  background: 'transparent',
  borderLeft: '1px solid #777',
  borderRight: '1px solid #777'
});
const audioPlayerLineStyles = {
  width: '100%',
  height: '0px',
  paddingTop: '10px',
  display: 'block',
  background: 'transparent',
  borderBottom: '1px solid #777'
};

const AudioPlayer = React.createClass({
  propTypes: {
    source: PropTypes.string.isRequired,
    sourceType: PropTypes.string.isRequired,
    playElement: PropTypes.object,
    pauseElement: PropTypes.object,
    autoPlay: PropTypes.any,
    onPlay: PropTypes.func
  },
  getInitialState() {
    return {
      fileFinishedDownloading: false,
      mediaDownloadProgressPercent: 0,
      mediaRequest: null,
      mediaFile: null,
      canPlay: false,
      paused: true,
      progressStyles: {}
    };
  },
  componentDidMount() {
    // The media is loaded as a blob to work around issues with Safari, for some reason,
    // not being able to play a wav file when it is an audio source. This makes no sense.
    // The other upside of having the file as a blob vs audio source is we can make
    // clicking the audio progress bar do a seek. For some reason, that only worked on
    // Firefox using an audio source.
    const mediaRequest = new XMLHttpRequest();
    this.setState({ mediaRequest });
    mediaRequest.open('GET', this.props.source, true);
    mediaRequest.responseType = 'blob';
    mediaRequest.onload = () => {
      const mediaFile = window.URL.createObjectURL(mediaRequest.response);
      this.setState({
        mediaFile,
        mediaRequest: null,
        fileFinishedDownloading: true,
        mediaDownloadProgressPercent: 0
      });
    };
    mediaRequest.onprogress = (e) => {
      this.setState({
        mediaDownloadProgressPercent: (e.loaded / e.total) * 100
      });
    };
    mediaRequest.send();
  },
  componentWillUnmount() {
    if (this.state.mediaRequest) {
      this.state.mediaRequest.abort();
    }
  },
  togglePlaying(e) {
    e.stopPropagation();
    e.preventDefault();
    if (this.refs.audioElement.paused) {
      this.refs.audioElement.play();
      this.setState({
        paused: false
      });
      if (this.props.onPlay) {
        this.props.onPlay();
      }
    } else {
      this.refs.audioElement.pause();
      this.setState({
        paused: true
      });
    }
  },
  setAudioProgress() {
    const progressStyles = {
      position: 'relative',
      display: 'inline-block',
      borderRight: '1px solid #777',
      height: '21px',
      padding: '0px',
      top: '-11px',
      left: '0'
    };

    const width = (
      this.refs.audioElement.currentTime / this.refs.audioElement.duration
    ) * 100;
    progressStyles.left = `${width}%`;
    if (width > 98) {
      this.setState({
        paused: true
      });
    }
    this.setState({ progressStyles });
  },
  replay(e) {
    e.stopPropagation();
    e.preventDefault();
    const x = e.pageX - e.target.offsetLeft;
    const howFarOverCursorX = Math.min((x / e.target.clientWidth), 1);
    const newDuration = howFarOverCursorX * this.refs.audioElement.duration;
    this.refs.audioElement.currentTime = newDuration;
    this.setState({
      paused: false
    });
  },
  onCanPlay() {
    this.setState({
      canPlay: true
    });
    if (this.props.autoPlay) {
      this.refs.audioElement.play();
      this.setState({
        paused: false
      });
    }
  },
  render() {
    const fileFinishedDownloading = this.state.fileFinishedDownloading;
    const mediaDownloadProgressPercent = this.state.mediaDownloadProgressPercent;
    const canPlay = this.state.canPlay;
    const paused = this.state.paused;
    const progressStyles = this.state.progressStyles;
    const mediaFile = this.state.mediaFile;
    const sourceType = this.state.sourceType;
    const playElement = this.props.playElement || defaultPlay;
    const pauseElement = this.props.pauseElement || defaultPause;

    const playPauseButtonInternals = paused ? playElement : pauseElement;

    const playPauseButton = (
      {playPauseButtonInternals}
    );

    const progressContainerStyles = audioProgressBarContainerStyles();
    const playProgress = (

);

    // audio player line is not even added until you press play and it fully loads
    let audioElement = null;

    if (!fileFinishedDownloading) {
      progressContainerStyles.width = `${mediaDownloadProgressPercent}%`;
    } else {
      progressContainerStyles.width = '100%';

      audioElement = (<audio onCanPlay={this.onCanPlay}
        onTimeUpdate={this.setAudioProgress}
        ref="audioElement">
        <source src={mediaFile} type={sourceType} />
      </audio>);
    }

    return (

        {audioElement}
        {playPauseButton}
        {playProgress}

    );
  }
});

module.exports = AudioPlayer;


text:
package com.google.cloud.kms.v1.stub.samples;

// [START cloudkms_v1_generated_KeyManagementServiceStubSettings_GetKeyRing_sync]
import com.google.cloud.kms.v1.stub.KeyManagementServiceStubSettings;
import java.time.Duration;

public class SyncGetKeyRing {

  public static void main(String[] args) throws Exception {
    syncGetKeyRing();
  }

  public static void syncGetKeyRing() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    KeyManagementServiceStubSettings.Builder keyManagementServiceSettingsBuilder =
        KeyManagementServiceStubSettings.newBuilder();
    keyManagementServiceSettingsBuilder
        .getKeyRingSettings()
        .setRetrySettings(
            keyManagementServiceSettingsBuilder.getKeyRingSettings().getRetrySettings().toBuilder()
                .setTotalTimeout(Duration.ofSeconds(30))
                .build());
    KeyManagementServiceStubSettings keyManagementServiceSettings =
        keyManagementServiceSettingsBuilder.build();
  }
}
// [END cloudkms_v1_generated_KeyManagementServiceStubSettings_GetKeyRing_sync]


text:
/**
 *
 */
package org.semanticweb.elk.reasoner.indexing.classes;

/*
 * #%L
 * ELK Reasoner
 * $Id:$
 * $HeadURL:$
 * %%
 * Copyright (C) 2011 - 2013 Department of Computer Science, University of Oxford
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

import org.semanticweb.elk.owl.interfaces.ElkAxiom;
import org.semanticweb.elk.owl.interfaces.ElkEquivalentObjectPropertiesAxiom;
import org.semanticweb.elk.owl.interfaces.ElkObjectPropertyRangeAxiom;
import org.semanticweb.elk.owl.interfaces.ElkReflexiveObjectPropertyAxiom;
import org.semanticweb.elk.owl.interfaces.ElkSubObjectPropertyOfAxiom;
import org.semanticweb.elk.owl.interfaces.ElkTransitiveObjectPropertyAxiom;
import org.semanticweb.elk.reasoner.incremental.AxiomLoadingListener;
import org.semanticweb.elk.reasoner.indexing.conversion.ElkAxiomConverter;

/**
 * A delegating visitor which notifies the provided
 * {@link AxiomLoadingListener} that some axiom represents a change
 * which cannot be processed incrementally by the reasoner
 *
 * @author Pavel Klinov
 *
 *         pavel.klinov@uni-ulm.de
 */
public class NonIncrementalElkAxiomVisitor extends DelegatingElkAxiomVisitor<Void>
		implements ElkAxiomConverter {

	private final AxiomLoadingListener<ElkAxiom> listener_;

	public NonIncrementalElkAxiomVisitor(ElkAxiomConverter visitor,
			AxiomLoadingListener<ElkAxiom> listener) {
		super(visitor);
		listener_ = listener;
	}

	@Override
	public Void visit(ElkEquivalentObjectPropertiesAxiom axiom) {
		listener_.notify(axiom);
		return super.visit(axiom);
	}

	@Override
	public Void visit(ElkReflexiveObjectPropertyAxiom axiom) {
		listener_.notify(axiom);
		return super.visit(axiom);
	}

	@Override
	public Void visit(ElkSubObjectPropertyOfAxiom axiom) {
		listener_.notify(axiom);
		return super.visit(axiom);
	}

	@Override
	public Void visit(ElkTransitiveObjectPropertyAxiom axiom) {
		listener_.notify(axiom);
		return super.visit(axiom);
	}

	@Override
	public Void visit(ElkObjectPropertyRangeAxiom axiom) {
		listener_.notify(axiom);
		return super.visit(axiom);
	}

}


text:
<?php declare(strict_types=1);

namespace PeeHaa\AsyncTwitter\Api\Request\User;

/**
 * @link https://dev.twitter.com/rest/reference/get/users/lookup
 */
class LookupByUserIds extends Lookup
{
    public function __construct(array $userIds)
    {
        parent::__construct();

        $this->parameters['user_id'] = implode(',', $userIds);
    }
}


text:
namespace mash {
namespace wm {
namespace {

enum class ShadowStyle {
  NORMAL,
  SMALL,
};

// LayoutManager associated with the window created by WindowTreeHost. Resizes
// all children of the parent to match the bounds of the parent. Additionally
// handles sizing of a Shadow.
class ContentWindowLayoutManager : public aura::LayoutManager {
 public:
  explicit ContentWindowLayoutManager(aura::Window* window,
                                      ShadowStyle style,
                                      Shadow* shadow)
      : window_(window), style_(style), shadow_(shadow) {
    OnWindowResized();
  }
  ~ContentWindowLayoutManager() override {}

 private:
  // Bounds for child windows.
  gfx::Rect child_bounds() const {
    return gfx::Rect(0, 0, window_->bounds().size().width(),
                     window_->bounds().size().height());
  }

  void UpdateChildBounds(aura::Window* child) {
    child->SetBounds(child_bounds());
  }

  // aura::LayoutManager:
  void OnWindowResized() override {
    for (aura::Window* child : window_->children())
      UpdateChildBounds(child);
    // Shadow takes care of resizing the layer appropriately.
    if (shadow_)
      shadow_->SetContentBounds(child_bounds());
  }
  void OnWindowAddedToLayout(aura::Window* child) override {
    UpdateChildBounds(child);
  }
  void OnWillRemoveWindowFromLayout(aura::Window* child) override {}
  void OnWindowRemovedFromLayout(aura::Window* child) override {}
  void OnChildWindowVisibilityChanged(aura::Window* child,
                                      bool visible) override {}
  void SetChildBounds(aura::Window* child,
                      const gfx::Rect& requested_bounds) override {
    SetChildBoundsDirect(child, requested_bounds);
  }

  aura::Window* window_;
  const ShadowStyle style_;
  Shadow* shadow_;

  DISALLOW_COPY_AND_ASSIGN(ContentWindowLayoutManager);
};

class WmNativeWidgetMus : public views::NativeWidgetMus {
 public:
  WmNativeWidgetMus(views::internal::NativeWidgetDelegate* delegate,
                    mojo::Connector* connector,
                    mus::Window* window)
      : NativeWidgetMus(delegate, connector, window,
                        mus::mojom::SurfaceType::UNDERLAY) {}
  ~WmNativeWidgetMus() override {
  }

  // NativeWidgetMus:
  views::NonClientFrameView* CreateNonClientFrameView() override {
    views::Widget* widget =
        static_cast<views::internal::NativeWidgetPrivate*>(this)->GetWidget();
    NonClientFrameViewMash* frame_view =
        new NonClientFrameViewMash(widget, window());
    move_event_handler_.reset(new MoveEventHandler(window(), GetNativeView()));
    return frame_view;
  }
  void InitNativeWidget(const views::Widget::InitParams& params) override {
    views::NativeWidgetMus::InitNativeWidget(params);
    aura::WindowTreeHost* window_tree_host = GetNativeView()->GetHost();
    // TODO(sky): shadow should be determined by window type and shadow type.
    shadow_.reset(new Shadow);
    shadow_->Init(Shadow::STYLE_INACTIVE);
    shadow_->Install(window());
    ContentWindowLayoutManager* layout_manager = new ContentWindowLayoutManager(
        window_tree_host->window(), ShadowStyle::NORMAL, shadow_.get());
    window_tree_host->window()->SetLayoutManager(layout_manager);
    const int inset = Shadow::GetInteriorInsetForStyle(Shadow::STYLE_ACTIVE);
    window_tree_host->SetOutputSurfacePadding(
        gfx::Insets(inset, inset, inset, inset));
    window_tree_host->window()->layer()->Add(shadow_->layer());
    shadow_->layer()->parent()->StackAtBottom(shadow_->layer());
  }
  void CenterWindow(const gfx::Size& size) override {
    // Do nothing. The client controls the size, not us.
  }
  void UpdateClientArea() override {
    // This pushes the client area to the WS. We don't want to do that as
    // the client area should come from the client, not us.
  }

 private:
  // The shadow, may be null.
  scoped_ptr<Shadow> shadow_;

  scoped_ptr<MoveEventHandler> move_event_handler_;

  DISALLOW_COPY_AND_ASSIGN(WmNativeWidgetMus);
};

class ClientViewMus : public views::ClientView {
 public:
  ClientViewMus(views::Widget* widget,
                views::View* contents_view,
                NonClientFrameController* frame_controller)
      : views::ClientView(widget, contents_view),
        frame_controller_(frame_controller) {}
  ~ClientViewMus() override {}

  // views::ClientView:
  bool CanClose() override {
    if (!frame_controller_->window())
      return true;

    frame_controller_->window()->RequestClose();
    return false;
  }

 private:
  NonClientFrameController* frame_controller_;

  DISALLOW_COPY_AND_ASSIGN(ClientViewMus);
};

}  // namespace

NonClientFrameController::NonClientFrameController(
    mojo::Connector* connector,
    mus::Window* window,
    mus::WindowManagerClient* window_manager_client)
    : widget_(new views::Widget), window_(window) {
  window_->AddObserver(this);

  views::Widget::InitParams params(views::Widget::InitParams::TYPE_WINDOW);
  // We initiate focus at the mus level, not at the views level.
  params.activatable = views::Widget::InitParams::ACTIVATABLE_NO;
  params.delegate = this;
  params.native_widget = new WmNativeWidgetMus(widget_, connector, window);
  widget_->Init(params);
  widget_->ShowInactive();

  const int shadow_inset =
      Shadow::GetInteriorInsetForStyle(Shadow::STYLE_ACTIVE);
  window_manager_client->SetUnderlaySurfaceOffsetAndExtendedHitArea(
      window, gfx::Vector2d(shadow_inset, shadow_inset),
      FrameBorderHitTestController::GetResizeOutsideBoundsSize());
}

// static
gfx::Insets NonClientFrameController::GetPreferredClientAreaInsets() {
  return NonClientFrameViewMash::GetPreferredClientAreaInsets();
}

// static
int NonClientFrameController::GetMaxTitleBarButtonWidth() {
  return NonClientFrameViewMash::GetMaxTitleBarButtonWidth();
}

NonClientFrameController::~NonClientFrameController() {
  if (window_)
    window_->RemoveObserver(this);
}

base::string16 NonClientFrameController::GetWindowTitle() const {
  if (!window_->HasSharedProperty(
          mus::mojom::WindowManager::kWindowTitle_Property)) {
    return base::string16();
  }

  return window_->GetSharedProperty<base::string16>(
      mus::mojom::WindowManager::kWindowTitle_Property);
}

views::View* NonClientFrameController::GetContentsView() {
  return this;
}

bool NonClientFrameController::CanResize() const {
  return window_ &&
         (GetResizeBehavior(window_) & mus::mojom::kResizeBehaviorCanResize) !=
             0;
}

bool NonClientFrameController::CanMaximize() const {
  return window_ &&
         (GetResizeBehavior(window_) &
          mus::mojom::kResizeBehaviorCanMaximize) != 0;
}

bool NonClientFrameController::CanMinimize() const {
  return window_ &&
         (GetResizeBehavior(window_) &
          mus::mojom::kResizeBehaviorCanMinimize) != 0;
}

views::ClientView* NonClientFrameController::CreateClientView(
    views::Widget* widget) {
  return new ClientViewMus(widget, GetContentsView(), this);
}

void NonClientFrameController::OnWindowSharedPropertyChanged(
    mus::Window* window,
    const std::string& name,
    const std::vector<uint8_t>* old_data,
    const std::vector<uint8_t>* new_data) {
  if (name == mus::mojom::WindowManager::kResizeBehavior_Property)
    widget_->OnSizeConstraintsChanged();
  else if (name == mus::mojom::WindowManager::kWindowTitle_Property)
    widget_->UpdateWindowTitle();
}

void NonClientFrameController::OnWindowDestroyed(mus::Window* window) {
  window_->RemoveObserver(this);
  window_ = nullptr;
}

}  // namespace wm
}  // namespace mash


text:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// Adding the Currency type to the Mongoose Schema types
require('mongoose-currency').loadType(mongoose);
var Currency = mongoose.Types.Currency;

// create promotion schema
var promotionSchema = new Schema({
    name: {
        type: String,
        required: true,
        unique: true
    },
    image: {
        type: String,
        required: true
    },
    label: {
        type: String,
        default:''
    },
    price: {
        type: Currency,
        required: true,
        min: 0
    },
    description: {
        type: String,
        required: true
    }
    }, {
        timestamps: true
    });

// Create a model
var Promotions = mongoose.model('Promotion', promotionSchema);

// make this available to our Node applications
module.exports = Promotions;


text:
import { moduleFor, test } from 'ember-qunit';

moduleFor('route:tables/table', 'Unit | Route | tables/table', {
  // Specify the other units that are required for this test.
  // needs: ['controller:foo']
});

test('it exists', function(assert) {
  var route = this.subject();
  assert.ok(route);
});


text:
const _       = require('lodash');
const fs      = require('fs-extra');
const util    = require('../util.js');
const Promise = require('bluebird');

const StockService = require('../stock/service');
const Crawler      = require('./crawler');
const Stock        = require('./stock');

const BASE_PATH = `${__dirname}/../../resources/industries`;
const ENTRIES_PATH = `${BASE_PATH}/entries.json`;
const LISTINGS_PATH = `${BASE_PATH}/listings`;

const extractSICsFromStocks = () => {
  return StockService.getStocksFromResources()
    .then((stocks) => {
      return _
        .chain(stocks)
        .map('sic')
        .uniq()
        .filter(_.isString)
        .filter(x => _.isNaN(parseInt(x)) === false)
        .sortBy()
        .value();
    })
};

const ensureDirectory = (pathname) => {
  return fs.pathExists(pathname)
    .then((exists) => {
      if(exists === false) {
        return fs.ensureDir(pathname);
      }
    });
};

const getEntries = () => {
  return fs.readJson(ENTRIES_PATH);
};

const saveEntries = (sics) => {
  return ensureDirectory(BASE_PATH)
    .then(() => {
      return getEntries().catch(() => { return {}; })
    })
    .then((currentEntries) => {
      const entries = _.map(sics, (sic) => {
        const entry = {};
        entry[sic] = {};

        return entry;
      });

      return _.assign(...entries, currentEntries);
    })
    .then((entries) => {
      return fs.writeJson(ENTRIES_PATH, entries);
    });
};

const updateEntriesByStocks = () => {
  return extractSICsFromStocks()
    .then(saveEntries)
};

const crawlEntries = (millisecondsDelay = 1000) => {
  return findNextPageEntry()
    .then((options) => {
      if(options) {
        console.log(`crawl entry of sic ${options.sic} with offset ${_.get(options, 'entry.stats.start')}`);
        return crawlEntry(options.sic, options.entry)
          .then(() => { return true; });
      }

      return false;
    })
    .then((crawled) => {
      if(crawled) {
        return Promise.delay(millisecondsDelay)
          .then(() => crawlEntries())
      }
    })
};

const findNextPageEntry = () => {
  return getEntries()
    .then((entries) => {
      const sic = _.findKey(entries, (entry) => {
        return _.has(entry, 'stats') === false ||
               _.get(entry, 'stats.hasNextPage', false);
      });

      if(sic) {
        return {
          sic,
          entry: entries[sic],
        };
      }
    })
};

const crawlEntry = (sic, entry = {}) => {
  const params = {
    sic,
    count: _.get(entry, 'stats.count', 100),
    start: 0,
  };

  if(_.has(entry, 'stats.start')) {
    params.start = entry.stats.start + params.count;
  }

  return Crawler.crawlCompanyPageBySIC(params)
    .then((response) => {
      return saveListing(sic, _.get(response, 'stocks.entries', []))
        .then(() => { return response; })
    })
    .then((response) => {
      const stats = {
        count: params.count,
        start: params.start,
        hasNextPage: _.get(response, 'hasNextPage'),
      };

      return setCrawlResultsToEntry(sic, stats)
        .then(() => { return response; })
    })
};

const getListing = (sic) => {
  return fs.readJson(`${LISTINGS_PATH}/${sic}.json`);
};

const saveListing = (sic, listing = []) => {
  return ensureDirectory(LISTINGS_PATH)
    .then(() => {
      return getListing(sic).catch(() => { return []; });
    })
    .then((currentListing) => {
      return fs.writeJson(`${LISTINGS_PATH}/${sic}.json`, [...currentListing , ...listing]);
    });
};

const setCrawlResultsToEntry = (sic, stats) => {
  return ensureDirectory(BASE_PATH)
    .then(() => {
      return getEntries().catch(() => { return {}; })
    })
    .then((entries) => {
      const entry = entries[sic];
      _.set(entry, 'stats', stats);
      return entries;
    })
    .then((entries) => {
      return fs.writeJson(ENTRIES_PATH, entries);
    });
};

const getStocksFromListings = () => {
  return getEntries()
    .then((entries) => {
      return _
        .chain(entries)
        .map((entry, sic) => {
          return require(`${LISTINGS_PATH}/${sic}.json`);
        })
        .flatten()
        .value();
    })
};

const crawlTitles = (millisecondsDelay = 1000) => {
  return findSicOfTitlelessEntry()
    .then((sic) => {
      if(_.isString(sic)) {
        console.log(`crawl title of sic ${sic}!`);
        return crawlTitle(sic)
          .then(() => { return true; });
      }

      return false;
    })
    .then((crawled) => {
      if(crawled) {
        return Promise.delay(millisecondsDelay)
          .then(() => crawlTitles())
      } else {
        console.log('All title crawled!');
      }
    })
};

const findSicOfTitlelessEntry = () => {
  return getEntries()
    .then((entries) => {
      return _.findKey(entries, (entry) => {
        return _.has(entry, 'title') === false;
      });
    })
};

const crawlTitle = (sic) => {
  return Crawler.crawlIndustryTitle(sic)
    .then((response) => {
      if(_.has(response, 'title')) {
        return saveTitleBySic(sic, response.title)
          .then(() => { return response; })
      }
    })
};

const saveTitleBySic = (sic, title) => {
  return getEntries()
    .then((entries) => {
      _.set(entries[sic], 'title', title);
      return entries;
    })
    .then((entries) => {
      return fs.writeJson(ENTRIES_PATH, entries);
    });
};

const getSicsOfSavedIndustryStockCrawls = () => {
  return util.getFiles(`${BASE_PATH}/stocks`)
    .then(files => _.map(files, file =>file.replace('.json', '')))
};

const getSicsOfUnsavedIndustryStockCrawls = () => {
  return getEntries()
    .then(_.keys)
    .then((sics) => {
      return getSicsOfSavedIndustryStockCrawls()
        .then((savedSics) => {
          return _.difference(sics, savedSics);
        })
    })
};

const createNextStocks = () => {
  return getSicsOfUnsavedIndustryStockCrawls()
    .then(_.first)
    .then((sic) => {
      if(sic) {
        console.log(`create stocks for industry ${sic}`);
        return Stock.createStocks(sic)
          .then(() => sic)
      }
    })
};

const crawlUnexploredStocks = () => {
  return getSicsOfSavedIndustryStockCrawls()
    .then(_.last)
    .then((sic) => {
      if(_.isString(sic)) {
        return Stock.crawlUnexploredStock(sic)
      }
    })
    .then(() => {
      return createNextStocks();
    })
    .then((nextSic) => {
      if(_.isString(nextSic)) {
        return crawlUnexploredStocks();
      }
    })
};

const filterInteractiveStocks = (minEntries) => {
  return getSicsOfSavedIndustryStockCrawls()
    // .then((sics) => {
    //   return _.slice(sics, 0, sics.length-1);
    // })
    .then((sics) => {
      const interActives = sics.map(sic => Stock.filterInteractiveStocks(sic, minEntries));
      return Promise.all(interActives);
    })
};

const filterInteractiveNotRegisteredStocks = (minEntries) => {
  return filterInteractiveStocks(minEntries)
    .then(_.flatten)
    .then((stocks) => {
      return StockService.getStocksFromResources()
        .then((resources) => {
          return _.map(resources, 'cik')
        })
        .then((ciks) => {
          return _.filter(_.values(stocks), (stock) => {
            return _.includes(ciks, stock.cik) === false;
          })
        })
    })
};

module.exports = {
  crawlEntry,
  crawlEntries,
  crawlTitles,
  crawlUnexploredStocks,
  extractSICsFromStocks,
  filterInteractiveStocks,
  filterInteractiveNotRegisteredStocks,
  getEntries,
  getListing,
  getSicsOfUnsavedIndustryStockCrawls,
  getStocksFromListings,
  saveEntries,
  updateEntriesByStocks,
};


text:
require 'spec_helper'

describe 'admin/people/new', :type => :view do
  before(:each) do
    assign(:person, stub_model(Person).as_new_record)
  end

  it 'renders new admin_person form' do
    render

    # Run the generator again with the --webrat flag if you want to use webrat matchers
    assert_select 'form[action=?][method=?]', admin_people_path, 'post' do
    end
  end
end


text:
package org.usfirst.frc5112.Magni.commands;

import edu.wpi.first.wpilibj.command.Command;
import org.usfirst.frc5112.Magni.Robot;

public class DriveTrainForward extends Command {

	public DriveTrainForward(double time) {
		super(time);
		requires(Robot.drivetrain);
	}

	protected void initialize() {
		Robot.drivetrain.forward(0.5);
	}

	protected void execute() {
	}

	protected boolean isFinished() {
		return isTimedOut();
	}

	protected void end() {
		Robot.drivetrain.stop();
	}

	protected void interrupted() {
		end();
	}
}


text:
<?php

class PHPParser_Tests_Builder_ParamTest extends PHPUnit_Framework_TestCase
{
    public function createParamBuilder($name) {
	return new PHPParser_Builder_Param($name);
    }

    /**
     * @dataProvider provideTestDefaultValues
     */
    public function testDefaultValues($value, $expectedValueNode) {
	$node = $this->createParamBuilder('test')
	    ->setDefault($value)
	    ->getNode()
	;

	$this->assertEquals($expectedValueNode, $node->default);
    }

    public function provideTestDefaultValues() {
	return array(
	    array(
		null,
		new PHPParser_Node_Expr_ConstFetch(new PHPParser_Node_Name('null'))
	    ),
	    array(
		true,
		new PHPParser_Node_Expr_ConstFetch(new PHPParser_Node_Name('true'))
	    ),
	    array(
		false,
		new PHPParser_Node_Expr_ConstFetch(new PHPParser_Node_Name('false'))
	    ),
	    array(
		31415,
		new PHPParser_Node_Scalar_LNumber(31415)
	    ),
	    array(
		3.1415,
		new PHPParser_Node_Scalar_DNumber(3.1415)
	    ),
	    array(
		'Hallo World',
		new PHPParser_Node_Scalar_String('Hallo World')
	    ),
	    array(
		array(1, 2, 3),
		new PHPParser_Node_Expr_Array(array(
		    new PHPParser_Node_Expr_ArrayItem(new PHPParser_Node_Scalar_LNumber(1)),
		    new PHPParser_Node_Expr_ArrayItem(new PHPParser_Node_Scalar_LNumber(2)),
		    new PHPParser_Node_Expr_ArrayItem(new PHPParser_Node_Scalar_LNumber(3)),
		))
	    ),
	    array(
		array('foo' => 'bar', 'bar' => 'foo'),
		new PHPParser_Node_Expr_Array(array(
		    new PHPParser_Node_Expr_ArrayItem(
			new PHPParser_Node_Scalar_String('bar'),
			new PHPParser_Node_Scalar_String('foo')
		    ),
		    new PHPParser_Node_Expr_ArrayItem(
			new PHPParser_Node_Scalar_String('foo'),
			new PHPParser_Node_Scalar_String('bar')
		    ),
		))
	    ),
	    array(
		new PHPParser_Node_Scalar_DirConst,
		new PHPParser_Node_Scalar_DirConst
	    )
	);
    }

    public function testTypeHints() {
	$node = $this->createParamBuilder('test')
	    ->setTypeHint('array')
	    ->getNode()
	;

	$this->assertEquals(
	    new PHPParser_Node_Param('test', null, 'array'),
	    $node
	);

	$node = $this->createParamBuilder('test')
	    ->setTypeHint('callable')
	    ->getNode()
	;

	$this->assertEquals(
	    new PHPParser_Node_Param('test', null, 'callable'),
	    $node
	);

	$node = $this->createParamBuilder('test')
	    ->setTypeHint('Some\Class')
	    ->getNode()
	;

	$this->assertEquals(
	    new PHPParser_Node_Param('test', null, new PHPParser_Node_Name('Some\Class')),
	    $node
	);
    }

    public function testByRef() {
	$node = $this->createParamBuilder('test')
	    ->makeByRef()
	    ->getNode()
	;

	$this->assertEquals(
	    new PHPParser_Node_Param('test', null, null, true),
	    $node
	);
    }
}


text:
import logging
import os
import yaml

from google.cloud import datastore
from googleapiclient import http

class LoggingHttpMockSequence(http.HttpMockSequence):
    """Log the mock request and responses for debugging purposes."""

    def __init__(self, iterable):
        """Construct from a list of request response pairs.

        Args:
            iterable: iterable, a sequence of pairs of (headers, body)
        """
        super(LoggingHttpMockSequence, self).__init__(iterable)
        self.requests = []

    def request(self,
                uri,
                method='GET',
                body=None,
                headers=None,
                redirections=1,
                connection_type=None):
        """Override to log request and response."""

        self.requests.append((uri, method, body, headers))
        logging.debug('mock request: request(%s, %s, %s, %s, %s, %s)', method,
                      uri, body, headers, redirections, connection_type)
        response, content = super(LoggingHttpMockSequence, self).request(
            uri, method, body, headers, redirections, connection_type)
        logging.debug('mock response %s, %s', response, content[:200])

        return response, content

def read_data_files(files):
    """Read in all files and provide a map of the results keyed by filename."""
    read_files = dict()
    for f in files:
        with open(f, 'rb') as of:
            read_files[os.path.basename(f)] = of.read()
    return read_files

def config_entity():
    config = None
    with open('tests/data/config-default-zone.yaml') as f:
        config = yaml.load(f.read())
        entity = datastore.Entity()
        entity.update(config)
    return entity


text:
<?php
				$singlepage = mysqld_select("SELECT * FROM " . table('addon9_singlepage')." where id=:id ",array(":id"=>intval($_GP['id'])) );
				$cfg=globaSetting();
  	 		include addons_page('singlepage');