text:
package com.google.cloud.dataflow.sdk.transforms.windowing;

import static com.google.cloud.dataflow.sdk.util.Structs.addString;
import static com.google.cloud.dataflow.sdk.util.TimeUtil.fromCloudDuration;
import static com.google.cloud.dataflow.sdk.util.TimeUtil.toCloudDuration;

import com.google.cloud.dataflow.sdk.coders.AtomicCoder;
import com.google.cloud.dataflow.sdk.coders.Coder;
import com.google.cloud.dataflow.sdk.coders.CoderException;
import com.google.cloud.dataflow.sdk.coders.InstantCoder;
import com.google.cloud.dataflow.sdk.util.CloudObject;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

import org.joda.time.Duration;
import org.joda.time.Instant;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * An implementation of {@link BoundedWindow} that represents an interval from
 * {@link #start} (inclusive) to {@link #end} (exclusive).
 */
public class IntervalWindow extends BoundedWindow
    implements Comparable<IntervalWindow> {
  /**
   * Start of the interval, inclusive.
   */
  private final Instant start;

  /**
   * End of the interval, exclusive.
   */
  private final Instant end;

  /**
   * Creates a new IntervalWindow that represents the half-open time
   * interval [start, end).
   */
  public IntervalWindow(Instant start, Instant end) {
    this.start = start;
    this.end = end;
  }

  public IntervalWindow(Instant start, Duration size) {
    this.start = start;
    this.end = start.plus(size);
  }

  /**
   * Returns the start of this window, inclusive.
   */
  public Instant start() {
    return start;
  }

  /**
   * Returns the end of this window, exclusive.
   */
  public Instant end() {
    return end;
  }

  /**
   * Returns the largest timestamp that can be included in this window.
   */
  @Override
  public Instant maxTimestamp() {
    // end not inclusive
    return end.minus(1);
  }

  /**
   * Returns whether this window contains the given window.
   */
  public boolean contains(IntervalWindow other) {
    return !this.start.isAfter(other.start) && !this.end.isBefore(other.end);
  }

  /**
   * Returns whether this window is disjoint from the given window.
   */
  public boolean isDisjoint(IntervalWindow other) {
    return !this.end.isAfter(other.start) || !other.end.isAfter(this.start);
  }

  /**
   * Returns whether this window intersects the given window.
   */
  public boolean intersects(IntervalWindow other) {
    return !isDisjoint(other);
  }

  /**
   * Returns the minimal window that includes both this window and
   * the given window.
   */
  public IntervalWindow span(IntervalWindow other) {
    return new IntervalWindow(
        new Instant(Math.min(start.getMillis(), other.start.getMillis())),
        new Instant(Math.max(end.getMillis(), other.end.getMillis())));
  }

  @Override
  public boolean equals(Object o) {
    return (o instanceof IntervalWindow)
        && ((IntervalWindow) o).end.isEqual(end)
        && ((IntervalWindow) o).start.isEqual(start);
  }

  @Override
  public int hashCode() {
    // The end values are themselves likely to be arithmetic sequence, which
    // is a poor distribution to use for a hashtable, so we
    // add a highly non-linear transformation.
    return (int)
        (start.getMillis() + modInverse((int) (end.getMillis() << 1) + 1));
  }

  /**
   * Compute the inverse of (odd) x mod 2^32.
   */
  private int modInverse(int x) {
    // Cube gives inverse mod 2^4, as x^4 == 1 (mod 2^4) for all odd x.
    int inverse = x * x * x;
    // Newton iteration doubles correct bits at each step.
    inverse *= 2 - x * inverse;
    inverse *= 2 - x * inverse;
    inverse *= 2 - x * inverse;
    return inverse;
  }

  @Override
  public String toString() {
    return "[" + start + ".." + end + ")";
  }

  @Override
  public int compareTo(IntervalWindow o) {
    if (start.isEqual(o.start)) {
      return end.compareTo(o.end);
    }
    return start.compareTo(o.start);
  }

  /**
   * Returns a Coder suitable for encoding IntervalWindows.
   */
  public static Coder<IntervalWindow> getCoder() {
    return IntervalWindowCoder.of();
  }

  /**
   * Returns a Coder for encoding interval windows of fixed size (which
   * is more efficient than {@link #getCoder()} as it only needs to encode
   * one endpoint).
   */
  public static Coder<IntervalWindow> getFixedSizeCoder(final Duration size) {
    return FixedSizeIntervalWindowCoder.of(size);
  }

  @SuppressWarnings("serial")
  private static class IntervalWindowCoder extends AtomicCoder<IntervalWindow> {
    private static final IntervalWindowCoder INSTANCE =
        new IntervalWindowCoder();
    private static final Coder<Instant> instantCoder = InstantCoder.of();

    @JsonCreator
    public static IntervalWindowCoder of() {
      return INSTANCE;
    }

    @Override
    public void encode(IntervalWindow window,
                       OutputStream outStream,
                       Context context)
        throws IOException, CoderException {
      instantCoder.encode(window.start, outStream, context.nested());
      instantCoder.encode(window.end, outStream, context.nested());
    }

    @Override
    public IntervalWindow decode(InputStream inStream, Context context)
        throws IOException, CoderException {
      Instant start = instantCoder.decode(inStream, context.nested());
      Instant end = instantCoder.decode(inStream, context.nested());
      return new IntervalWindow(start, end);
    }

    @Override
    public boolean isDeterministic() { return true; }
  }

  @SuppressWarnings("serial")
  private static class FixedSizeIntervalWindowCoder
      extends AtomicCoder<IntervalWindow> {
    private static final Coder<Instant> instantCoder = InstantCoder.of();

    private final Duration size;

    @JsonCreator
    public static FixedSizeIntervalWindowCoder of(
        @JsonProperty("duration") String duration) {
      return of(fromCloudDuration(duration));
    }

    public static FixedSizeIntervalWindowCoder of(Duration size) {
      return new FixedSizeIntervalWindowCoder(size);
    }

    private FixedSizeIntervalWindowCoder(Duration size) {
      this.size = size;
    }

    @Override
    public void encode(IntervalWindow window,
                       OutputStream outStream,
                       Context context)
        throws IOException, CoderException {
      instantCoder.encode(window.start, outStream, context);
    }

    @Override
    public IntervalWindow decode(InputStream inStream, Context context)
        throws IOException, CoderException {
      Instant start = instantCoder.decode(inStream, context);
      return new IntervalWindow(start, size);
    }

    @Override
    public boolean isDeterministic() { return true; }

    @Override
    public CloudObject asCloudObject() {
      CloudObject result = super.asCloudObject();
      addString(result, "duration", toCloudDuration(Duration.millis(size.getMillis())));
      return result;
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
"""Module for constructing
 tag."""

from __future__ import absolute_import

from ...lib.utils import validate_attribute_values
from ...templates.html.tags import hr

ATTRIBUTES = {
    'align': {
        'description': 'Specifies the alignment of a
 element',
        'values': ['left', 'center', 'right']
    },
    'noshade': {
        'description': 'Specifies that a
 element should render in'
                       ' one solid color (noshaded), instead of a '
                       'shaded color',
        'values': None
    },
    'size': {
        'description': 'Specifies the height of a
 element',
        'values': None
    },
    'width': {
        'description': 'Specifies the width of a
 element',
        'values': None
    }
}

class HR(object):
    """Class for constructing hr tag.

    Args:
        align (str): Specifies the alignment of a
 element.
        noshade (bool): Specifies that a
 element should render in one
            solid color (noshaded), instead of a shaded color.
        size (str): Specifies the height of a
 element.
        width (str): Specifies the width of a
 element

    .. versionadded:: 0.3.0
    """
    def __init__(self, align=None, noshade=False, size=None, width=None):
        self.tag = 'hr'
        validate_attribute_values(tag=self.tag,
                                  attribute_name='align',
                                  attribute_value=align,
                                  default_values=ATTRIBUTES['align']['values'])
        self.values = {'align': align,
                       'noshade': noshade,
                       'size': size,
                       'width': width}

    def construct(self):
        """Returns the constructed hr tag
."""
        return hr.render(self.values)


text:
package de.theoptik.doe.players;

import java.util.List;

import de.theoptik.doe.Board;
import de.theoptik.doe.Move;
import de.theoptik.doe.MoveGenerator;
import de.theoptik.doe.Player;

public class RandomPlayer extends AbstractPlayer {

	public RandomPlayer(Player player) {
		super(player);
	}

	@Override
	public Move getMove(Board board) {

		MoveGenerator generator = new MoveGenerator(board);

		List<Move> moves = generator.getAllMoves();
		if (moves.size() > 0) {
			return moves.get((int) (Math.random() * moves.size()));
		} else {
			return null;
		}
	}

}


text:
namespace xml2ps {

struct Part {
  Part(Glib::ustring _text, Glib::ustring _fontname, float _fontsize,
       float _x, float _y,
       Gdk::Color &_color)
    :text(_text), fontname(_fontname), fontsize(_fontsize),
     x(_x), y(_y), color(_color)
  {}
  Glib::ustring text, fontname;
  float fontsize, x, y;
  Gdk::Color color;
  float width;
};
typedef std::vector<Part> Parts;

class XCanvas: public Canvas, public sigc::trackable {
public:
  explicit XCanvas(const PageVec& pages, bool allow_extra_pages);
  virtual ~XCanvas();

  virtual void newPage();
  virtual void closePage() {}

  virtual void setgray(float gray);
  virtual void setfont(const font::FontInfo& font);
  virtual void moveto(float hpos, float vpos);

  virtual float textRise(float rise);
  virtual float getRise() const;

  virtual void setWordSpace(const float& space);

  virtual void show(const Glib::ustring& text);
  virtual void whitespace();
  virtual void whitespace(const float& space);

  virtual void underlineFrom(const float& below);
  virtual void underlineTo(const float& below, const float& thickness);

  virtual void line(float x1, float y1, float x2, float y2);

  float p2s(float length); // paper length to screen length

protected:
  float res; // screen resolution in pixels per inch
  Parts parts;
  Gtk::Window *window;
  Gtk::Main *kit;
  Gnome::Canvas::Canvas *canvas;
  //  Gnome::Canvas::Group canvasgroup;
  Gdk::Color color;
  float x, y;
  const font::FontInfo *current_font;

  bool draw(GdkEventExpose*);
};

};

#endif


text:
import * as React from 'react';
import ReactNativeAndroidTaskDescription from 'react-native-android-taskdescription';

const test: React.SFC = () => (
    <ReactNativeAndroidTaskDescription
        label="React native android task description"
        backgroundColor="#112233"
    />
);


text:
package org.apache.directory.shared.kerberos.codec.EncKdcRepPart.actions;

import org.apache.directory.shared.kerberos.KerberosTime;
import org.apache.directory.shared.kerberos.codec.EncKdcRepPart.EncKdcRepPartContainer;
import org.apache.directory.shared.kerberos.codec.actions.AbstractReadKerberosTime;

/**
 * The action used to store the EncKdcRepPart renew till
 *
 * @author Apache Directory Project
 */
public class StoreRenewTill extends AbstractReadKerberosTime<EncKdcRepPartContainer>
{

    /**
     * Instantiates a new StoreRenewTill action.
     */
    public StoreRenewTill()
    {
        super( "EncKdcRepPart renew till" );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void setKerberosTime( KerberosTime krbtime, EncKdcRepPartContainer encKdcRepPartContainer )
    {
        encKdcRepPartContainer.getEncKdcRepPart().setRenewTill( krbtime );
    }
}


text:
import sys
import os
import threading
import json

current_path = os.path.dirname(os.path.abspath(__file__))
root_path = os.path.abspath( os.path.join(current_path, os.pardir, os.pardir, os.pardir))
local_path = os.path.abspath( os.path.join(current_path, os.pardir))
data_path = os.path.abspath(os.path.join(root_path, os.pardir, os.pardir, 'data'))
module_data_path = os.path.join(data_path, 'x_tunnel')
python_path = root_path

if __name__ == "__main__":
    sys.path.append(root_path)
    sys.path.append(local_path)

    noarch_lib = os.path.abspath( os.path.join(python_path, 'lib', 'noarch'))
    sys.path.append(noarch_lib)

    if sys.platform == "win32":
        win32_lib = os.path.abspath( os.path.join(python_path, 'lib', 'win32'))
        sys.path.append(win32_lib)
    elif sys.platform.startswith("linux"):
        linux_lib = os.path.abspath( os.path.join(python_path, 'lib', 'linux'))
        sys.path.append(linux_lib)
    elif sys.platform == "darwin":
        darwin_lib = os.path.abspath( os.path.join(python_path, 'lib', 'darwin'))
        sys.path.append(darwin_lib)
        extra_lib = "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python"
        sys.path.append(extra_lib)

import utils
import xlog
logger = xlog.getLogger("cloudflare_front")
logger.set_buffer(500)

from front_base.openssl_wrap import SSLContext
from front_base.connect_creator import ConnectCreator
from front_base.check_ip import CheckIp
from front_base.host_manager import HostManagerBase

from cloudflare_front.config import Config
from cloudflare_front import front

def check_all_domain(check_ip):
    with open(os.path.join(current_path, "front_domains.json"), "r") as fd:
        content = fd.read()
        cs = json.loads(content)
        for host in cs:
            host = "scan1." + host
            res = check_ip.check_ip(ip, host=host, wait_time=wait_time)
            if not res or not res.ok:
                xlog.warn("host:%s fail", host)
            else:
                xlog.info("host:%s ok", host)

class CheckAllIp(object):
    def __init__(self, check_ip, host):
        self.check_ip = check_ip
        self.host = host
        self.lock = threading.Lock()

        self.in_fd = open("good_ip.txt", "r")
        self.out_fd = open(
            os.path.join(module_data_path, "cloudflare_checked_ip.txt"),
            "w"
        )

    def get_ip(self):
        with self.lock:
            while True:
                line = self.in_fd.readline()
                if not line:
                    raise Exception()

                try:
                    ip = line.split()[0]
                    return ip
                except:
                    continue

    def write_ip(self, ip, host, handshake):
        with self.lock:
            self.out_fd.write("%s %s gws %d 0 0\n" % (ip, host, handshake))
            self.out_fd.flush()

    def checker(self):
        while True:
            try:
                ip = self.get_ip()
            except Exception as e:
                xlog.info("no ip left")
                return

            try:
                res = self.check_ip.check_ip(ip, sni=host, host=host)
            except Exception as e:
                xlog.warn("check fail:%s except:%r", e)
                continue

            if not res or not res.ok:
                xlog.debug("check fail:%s fail", ip)
                continue

            self.write_ip(ip, res.domain, res.handshake_time)

    def run(self):
        for i in range(0, 10):
            threading.Thread(target=self.checker).start()

def check_all_ip(check_ip):
    check = CheckAllIp(check_ip, "scan1.movistar.gq")
    check.run()

if __name__ == "__main__":
    # format: [ip] [domain [sni] ]

    # case 1: only ip
    # case 2: ip domain
    # case 3: ip domain sni
    # case 4: domain
    # case 5: domain sni

    ip = "141.101.120.131"
    host = "v3.freena.cf"
    sni = host

    args = list(sys.argv[1:])

    if len(args):
        if utils.check_ip_valid(args[0]):
            ip = args.pop(0)

    if len(args):
        host = args.pop(0)
        sni = host

    if len(args):
        sni = args.pop(0)

    # print("Usage: check_ip.py [ip] [top_domain] [wait_time=0]")
    xlog.info("test ip:%s", ip)
    xlog.info("host:%s", host)
    xlog.info("sni:%s", sni)

    wait_time = 0

    config_path = os.path.join(module_data_path, "cloudflare_front.json")
    config = Config(config_path)

    ca_certs = os.path.join(current_path, "cacert.pem")
    openssl_context = SSLContext(logger, ca_certs=ca_certs)
    host_manager = HostManagerBase()
    connect_creator = ConnectCreator(logger, config, openssl_context, host_manager, debug=True)
    check_ip = CheckIp(logger, config, connect_creator)

    #check_all_domain(check_ip)
    #check_all_ip(check_ip)

    res = check_ip.check_ip(ip, sni=sni, host=host, wait_time=wait_time)
    if not res:
        xlog.warn("connect fail")
    elif res.ok:
        xlog.info("success, domain:%s handshake:%d", res.host, res.handshake_time)
    else:
        xlog.warn("not support")

    front.stop()
    sys.exit(0)
    exit(0)


text:
<?php

namespace ZendTest\Mvc\Controller\Plugin;

use PHPUnit_Framework_TestCase as TestCase;
use Zend\Form\Form;
use Zend\Http\Request;
use Zend\Http\Response;
use Zend\InputFilter\InputFilter;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Zend\Mvc\Router\Http\Literal as LiteralRoute;
use Zend\Mvc\Router\Http\Segment as SegmentRoute;
use Zend\Mvc\Router\RouteMatch;
use Zend\Mvc\Router\SimpleRouteStack;
use Zend\Stdlib\Parameters;
use ZendTest\Mvc\Controller\TestAsset\SampleController;
use ZendTest\Session\TestAsset\TestManager as SessionManager;

class FilePostRedirectGetTest extends TestCase
{
    public $form;
    public $controller;
    public $event;
    public $request;
    public $response;

    public function setUp()
    {
        $this->form = new Form();

        $router = new SimpleRouteStack;
        $router->addRoute('home', LiteralRoute::factory(array(
            'route'    => '/',
            'defaults' => array(
                'controller' => 'ZendTest\Mvc\Controller\TestAsset\SampleController',
            )
        )));

        $router->addRoute('sub', SegmentRoute::factory(array(
            'route' => '/foo/:param',
            'defaults' => array(
                'param' => 1
            )
        )));

        $router->addRoute('ctl', SegmentRoute::factory(array(
            'route' => '/ctl/:controller',
            'defaults' => array(
                '__NAMESPACE__' => 'ZendTest\Mvc\Controller\TestAsset',
            )
        )));

        $this->controller = new SampleController();
        $this->request    = new Request();
        $this->event      = new MvcEvent();
        $this->routeMatch = new RouteMatch(array('controller' => 'controller-sample', 'action' => 'postPage'));

        $this->event->setRequest($this->request);
        $this->event->setRouteMatch($this->routeMatch);
        $this->event->setRouter($router);

        $this->sessionManager = new SessionManager();
        $this->sessionManager->destroy();

        $this->controller->setEvent($this->event);
        $this->controller->flashMessenger()->setSessionManager($this->sessionManager);
    }

    public function testReturnsFalseOnIntialGet()
    {
        $result    = $this->controller->dispatch($this->request, $this->response);
        $prgResult = $this->controller->fileprg($this->form, 'home');

        $this->assertFalse($prgResult);
    }

    public function testRedirectsToUrlOnPost()
    {
        $this->request->setMethod('POST');
        $this->request->setPost(new Parameters(array(
            'postval1' => 'value'
        )));

        $this->controller->dispatch($this->request, $this->response);
        $prgResultUrl = $this->controller->fileprg($this->form, '/test/getPage', true);

        $this->assertInstanceOf('Zend\Http\Response', $prgResultUrl);
        $this->assertTrue($prgResultUrl->getHeaders()->has('Location'));
        $this->assertEquals('/test/getPage', $prgResultUrl->getHeaders()->get('Location')->getUri());
        $this->assertEquals(303, $prgResultUrl->getStatusCode());
    }

    public function testRedirectsToRouteOnPost()
    {
        $this->request->setMethod('POST');
        $this->request->setPost(new Parameters(array(
            'postval1' => 'value1'
        )));

        $this->controller->dispatch($this->request, $this->response);
        $prgResultRoute = $this->controller->fileprg($this->form, 'home');

        $this->assertInstanceOf('Zend\Http\Response', $prgResultRoute);
        $this->assertTrue($prgResultRoute->getHeaders()->has('Location'));
        $this->assertEquals('/', $prgResultRoute->getHeaders()->get('Location')->getUri());
        $this->assertEquals(303, $prgResultRoute->getStatusCode());
    }

    /**
     * @expectedException Zend\Mvc\Exception\RuntimeException
     */
    public function testThrowsExceptionOnRouteWithoutRouter()
    {
        $controller = $this->controller;
        $controller = $controller->getEvent()->setRouter(new SimpleRouteStack);

        $this->request->setMethod('POST');
        $this->request->setPost(new Parameters(array(
            'postval1' => 'value'
        )));

        $this->controller->dispatch($this->request, $this->response);
        $this->controller->fileprg($this->form, 'some/route');
    }

    public function testNullRouteUsesMatchedRouteName()
    {
        $this->controller->getEvent()->getRouteMatch()->setMatchedRouteName('home');

        $this->request->setMethod('POST');
        $this->request->setPost(new Parameters(array(
            'postval1' => 'value1'
        )));

        $this->controller->dispatch($this->request, $this->response);
        $prgResultRoute = $this->controller->fileprg($this->form);

        $this->assertInstanceOf('Zend\Http\Response', $prgResultRoute);
        $this->assertTrue($prgResultRoute->getHeaders()->has('Location'));
        $this->assertEquals('/', $prgResultRoute->getHeaders()->get('Location')->getUri());
        $this->assertEquals(303, $prgResultRoute->getStatusCode());
    }

    public function testReuseMatchedParameters()
    {
        $this->controller->getEvent()->getRouteMatch()->setMatchedRouteName('sub');

        $this->request->setMethod('POST');
        $this->request->setPost(new Parameters(array(
            'postval1' => 'value1'
        )));

        $this->controller->dispatch($this->request, $this->response);
        $prgResultRoute = $this->controller->fileprg($this->form);

        $this->assertInstanceOf('Zend\Http\Response', $prgResultRoute);
        $this->assertTrue($prgResultRoute->getHeaders()->has('Location'));
        $this->assertEquals('/foo/1', $prgResultRoute->getHeaders()->get('Location')->getUri());
        $this->assertEquals(303, $prgResultRoute->getStatusCode());
    }

    public function testReturnsPostOnRedirectGet()
    {
        // Do POST
        $params = array(
            'postval1' => 'value'
        );
        $this->request->setMethod('POST');
        $this->request->setPost(new Parameters($params));

        $this->form->add(array(
            'name' => 'postval1'
        ));

        $this->controller->dispatch($this->request, $this->response);
        $prgResultUrl = $this->controller->fileprg($this->form, '/test/getPage', true);

        $this->assertInstanceOf('Zend\Http\Response', $prgResultUrl);
        $this->assertTrue($prgResultUrl->getHeaders()->has('Location'));
        $this->assertEquals('/test/getPage', $prgResultUrl->getHeaders()->get('Location')->getUri());
        $this->assertEquals(303, $prgResultUrl->getStatusCode());

        // Do GET
        $this->request = new Request();
        $this->controller->dispatch($this->request, $this->response);
        $prgResult = $this->controller->fileprg($this->form, '/test/getPage', true);

        $this->assertEquals($params, $prgResult);
        $this->assertEquals($params['postval1'], $this->form->get('postval1')->getValue());

        // Do GET again to make sure data is empty
        $this->request = new Request();
        $this->controller->dispatch($this->request, $this->response);
        $prgResult = $this->controller->fileprg($this->form, '/test/getPage', true);

        $this->assertFalse($prgResult);
    }

    public function testAppliesFormErrorsOnPostRedirectGet()
    {
        // Do POST
        $params = array();
        $this->request->setMethod('POST');
        $this->request->setPost(new Parameters($params));

        $this->form->add(array(
            'name' => 'postval1'
        ));
        $inputFilter = new InputFilter();
        $inputFilter->add(array(
            'name'     => 'postval1',
            'required' => true,
        ));
        $this->form->setInputFilter($inputFilter);

        $this->controller->dispatch($this->request, $this->response);
        $prgResultUrl = $this->controller->fileprg($this->form, '/test/getPage', true);
        $this->assertInstanceOf('Zend\Http\Response', $prgResultUrl);
        $this->assertTrue($prgResultUrl->getHeaders()->has('Location'));
        $this->assertEquals('/test/getPage', $prgResultUrl->getHeaders()->get('Location')->getUri());
        $this->assertEquals(303, $prgResultUrl->getStatusCode());

        // Do GET
        $this->request = new Request();
        $this->controller->dispatch($this->request, $this->response);
        $prgResult = $this->controller->fileprg($this->form, '/test/getPage', true);
        $messages  = $this->form->getMessages();

        $this->assertEquals($params, $prgResult);
        $this->assertNotEmpty($messages['postval1']['isEmpty']);
    }

    public function testReuseMatchedParametersWithSegmentController()
    {
        $expects = '/ctl/sample';
        $this->request->setMethod('POST');
        $this->request->setUri($expects);
        $this->request->setPost(new Parameters(array(
            'postval1' => 'value1'
        )));

        $routeMatch = $this->event->getRouter()->match($this->request);
        $this->event->setRouteMatch($routeMatch);

        $moduleRouteListener = new ModuleRouteListener;
        $moduleRouteListener->onRoute($this->event);

        $this->controller->dispatch($this->request, $this->response);
        $prgResultRoute = $this->controller->fileprg($this->form);

        $this->assertInstanceOf('Zend\Http\Response', $prgResultRoute);
        $this->assertTrue($prgResultRoute->getHeaders()->has('Location'));
        $this->assertEquals($expects, $prgResultRoute->getHeaders()->get('Location')->getUri() , 'redirect to the same url');
        $this->assertEquals(303, $prgResultRoute->getStatusCode());
    }
}


text:
// Copyright (C) 2013 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 12.12.3
description: >
    "Logical OR" Symbol evaluation
---*/
var sym = Symbol();

assert.sameValue(!sym || true, true, "`!sym || true` is `true`");
assert.sameValue(sym || false, sym, "`sym || false` is `sym`");


text:
package petablox.analyses.alias;

import java.io.Serializable;

import petablox.util.soot.SootUtilities;
import soot.Unit;

/**
 * Representation of an abstract context of a method.
 *

 * Each abstract context is a possibly empty sequence of the form
 * <tt>[e1,...,en]</tt> where each <tt>ei</tt> is either an object
 * allocation statement or a method invocation statement in
 * decreasing order of significance.
 *

 * The abstract context corresponding to the empty sequence, called
 * <tt>epsilon</tt>, is the lone context of methods that are
 * analyzed context insensitively.  These include the main method,
 * all class initializer methods, and any additional user-specified
 * methods (see {@link petablox.analyses.alias.CtxtsAnalysis}).
 *
 * @author Mayur Naik (mhn@cs.stanford.edu)
 */
public class Ctxt implements Serializable {
    /**
     * The sequence of statements comprising the abstract context, in decreasing order of significance.
     */
    private final Unit[] elems;
    /**
     * Constructor.
     *
     * @param elems The sequence of statements comprising this abstract context.
     */
    public Ctxt(Unit[] elems) {
        this.elems = elems;
    }
    /**
     * Provides the sequence of statements comprising this abstract context.
     *
     * @return The sequence of statements comprising this abstract context.
     */
    public Unit[] getElems() {
        return elems;
    }
    /**
     * Determines whether this abstract context contains a given statement.
     *
     * @param inst A statement.
     *
     * @return true iff this abstract context contains the given statement.
     */
    public boolean contains(Unit inst) {
        for (int i = 0; i < elems.length; i++) {
            if (elems[i] == inst)
                return true;
        }
        return false;
    }
  public int count(Unit inst) {
    int n = 0;
        for (int i = 0; i < elems.length; i++) {
            if (elems[i] == inst)
        n++;
        }
    return n;
  }
    public int hashCode() {
        int i = 5381;
        for (Unit inst : elems) {
            int q = inst == null ? 9999 : SootUtilities.getID(inst);
            i = ((i << 5) + i) + q; // i*33 + q
        }
        return i;
    }
    public boolean equals(Object o) {
        if (!(o instanceof Ctxt))
            return false;
        Ctxt that = (Ctxt) o;
        Unit[] thisElems = this.elems;
        Unit[] thatElems = that.elems;
        int n = thisElems.length;
        if (thatElems.length != n)
            return false;
        for (int i = 0; i < n; i++) {
            Unit inst = thisElems[i];
            if (inst != thatElems[i])
                return false;
        }
        return true;
    }
    public String toString() {
        String s = "[";
        int n = elems.length;
        for (int i = 0; i < n; i++) {
            Unit q = elems[i];
            s += q == null ? "null" : SootUtilities.toByteLocStr(q);
            if (i < n - 1)
                s += ",";
        }
        return s + "]";
    }

    //PRT added from stamp
    public String toString(boolean asCtxtObj) {
		StringBuilder builder = new StringBuilder("[");
		boolean first = true;
		// If this is a contextified abstract object, skip the first element,
		// i.e. the allocation statement that identifies the object.
        for (int i = asCtxtObj ? 1 : 0; i < elems.length; i++) {
			Unit inst = elems[i];
			if(!first) {
				builder.append(',');
			} else {
				first = false;
			}
			builder.append(inst == null ? "null"
						   : SootUtilities.toByteLocStr(inst));
		}
		builder.append(']');
		if (asCtxtObj) {
			builder.append(':');
			builder.append(SootUtilities.toByteLocStr(elems[0]));
		}
		return builder.toString();
	}

  public int length() { return elems.length; }
  public Unit get(int i) { return elems[i]; }
  public Unit head() { return elems[0]; }
  public Unit last() { return elems[elems.length-1]; }
  public Ctxt tail() { return suffix(elems.length-1); }
  public Ctxt prefix(int k) {
    if (k >= elems.length) return this;
    Unit[] newElems = new Unit[k];
    if (k > 0) System.arraycopy(elems, 0, newElems, 0, k);
    return new Ctxt(newElems);
  }
  public Ctxt suffix(int k) {
    if (k >= elems.length) return this;
    Unit[] newElems = new Unit[k];
    if (k > 0) System.arraycopy(elems, elems.length-k, newElems, 0, k);
    return new Ctxt(newElems);
  }

  // Maximize length of returned context is max
  public Ctxt prepend(Unit q) { return prepend(q, Integer.MAX_VALUE); }
  public Ctxt prepend(Unit q, int max) {
    int oldLen = elems.length;
    int newLen = Math.min(max, oldLen+1);
    Unit[] newElems = new Unit[newLen];
    if (newLen > 0) newElems[0] = q;
    if (newLen > 1) System.arraycopy(elems, 0, newElems, 1, newLen-1);
    return new Ctxt(newElems);
  }

  public Ctxt append(Unit q) {
    Unit[] newElems = new Unit[elems.length+1];
    System.arraycopy(elems, 0, newElems, 0, elems.length);
    newElems[newElems.length-1] = q;
    return new Ctxt(newElems);
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>com.box.boxjavalibv2.interfaces Class Hierarchy</title>
<meta name="date" content="2014-01-24">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package com.box.boxjavalibv2.interfaces

Package Hierarchies:

All Packages

Interface Hierarchy

com.box.boxjavalibv2.interfaces.IAuthData

com.box.boxjavalibv2.interfaces.IAuthDataController

com.box.boxjavalibv2.interfaces.IAuthEvent

com.box.boxjavalibv2.interfaces.IAuthFlowListener

com.box.boxjavalibv2.interfaces.IAuthFlowMessage

com.box.boxjavalibv2.interfaces.IAuthFlowUI

com.box.boxjavalibv2.interfaces.IAuthSecureStorage

com.box.boxjavalibv2.interfaces.IBoxJSONParser

com.box.boxjavalibv2.interfaces.IBoxJSONStringEntity

com.box.boxjavalibv2.interfaces.IBoxParcelable

com.box.boxjavalibv2.interfaces.IBoxParcelWrapper

com.box.boxjavalibv2.interfaces.IBoxRequestObject

com.box.boxjavalibv2.interfaces.IBoxResourceHub

com.box.boxjavalibv2.interfaces.IBoxType

com.box.boxjavalibv2.interfaces.IFileTransferListener

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
make cscope O=. SRCARCH=arm64 SUBARCH=mach-msm
make tags  SRCARCH=arm64 SUBARCH=mach-msm
#make gtags ARCH=arm SUBARCH=mach-msm


text:
{% import "search/result.html" as resultTypes %}

    {{result.total}} results found containing
    {{ params.term }}

  {% for hit in result.hits %}
    {% if hit._type == 'company_contact' %}
      {{ resultTypes.contactresult(hit._id, hit._source, params.term, hit._type) }}
    {% elseif hit._type == 'company_companieshousecompany' or hit._type == 'company_company' %}
      {{ resultTypes.companyresult(hit._id, hit._source, params.term, hit._type) }}
    {% endif %}
  {% endfor %}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.hive;

import com.facebook.presto.hive.HdfsEnvironment.HdfsContext;
import com.facebook.presto.hive.metastore.StorageFormat;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.PrestoException;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.ql.exec.FileSinkOperator.RecordWriter;
import org.apache.hadoop.mapred.JobConf;

import javax.inject.Inject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import static com.facebook.presto.hive.HiveErrorCode.HIVE_WRITER_CLOSE_ERROR;
import static com.facebook.presto.hive.HiveWriteUtils.initializeSerializer;
import static com.facebook.presto.hive.util.ConfigurationUtils.configureCompression;
import static com.google.common.util.concurrent.Futures.whenAllSucceed;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static io.airlift.concurrent.MoreFutures.getFutureValue;
import static java.util.Objects.requireNonNull;

public class HiveZeroRowFileCreator
        implements ZeroRowFileCreator
{
    private final HdfsEnvironment hdfsEnvironment;
    private final ListeningExecutorService executor;

    @Inject
    public HiveZeroRowFileCreator(
            HdfsEnvironment hdfsEnvironment,
            @ForZeroRowFileCreator ListeningExecutorService zeroRowFileCreatorExecutor)
    {
        this.hdfsEnvironment = requireNonNull(hdfsEnvironment, "hdfsEnvironment is null");
        this.executor = requireNonNull(zeroRowFileCreatorExecutor, "zeroRowFileCreatorExecutor is null");
    }

    @Override
    public void createFiles(ConnectorSession session, HdfsContext hdfsContext, Path destinationDirectory, List<String> fileNames, StorageFormat format, HiveCompressionCodec compressionCodec, Properties schema)
    {
        JobConf conf = configureCompression(hdfsEnvironment.getConfiguration(hdfsContext, destinationDirectory), compressionCodec);
        List<ListenableFuture<?>> commitFutures = new ArrayList<>();

        for (String fileName : fileNames) {
            commitFutures.add(
                    executor.submit(
                            () -> writeZeroRowFile(session, new Path(destinationDirectory, fileName), conf, schema, format.getSerDe(), format.getOutputFormat())));
        }

        ListenableFuture<?> listenableFutureAggregate = whenAllSucceed(commitFutures).call(() -> null, directExecutor());
        try {
            getFutureValue(listenableFutureAggregate, PrestoException.class);
        }
        catch (RuntimeException e) {
            listenableFutureAggregate.cancel(true);
            throw e;
        }
    }

    private static void writeZeroRowFile(ConnectorSession session, Path target, JobConf conf, Properties properties, String serDe, String outputFormatName)
    {
        // Some serializers such as Avro set a property in the schema.
        initializeSerializer(conf, properties, serDe);

        // The code below is not a try with resources because RecordWriter is not Closeable.
        RecordWriter recordWriter = HiveWriteUtils.createRecordWriter(target, conf, properties, outputFormatName, session);
        try {
            recordWriter.close(false);
        }
        catch (IOException e) {
            throw new PrestoException(HIVE_WRITER_CLOSE_ERROR, "Error write zero-row file to Hive", e);
        }
    }
}


text:
package org.apache.wicket.examples.ajax.builtin;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxFallbackLink;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.util.io.IClusterable;

/**
 * Ajax todo list without having to write any JavaScript yourself.
 *
 * @author Martijn Dashorst
 */
public class TodoList extends BasePage
{
	/**
	 * The todo object.
	 */
	public static class TodoItem implements IClusterable
	{
		private static final long serialVersionUID = 1L;

		/** Is the item done? */
		private boolean checked;

		/** Description of the item. */
		private String text;

		/** Constructor. */
		public TodoItem()
		{
		}

		/**
		 * Copy constructor.
		 *
		 * @param item
		 *            the item to copy the values from.
		 */
		public TodoItem(TodoItem item)
		{
			text = item.text;
		}

		/**
		 * @return Returns the checked property.
		 */
		public boolean isChecked()
		{
			return checked;
		}

		/**
		 * Sets the checked property.
		 *
		 * @param checked
		 *            The checked property to set.
		 */
		public void setChecked(boolean checked)
		{
			this.checked = checked;
		}

		/**
		 * Gets the description of the item.
		 *
		 * @return Returns the text.
		 */
		public String getText()
		{
			return text;
		}

		/**
		 * Sets the description of the item.
		 *
		 * @param text
		 *            The text to set.
		 */
		public void setText(String text)
		{
			this.text = text;
		}
	}

	/**
	 * Container for displaying the todo items in a list.
	 */
	public class TodoItemsContainer extends WebMarkupContainer
	{
		/**
		 * Constructor.
		 *
		 * @param id
		 *            the component identifier.
		 */
		public TodoItemsContainer(String id)
		{
			super(id);

			// let wicket generate a markup-id so the contents can be
			// updated through an AJAX call.
			setOutputMarkupId(true);

			// add the listview to the container
			add(new ListView<TodoItem>("item", items)
			{
				@Override
				protected void populateItem(ListItem<TodoItem> item)
				{
					// add an AJAX checkbox to the item
					item.add(new AjaxCheckBox("check", new PropertyModel<Boolean>(
						item.getDefaultModel(), "checked"))
					{
						@Override
						protected void onUpdate(AjaxRequestTarget target)
						{
							// no need to do anything, the model is updated by
							// itself, and we don't have to re-render a
							// component (the client already has the correct
							// state).
						}
					});
					// display the text of the todo item
					item.add(new Label("text", new PropertyModel<String>(item.getDefaultModel(),
						"text")));
				}
			});
		}
	}

	/**
	 * Container for showing either the add link, or the addition form.
	 */
	public class AddItemsContainer extends WebMarkupContainer
	{
		/** Visibility toggle so that either the link or the form is visible. */
		private boolean linkVisible = true;

		/** Link for displaying the AddTodo form. */
		private final class AddTodoLink extends AjaxFallbackLink
		{
			/** Constructor. */
			private AddTodoLink(String id)
			{
				super(id);
			}

			/**
			 * onclick handler.
			 *
			 * @param target
			 *            the request target.
			 */
			@Override
			public void onClick(AjaxRequestTarget target)
			{
				onShowForm(target);
			}

			/**
			 * Toggles the visibility with the add form.
			 *
			 * @return true when the add links is visible and the form isn't.
			 */
			@Override
			public boolean isVisible()
			{
				return linkVisible;
			}
		}

		/**
		 * Link for removing all completed todos from the list, this link follows the same
		 * visibility rules as the add link.
		 */
		private final class RemoveCompletedTodosLink extends AjaxFallbackLink
		{
			/**
			 * Constructor.
			 *
			 * @param id
			 *            component id
			 */
			public RemoveCompletedTodosLink(String id)
			{
				super(id);
			}

			/**
			 * @see AjaxFallbackLink#onClick(org.apache.wicket.ajax.AjaxRequestTarget)
			 */
			@Override
			public void onClick(AjaxRequestTarget target)
			{
				onRemoveCompletedTodos(target);
			}

			/**
			 * Toggles the visibility with the add form.
			 *
			 * @return true when the add links is visible and the form isn't.
			 */
			@Override
			public boolean isVisible()
			{
				return linkVisible;
			}
		}

		/**
		 * Displays a form which offers an edit field and two buttons: one for adding the todo item,
		 * and one for canceling the addition. The visibility of this component is mutual exclusive
		 * with the visibility of the add-link.
		 */
		private final class AddTodoForm extends Form<TodoItem>
		{
			/**
			 * Constructor.
			 *
			 * @param id
			 *            the component id.
			 */
			public AddTodoForm(String id)
			{
				super(id, new CompoundPropertyModel<>(new TodoItem()));
				setOutputMarkupId(true);
				add(new TextField<>("text"));
				add(new AjaxButton("add", this)
				{
					@Override
					protected void onSubmit(AjaxRequestTarget target, Form<?> form)
					{
						// retrieve the todo item
						TodoItem item = (TodoItem)getParent().getDefaultModelObject();

						// add the item
						onAdd(item, target);
					}

					@Override
					protected void onError(AjaxRequestTarget target, Form<?> form)
					{
					}
				});

				add(new AjaxButton("cancel", this)
				{
					@Override
					public void onSubmit(AjaxRequestTarget target, Form<?> form)
					{
						onCancelTodo(target);
					}

					@Override
					protected void onError(AjaxRequestTarget target, Form<?> form)
					{
					}
				});
			}

			/**
			 * Toggles the visibility with the add link. When the link is visible, the form isn't.
			 *
			 * @return true when the form is visible and the link isn't.
			 */
			@Override
			public boolean isVisible()
			{
				return !linkVisible;
			}
		}

		/**
		 * Constructor.
		 *
		 * @param id
		 *            the component id.
		 */
		public AddItemsContainer(String id)
		{
			super(id);
			// let wicket generate a markup-id so the contents can be
			// updated through an AJAX call.
			setOutputMarkupId(true);
			add(new AddTodoLink("link"));
			add(new RemoveCompletedTodosLink("remove"));
			add(new AddTodoForm("form"));
		}

		/**
		 * Called then the add link was clicked, shows the form, and hides the link.
		 *
		 * @param target
		 *            the request target.
		 */
		void onShowForm(AjaxRequestTarget target)
		{
			// toggle the visibility
			linkVisible = false;

			// redraw the add container.
			target.add(this);
		}

		void onRemoveCompletedTodos(AjaxRequestTarget target)
		{
			List<TodoItem> ready = new ArrayList<>();
			for (TodoItem todo : items)
			{
				if (todo.isChecked())
				{
					ready.add(todo);
				}
			}
			items.removeAll(ready);

			// repaint our panel
			target.add(this);

			// repaint the listview as there was a new item added.
			target.add(showItems);
		}

		/**
		 * Called when the form is submitted through the add button, stores the todo item, hides the
		 * form, displays the add link and updates the listview.
		 *
		 * @param target
		 *            the request target
		 */
		void onAdd(TodoItem item, AjaxRequestTarget target)
		{
			// add the item
			items.add(new TodoItem(item));

			// reset the model
			item.setChecked(false);
			item.setText("");

			// toggle the visibility
			linkVisible = true;

			// repaint our panel
			target.add(this);

			// repaint the listview as there was a new item added.
			target.add(showItems);
		}

		/**
		 * Called when adding a new todo item was canceled. Hides the add form and displays the add
		 * link.
		 *
		 * @param target
		 *            the request target.
		 */
		void onCancelTodo(AjaxRequestTarget target)
		{
			// toggle the visibility
			linkVisible = true;

			// repaint the panel.
			target.add(this);
		}
	}

	/**
	 * Container for redrawing the todo items list with an AJAX call.
	 */
	private final WebMarkupContainer showItems;

	/**
	 * The list of todo items.
	 */
	final List<TodoItem> items = new ArrayList<>();

	/**
	 * Constructor.
	 */
	public TodoList()
	{
		// add the listview container for the todo items.
		showItems = new TodoItemsContainer("showItems");
		add(showItems);

		add(new AjaxFallbackLink<Void>("ajaxback")
		{
			/**
			 * @see org.apache.wicket.ajax.markup.html.AjaxFallbackLink#onClick(org.apache.wicket.ajax.AjaxRequestTarget)
			 */
			@Override
			public void onClick(AjaxRequestTarget target)
			{
				setResponsePage(getPage());
			}
		});
		// add the add container for the todo items.
		add(new AddItemsContainer("addItems"));
	}
}


text:
require 'matrix'

class Vote < ActiveRecord::Base
  has_many :users, :through => :tallies
  has_many :tallies, :dependent => :destroy
  has_many :options, :dependent => :destroy
  belongs_to :remuneration

  validates_presence_of :name

  has_many :options

  VOTE_TYPES = ["single_option", "multi_option", "prioritization", "allocation"]

  def validate
    if self.options.length <= 1
      self.errors.add_to_base("You must have at least two topics on which to vote")
    end
  end

  def handle_cast(params, current_user)
    case self.kind.to_sym
    when :single_option
      if params[:option]
        opt = self.options.find_by_id(params[:option].first)
        opt.tallies.create(:vote => self, :user => current_user) if opt
      end
    when :multi_option
      option_ids = params[:options].keys
      self.options.each do |opt|
        opt.tallies.create(:user => current_user, :vote => self, :value => 1) if option_ids.include?(opt.id.to_s)
      end
    when :allocation
      self.options.each do |opt|
        value = params[:options][opt.id.to_s]
        opt.tallies.create(:user => current_user, :vote => self, :value => value)
      end
    when :prioritization
      self.tallies.create(:user => current_user, :option_order => params[:options].join("|"))
    end
  end

  def tally_total
    self.tallies.count
  end

  def assign_options(ara)
    self.options = ara.map { |opt| Option.new(:name => opt) }
  end

  def percentage(option)
    return 0 if self.tally_total == 0
    percent = (option.tallies.count.to_f / self.tally_total) * 100
    sprintf("%.1f", percent)
  end

  def option_count
    @oc ||= self.options.count
  end

  def tally_count
    @tc ||= self.tallies.count
  end

  def votes_cast
    @vsc ||= tally_count / option_count
  end

  def self.round_robin(num_opts)
    ara = Array.new(num_opts, 0)
    j=0
    100.times do |i|
      ara[j] += 1
      if(j == num_opts - 1)
        j = 0
      else
        j += 1
      end
    end
    return ara
  end

  def tally_matrix_sum
    matrices = tallies.map {|x| Matrix[*x.matrix] }
    retval = Matrix.zero(options.count)
    matrices.each {|m| retval += m }
    retval.to_a
  end

  def ordered_options
    return @oos if @oos
    self.condorcet.each do |opt_id, score|
      opt = self.options.select {|x| x.id == opt_id.to_i }.first
      opt.condorcet_score = score
    end
    @oos = self.options.sort_by {|x| x.condorcet_score }.reverse
  end

  def total_condorcet_points
    condorcet.values.map(&:abs).sum
  end

  def weighted_ordered_option_scores
    oos = ordered_options
    lowest = oos.last.condorcet_score.abs
    oos.map {|x| x.condorcet_score += lowest }
  end

  def condorcet
    sum_matrix = tally_matrix_sum
    sum_matrix.map! {|x| x.sum }
    ret_hsh = {}
    self.options.each_with_index do |opt, i|
      ret_hsh.merge!({ opt.id.to_s => sum_matrix[i] })
    end
    ret_hsh
  end

  def is_for_peer_review?
    !self.options.first.payment_id.blank?
  end

  def already_cast?(user)
    self.tallies.map(&:user_id).include?(user.id)
  end

end


text:
import React from 'react';
import PropTypes from 'prop-types';
import injectSheet from 'react-jss';
import classNames from 'classnames';

const styles = {
  button: {
    '-webkit-tap-highlight-color': 'rgba(0, 0, 0, 0)',
    // eslint-disable-next-line
        '-webkit-tap-highlight-color': 'transparent',
    '&:focus': {
      outline: 'none',
    },
  },

  wrapper: {
    transition: 'opacity 500ms cubic-bezier(0.03, 0.72, 0.36, 0.99)',
    position: 'fixed',
    top: 0,
    left: 0,
    zIndex: 998,
    width: '100%',
    height: '100%',
    opacity: 0,
  },

  block_layer: {
    position: 'absolute',
    top: 0,
    left: 0,
    width: '100%',
    height: '100%',
    backgroundColor: 'rgba(0, 0, 0, 0.8)',
  },

  bottom_sheet: {
    transition: 'transform 500ms cubic-bezier(0.03, 0.72, 0.36, 0.99)',
    transform: 'translate3d(0, 100%, 0)',
    position: 'absolute',
    bottom: 0,
    zIndex: 999,
    width: '100%',
    backgroundColor: '#fff',
  },
  bottom_sheet_item: {
    display: 'block',
    width: '100%',
    backgroundColor: '#fff',
    textAlign: 'center',
    padding: props => `${props.itemPadding} 0`,
    border: 'none',
    borderTop: '0.02rem solid #ededed',
    fontSize: props => props.fontSize,
    color: 'rgba(0,0,0,.87)',
  },
  bottom_sheet_item_cancel: {
    color: '#d0021b',
  },

  wrapper_hide: {
    display: 'none',
  },
  wrapper_enter: {
    opacity: 1,
  },
  bottom_sheet_enter: {
    transform: 'translate3d(0, 0, 0)',
  },
};

class BottomSheet extends React.Component {
    static propTypes = {
      showBlockLayer: PropTypes.bool,
      visible: PropTypes.bool,
      className: PropTypes.string,
      onClose: PropTypes.func.isRequired,
      appendCancelBtn: PropTypes.bool,
      customLayout: PropTypes.string,
      fontSize: PropTypes.string,
      itemPadding: PropTypes.string,
    };

    static defaultProps = {
      showBlockLayer: true,
      visible: true,
      className: '',
      appendCancelBtn: true,
      fontSize: '.32rem',
      itemPadding: '.40rem',
    };

    constructor(props) {
      super(props);

      this.state = {
        isShow: false,
        animationState: 'leave',
      };
    }

    componentDidMount() {
      if (this.props.visible) {
        this.enter();
      }
    }

    shouldComponentUpdate(nextProps, nextState) {
      if (Object.is(this.state, nextState) && Object.is(this.props, nextProps)) {
        return false;
      }
      return true;
    }

    componentWillReceiveProps(nextProps) {
      if (!this.props.visible && nextProps.visible) {
        this.enter();
      } else if (this.props.visible && !nextProps.visible) {
        this.leave();
      }
    }

    enter() {
      this.setState({
        isShow: true,
      });
      setTimeout(() => {
        document.getElementsByTagName('html')[0].style.overflow = 'hidden';
        this.setState({
          animationState: 'enter',
        });
      }, 50);
    }

    leave() {
      this.setState({
        animationState: 'leave',
      });
      setTimeout(this.onClose.bind(this), 500);
    }

    onClose() {
      if (this.state.animationState === 'leave') {
        document.getElementsByTagName('html')[0].style.overflow = 'auto';
        this.setState({
          isShow: false,
        });
      }

      this.props.onCloseFinishAnimation && this.props.onCloseFinishAnimation();
    }

    componentWillUnmount() {
      document.getElementsByTagName('html')[0].style.overflow = 'auto';
    }

    render() {
      const { classes } = this.props;
      const layer = this.props.showBlockLayer ?
 : null;

      return (

          {layer}
          {this.props.customLayout}

            {this.props.children}
            {this.props.list && this.props.list.map((item, idx) => (<button key={idx} className={classes.bottom_sheet_item} onClick={item.handler}>{item.title}</button>))}
            {this.props.appendCancelBtn && (() => (<button className={classNames(classes.bottom_sheet_item, classes.bottom_sheet_item_cancel)} onClick={this.props.onClose}>取消</button>))()}

      );
    }
}

export default injectSheet(styles)(BottomSheet);


text:
#Apache OCW lib immports
import ocw.dataset as ds
import ocw.data_source.local as local
import ocw.plotter as plotter
import ocw.utils as utils
from ocw.evaluation import Evaluation
import ocw.metrics as metrics

# Python libraries
import numpy as np
import numpy.ma as ma
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib import rcParams
from matplotlib.patches import Polygon
import string

def Map_plot_bias_of_multiyear_climatology(obs_dataset, obs_name, model_datasets, model_names,
                                      file_name, row, column, map_projection=None):
    '''Draw maps of observed multi-year climatology and biases of models"'''

    # calculate climatology of observation data
    obs_clim = utils.calc_temporal_mean(obs_dataset)
    # determine the metrics
    map_of_bias = metrics.TemporalMeanBias()

    # create the Evaluation object
    bias_evaluation = Evaluation(obs_dataset, # Reference dataset for the evaluation
                                 model_datasets, # list of target datasets for the evaluation
                                 [map_of_bias, map_of_bias])
    # run the evaluation (bias calculation)
    bias_evaluation.run()

    rcm_bias = bias_evaluation.results[0]

    fig = plt.figure()

    lat_min = obs_dataset.lats.min()
    lat_max = obs_dataset.lats.max()
    lon_min = obs_dataset.lons.min()
    lon_max = obs_dataset.lons.max()

    string_list = list(string.ascii_lowercase)
    nmodels = len(model_datasets)
    row, column = plotter._best_grid_shape(nmodels + 1, (row, column))
    ax = fig.add_subplot(row,column,1)
    if map_projection == 'npstere':
        m = Basemap(ax=ax, projection ='npstere', boundinglat=lat_min, lon_0=0,
            resolution = 'l', fix_aspect=True)
    else:
        m = Basemap(ax=ax, projection ='cyl', llcrnrlat = lat_min, urcrnrlat = lat_max,
            llcrnrlon = lon_min, urcrnrlon = lon_max, resolution = 'l', fix_aspect=True)
    if obs_dataset.lons.ndim == 1 and obs_dataset.lats.ndim == 1:
        lons, lats = np.meshgrid(obs_dataset.lons, obs_dataset.lats)
    if obs_dataset.lons.ndim == 2 and obs_dataset.lats.ndim == 2:
        lons = obs_dataset.lons
        lats = obs_dataset.lats

    x,y = m(lons, lats)

    m.drawcoastlines(linewidth=1)
    m.drawcountries(linewidth=1)
    m.drawstates(linewidth=0.5, color='w')
    max = m.contourf(x,y,obs_clim,levels = plotter._nice_intervals(obs_dataset.values, 10), extend='both',cmap='rainbow')
    ax.annotate('(a) \n' + obs_name,xy=(lon_min, lat_min))
    cax = fig.add_axes([0.02, 1.-float(1./row)+1./row*0.25, 0.01, 1./row*0.5])
    plt.colorbar(max, cax = cax)
    clevs = plotter._nice_intervals(rcm_bias, 11)
    for imodel in np.arange(nmodels):

        ax = fig.add_subplot(row, column,2+imodel)
        if map_projection == 'npstere':
            m = Basemap(ax=ax, projection ='npstere', boundinglat=lat_min, lon_0=0,
                resolution = 'l', fix_aspect=True)
        else:
            m = Basemap(ax=ax, projection ='cyl', llcrnrlat = lat_min, urcrnrlat = lat_max,
                llcrnrlon = lon_min, urcrnrlon = lon_max, resolution = 'l', fix_aspect=True)
        m.drawcoastlines(linewidth=1)
        m.drawcountries(linewidth=1)
        m.drawstates(linewidth=0.5, color='w')
        max = m.contourf(x,y,rcm_bias[imodel,:],levels = clevs, extend='both', cmap='RdBu_r')
        ax.annotate('('+string_list[imodel+1]+')  \n '+model_names[imodel],xy=(lon_min, lat_min))

    cax = fig.add_axes([0.91, 0.5, 0.015, 0.4])
    plt.colorbar(max, cax = cax)

    plt.subplots_adjust(hspace=0.01,wspace=0.05)

    fig.savefig(file_name,dpi=600,bbox_inches='tight')

def Taylor_diagram_spatial_pattern_of_multiyear_climatology(obs_dataset, obs_name, model_datasets, model_names,
                                      file_name):

    # calculate climatological mean fields
    obs_clim_dataset = ds.Dataset(obs_dataset.lats, obs_dataset.lons, obs_dataset.times, utils.calc_temporal_mean(obs_dataset))
    model_clim_datasets = []
    for dataset in model_datasets:
        model_clim_datasets.append(ds.Dataset(dataset.lats, dataset.lons, dataset.times, utils.calc_temporal_mean(dataset)))

    # Metrics (spatial standard deviation and pattern correlation)
    # determine the metrics
    taylor_diagram = metrics.SpatialPatternTaylorDiagram()

    # create the Evaluation object
    taylor_evaluation = Evaluation(obs_clim_dataset, # Climatological mean of reference dataset for the evaluation
                                 model_clim_datasets, # list of climatological means from model datasets for the evaluation
                                 [taylor_diagram])

    # run the evaluation (bias calculation)
    taylor_evaluation.run()

    taylor_data = taylor_evaluation.results[0]

    plotter.draw_taylor_diagram(taylor_data, model_names, obs_name, file_name, pos='upper right',frameon=False)

def Time_series_subregion(obs_subregion_mean, obs_name, model_subregion_mean, model_names, seasonal_cycle,
                          file_name, row, column, x_tick=['']):

    nmodel, nt, nregion = model_subregion_mean.shape

    if seasonal_cycle:
        obs_data = ma.mean(obs_subregion_mean.reshape([1,nt/12,12,nregion]), axis=1)
        model_data = ma.mean(model_subregion_mean.reshape([nmodel,nt/12,12,nregion]), axis=1)
        nt = 12
    else:
        obs_data = obs_subregion_mean
        model_data = model_subregion_mean

    x_axis = np.arange(nt)
    x_tick_values = x_axis

    fig = plt.figure()
    rcParams['xtick.labelsize'] = 6
    rcParams['ytick.labelsize'] = 6

    for iregion in np.arange(nregion):
        ax = fig.add_subplot(row, column, iregion+1)
        x_tick_labels = ['']
        if iregion+1  > column*(row-1):
            x_tick_labels = x_tick
        else:
            x_tick_labels=['']
        ax.plot(x_axis, obs_data[0, :, iregion], color='r', lw=2, label=obs_name)
        for imodel in np.arange(nmodel):
            ax.plot(x_axis, model_data[imodel, :, iregion], lw=0.5, label = model_names[imodel])
        ax.set_xlim([-0.5,nt-0.5])
        ax.set_xticks(x_tick_values)
        ax.set_xticklabels(x_tick_labels)
        ax.set_title('Region %02d' % (iregion+1), fontsize=8)

    ax.legend(bbox_to_anchor=(-0.2, row/2), loc='center' , prop={'size':7}, frameon=False)

    fig.subplots_adjust(hspace=0.7, wspace=0.5)
    fig.savefig(file_name, dpi=600, bbox_inches='tight')

def Portrait_diagram_subregion(obs_subregion_mean, obs_name, model_subregion_mean, model_names, seasonal_cycle,
                               file_name, normalize=True):

    nmodel, nt, nregion = model_subregion_mean.shape

    if seasonal_cycle:
        obs_data = ma.mean(obs_subregion_mean.reshape([1,nt/12,12,nregion]), axis=1)
        model_data = ma.mean(model_subregion_mean.reshape([nmodel,nt/12,12,nregion]), axis=1)
        nt = 12
    else:
        obs_data = obs_subregion_mean
        model_data = model_subregion_mean

    subregion_metrics = ma.zeros([4, nregion, nmodel])

    for imodel in np.arange(nmodel):
        for iregion in np.arange(nregion):
            # First metric: bias
            subregion_metrics[0, iregion, imodel] = metrics.calc_bias(model_data[imodel, :, iregion], obs_data[0, :, iregion], average_over_time = True)
            # Second metric: standard deviation
            subregion_metrics[1, iregion, imodel] = metrics.calc_stddev_ratio(model_data[imodel, :, iregion], obs_data[0, :, iregion])
            # Third metric: RMSE
            subregion_metrics[2, iregion, imodel] = metrics.calc_rmse(model_data[imodel, :, iregion], obs_data[0, :, iregion])
            # Fourth metric: correlation
            subregion_metrics[3, iregion, imodel] = metrics.calc_correlation(model_data[imodel, :, iregion], obs_data[0, :, iregion])

    if normalize:
        for iregion in np.arange(nregion):
            subregion_metrics[0, iregion, : ] = subregion_metrics[0, iregion, : ]/ma.std(obs_data[0, :, iregion])*100.
            subregion_metrics[1, iregion, : ] = subregion_metrics[1, iregion, : ]*100.
            subregion_metrics[2, iregion, : ] = subregion_metrics[2, iregion, : ]/ma.std(obs_data[0, :, iregion])*100.

    region_names = ['R%02d' % i for i in np.arange(nregion)+1]

    for imetric, metric in enumerate(['bias','std','RMSE','corr']):
        plotter.draw_portrait_diagram(subregion_metrics[imetric, :, :], region_names, model_names, file_name+'_'+metric,
                                      xlabel='model',ylabel='region')

def Map_plot_subregion(subregions, ref_dataset, directory):

    lons, lats = np.meshgrid(ref_dataset.lons, ref_dataset.lats)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    m = Basemap(ax=ax, projection='cyl',llcrnrlat = lats.min(), urcrnrlat = lats.max(),
                llcrnrlon = lons.min(), urcrnrlon = lons.max(), resolution = 'l')
    m.drawcoastlines(linewidth=0.75)
    m.drawcountries(linewidth=0.75)
    m.etopo()
    x, y = m(lons, lats)
    #subregion_array = ma.masked_equal(subregion_array, 0)
    #max=m.contourf(x, y, subregion_array, alpha=0.7, cmap='Accent')
    for subregion in subregions:
        draw_screen_poly(subregion[1], m, 'w')
        plt.annotate(subregion[0],xy=(0.5*(subregion[1][2]+subregion[1][3]), 0.5*(subregion[1][0]+subregion[1][1])), ha='center',va='center', fontsize=8)
    fig.savefig(directory+'map_subregion', bbox_inches='tight')

def draw_screen_poly(boundary_array, m, linecolor='k'):

    ''' Draw a polygon on a map

    :param boundary_array: [lat_north, lat_south, lon_east, lon_west]
    :param m   : Basemap object
    '''

    lats = [boundary_array[0], boundary_array[0], boundary_array[1], boundary_array[1]]
    lons = [boundary_array[3], boundary_array[2], boundary_array[2], boundary_array[3]]
    x, y = m( lons, lats )
    xy = zip(x,y)
    poly = Polygon( xy, facecolor='none',edgecolor=linecolor )
    plt.gca().add_patch(poly)


text:
package org.apache.flink.table.planner.factories;

import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.configuration.ConfigOption;
import org.apache.flink.configuration.ConfigOptions;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.file.src.FileSource;
import org.apache.flink.connector.file.src.reader.SimpleStreamFormat;
import org.apache.flink.core.fs.FSDataInputStream;
import org.apache.flink.core.fs.Path;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.connector.ChangelogMode;
import org.apache.flink.table.connector.source.DataStreamScanProvider;
import org.apache.flink.table.connector.source.DynamicTableSource;
import org.apache.flink.table.connector.source.ScanTableSource;
import org.apache.flink.table.connector.source.SourceProvider;
import org.apache.flink.table.data.GenericRowData;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.data.StringData;
import org.apache.flink.table.factories.DynamicTableSourceFactory;
import org.apache.flink.table.filesystem.FileSystemOptions;
import org.apache.flink.table.runtime.typeutils.InternalTypeInfo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/** Test file source {@link DynamicTableSourceFactory}. */
public class TestFileSourceFactory implements DynamicTableSourceFactory {

    private static final ConfigOption<String> RUNTIME_SOURCE =
            ConfigOptions.key("runtime-source")
                    .stringType()
                    .defaultValue("Source"); // another is "DataStream"

    @Override
    public DynamicTableSource createDynamicTableSource(Context context) {
        Configuration conf = Configuration.fromMap(context.getCatalogTable().getOptions());
        return new TestFileTableSource(
                new Path(conf.getString(FileSystemOptions.PATH)), conf.getString(RUNTIME_SOURCE));
    }

    @Override
    public String factoryIdentifier() {
        return "filesource";
    }

    @Override
    public Set<ConfigOption<?>> requiredOptions() {
        return new HashSet<>();
    }

    @Override
    public Set<ConfigOption<?>> optionalOptions() {
        return new HashSet<>(Collections.singletonList(RUNTIME_SOURCE));
    }

    private static class TestFileTableSource implements ScanTableSource {

        private final Path path;
        private final String runtimeSource;

        private TestFileTableSource(Path path, String runtimeSource) {
            this.path = path;
            this.runtimeSource = runtimeSource;
        }

        @Override
        public ChangelogMode getChangelogMode() {
            return ChangelogMode.insertOnly();
        }

        @Override
        public ScanRuntimeProvider getScanRuntimeProvider(ScanContext runtimeProviderContext) {
            FileSource<RowData> fileSource =
                    FileSource.forRecordStreamFormat(new FileFormat(), path).build();
            switch (runtimeSource) {
                case "Source":
                    return SourceProvider.of(fileSource);
                case "DataStream":
                    return new TestFileSourceDataStreamScanProvider(fileSource, asSummaryString());
                default:
                    throw new IllegalArgumentException(
                            "Unsupported runtime source class: " + runtimeSource);
            }
        }

        @Override
        public DynamicTableSource copy() {
            return new TestFileTableSource(path, runtimeSource);
        }

        @Override
        public String asSummaryString() {
            return "test-file-source";
        }
    }

    private static class FileFormat extends SimpleStreamFormat<RowData> {

        @Override
        public Reader<RowData> createReader(Configuration config, FSDataInputStream stream) {
            BufferedReader reader =
                    new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
            return new Reader<RowData>() {
                @Override
                public RowData read() throws IOException {
                    String line = reader.readLine();
                    if (line == null) {
                        return null;
                    }
                    return GenericRowData.of(StringData.fromString(line));
                }

                @Override
                public void close() throws IOException {
                    reader.close();
                }
            };
        }

        @Override
        public TypeInformation<RowData> getProducedType() {
            return InternalTypeInfo.ofFields(DataTypes.STRING().getLogicalType());
        }
    }

    private static class TestFileSourceDataStreamScanProvider implements DataStreamScanProvider {
        private final FileSource<RowData> fileSource;
        private final String name;

        private TestFileSourceDataStreamScanProvider(FileSource<RowData> fileSource, String name) {
            this.fileSource = fileSource;
            this.name = name;
        }

        @Override
        public DataStream<RowData> produceDataStream(StreamExecutionEnvironment execEnv) {
            return execEnv.fromSource(fileSource, WatermarkStrategy.noWatermarks(), name);
        }

        @Override
        public boolean isBounded() {
            return true;
        }
    }
}


text:
using System;
using System.Collections.Generic;

using System.Text;

namespace DomainCQRS.Domain
{
	public interface IHandlesEvent<E>
		where E : IEvent
	{
		void Apply(E @event);
	}
}


text:
<?php

namespace Common\Core;

/**
 * This is our extended version of \SpoonFormCheckbox
 */
class CommonFormCheckbox extends \SpoonFormCheckbox
{
    /**
     * Returns the value corresponding with the state of the checkbox
     *
     * @param mixed $checked the return value when checked
     * @param mixed $notChecked the return value when not checked
     *
     * @return string
     */
    public function getActualValue($checked = 'Y', $notChecked = 'N')
    {
        return $this->isChecked() ? $checked : $notChecked;
    }
}


text:
> Recursively find and return a nested node and all its ancestors (parents)
from a nested data structure (i.e. tree)

## Install
```
$ npm install --save find-ancestors
```

## Usage
```js
var findAncestors = require('find-ancestors');

var tree = [{
  id: 1,
  children: [{
    id: 2
  }, {
    id: 3
  }]
}];

findAncestors(tree, function(item) {
  return item.id === 3;
}); // => [{ id: 3 }, { id: 1, children: [{ id: 2 }, { id: 3 }] }]

```

## API
### `findAncestors(options)`
Recursively find and return a nested node and all its ancestors (parents) from a nested data structure (i.e. tree)

#### Params
- **Array** `data`: An array of data
- **Function** `predicate`: A filter criteria

#### Return
- **Array**: Matched node and its ancestors

## License
MIT © [Philipp Alferov](https://github.com/alferov)


text:
package com.github.zzwwws.rxzhihudaily.presenter.activity;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;

import com.github.zzwwws.rxzhihudaily.presenter.fragment.BaseFragment;

/**
 * Created by zzwwws on 2016/2/19.
 */
public class BaseActivity extends AppCompatActivity {

    protected Menu menu;

    protected void hideOption(int id) {
        MenuItem item = menu.findItem(id);
        item.setVisible(false);
    }

    protected void showOption(int id) {
        MenuItem item = menu.findItem(id);
        item.setVisible(true);
    }

    protected void setOptionTitle(int id, String title) {
        MenuItem item = menu.findItem(id);
        item.setTitle(title);
    }

    protected void setOptionIcon(int id, int iconRes) {
        MenuItem item = menu.findItem(id);
        item.setIcon(iconRes);
    }

    protected void switchContent(BaseFragment from, BaseFragment to, Bundle bundle) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (from != null)
            transaction.remove(from);
        if (!to.isAdded()) {
            to.setArguments(bundle);
            transaction.add(to.getFragmentId(), to);
        } else {
            if (bundle != null) {
                to.setUIFragmentBundle(bundle);
            }
            transaction.show(to);
        }
        try {
            transaction.commit();
        } catch (Exception e) {

        }
    }

}


text:
#include "Arduino.h"
#include "Reset.h"

#ifdef __cplusplus
extern "C" {
#endif

static void __halt() {
	// Halts
	while (1)
		;
}
#ifdef __RT_ARDUINO__
extern void EE_SysTick_Handler(void);
#endif

extern void svcHook(void);
extern void pendSVHook(void);
extern int sysTickHook(void);

/* Cortex-M3 core handlers */
void NMI_Handler       (void) __attribute__ ((weak, alias("__halt")));
void HardFault_Handler (void) __attribute__ ((weak, alias("__halt")));
void MemManage_Handler (void) __attribute__ ((weak, alias("__halt")));
void BusFault_Handler  (void) __attribute__ ((weak, alias("__halt")));
void UsageFault_Handler(void) __attribute__ ((weak, alias("__halt")));
void DebugMon_Handler  (void) __attribute__ ((weak, alias("__halt")));
void SVC_Handler       (void) { svcHook(); }
void PendSV_Handler    (void) {	pendSVHook(); }

void SysTick_Handler(void)
{
	if (sysTickHook())
		return;

	tickReset();

	// Increment tick count each ms
	TimeTick_Increment();
#ifdef __RT_ARDUINO__
	EE_SysTick_Handler();
#endif
}

/* Peripherals handlers */
void SUPC_Handler       (void) __attribute__ ((weak, alias("__halt")));
void RSTC_Handler       (void) __attribute__ ((weak, alias("__halt")));
void RTC_Handler        (void) __attribute__ ((weak, alias("__halt")));
void RTT_Handler        (void) __attribute__ ((weak, alias("__halt")));
void WDT_Handler        (void) __attribute__ ((weak, alias("__halt")));
void PMC_Handler        (void) __attribute__ ((weak, alias("__halt")));
void EFC0_Handler       (void) __attribute__ ((weak, alias("__halt")));
void EFC1_Handler       (void) __attribute__ ((weak, alias("__halt")));
void UART_Handler       (void) __attribute__ ((weak, alias("__halt")));
#ifdef _SAM3XA_SMC_INSTANCE_
void SMC_Handler        (void) __attribute__ ((weak, alias("__halt")));
#endif
#ifdef _SAM3XA_SDRAMC_INSTANCE_
void SDRAMC_Handler     (void) __attribute__ ((weak, alias("__halt")));
#endif
void PIOA_Handler       (void) __attribute__ ((weak, alias("__halt")));
void PIOB_Handler       (void) __attribute__ ((weak, alias("__halt")));
#ifdef _SAM3XA_PIOC_INSTANCE_
void PIOC_Handler       (void) __attribute__ ((weak, alias("__halt")));
#endif
#ifdef _SAM3XA_PIOD_INSTANCE_
void PIOD_Handler       (void) __attribute__ ((weak, alias("__halt")));
#endif
#ifdef _SAM3XA_PIOE_INSTANCE_
void PIOE_Handler       (void) __attribute__ ((weak, alias("__halt")));
#endif
#ifdef _SAM3XA_PIOF_INSTANCE_
void PIOF_Handler       (void) __attribute__ ((weak, alias("__halt")));
#endif
void USART0_Handler     (void) __attribute__ ((weak, alias("__halt")));
void USART1_Handler     (void) __attribute__ ((weak, alias("__halt")));
void USART2_Handler     (void) __attribute__ ((weak, alias("__halt")));
#ifdef _SAM3XA_USART3_INSTANCE_
void USART3_Handler     (void) __attribute__ ((weak, alias("__halt")));
#endif
void HSMCI_Handler      (void) __attribute__ ((weak, alias("__halt")));
void TWI0_Handler       (void) __attribute__ ((weak, alias("__halt")));
void TWI1_Handler       (void) __attribute__ ((weak, alias("__halt")));
void SPI0_Handler       (void) __attribute__ ((weak, alias("__halt")));
#ifdef _SAM3XA_SPI1_INSTANCE_
void SPI1_Handler       (void) __attribute__ ((weak, alias("__halt")));
#endif
void SSC_Handler        (void) __attribute__ ((weak, alias("__halt")));
void TC0_Handler        (void) __attribute__ ((weak, alias("__halt")));
void TC1_Handler        (void) __attribute__ ((weak, alias("__halt")));
void TC2_Handler        (void) __attribute__ ((weak, alias("__halt")));
void TC3_Handler        (void) __attribute__ ((weak, alias("__halt")));
void TC4_Handler        (void) __attribute__ ((weak, alias("__halt")));
void TC5_Handler        (void) __attribute__ ((weak, alias("__halt")));
#ifdef _SAM3XA_TC2_INSTANCE_
void TC6_Handler        (void) __attribute__ ((weak, alias("__halt")));
void TC7_Handler        (void) __attribute__ ((weak, alias("__halt")));
void TC8_Handler        (void) __attribute__ ((weak, alias("__halt")));
#endif
void PWM_Handler        (void) __attribute__ ((weak, alias("__halt")));
void ADC_Handler        (void) __attribute__ ((weak, alias("__halt")));
void DACC_Handler       (void) __attribute__ ((weak, alias("__halt")));
void DMAC_Handler       (void) __attribute__ ((weak, alias("__halt")));
void UOTGHS_Handler     (void) __attribute__ ((weak, alias("__halt")));
void TRNG_Handler       (void) __attribute__ ((weak, alias("__halt")));
#ifdef _SAM3XA_EMAC_INSTANCE_
void EMAC_Handler       (void) __attribute__ ((weak, alias("__halt")));
#endif
void CAN0_Handler       (void) __attribute__ ((weak, alias("__halt")));
void CAN1_Handler       (void) __attribute__ ((weak, alias("__halt")));

#ifdef __cplusplus
}
#endif


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
N. Amer. Fl. (New York) 9(4): 244 (1915)

#### Original name
Panellus jalapensis Murrill

### Remarks
null


text:
import _curry2 from './internal/_curry2.js';
import _isFunction from './internal/_isFunction.js';
import lift from './lift.js';
import or from './or.js';

/**
 * A function wrapping calls to the two functions in an `||` operation,
 * returning the result of the first function if it is truth-y and the result
 * of the second function otherwise. Note that this is short-circuited,
 * meaning that the second function will not be invoked if the first returns a
 * truth-y value.
 *
 * In addition to functions, `R.either` also accepts any fantasy-land compatible
 * applicative functor.
 *
 * @func
 * @memberOf R
 * @since v0.12.0
 * @category Logic
 * @sig (*... -> Boolean) -> (*... -> Boolean) -> (*... -> Boolean)
 * @param {Function} f a predicate
 * @param {Function} g another predicate
 * @return {Function} a function that applies its arguments to `f` and `g` and `||`s their outputs together.
 * @see R.both, R.or
 * @example
 *
 *      const gt10 = x => x > 10;
 *      const even = x => x % 2 === 0;
 *      const f = R.either(gt10, even);
 *      f(101); //=> true
 *      f(8); //=> true
 *
 *      R.either(Maybe.Just(false), Maybe.Just(55)); // => Maybe.Just(55)
 *      R.either([false, false, 'a'], [11]) // => [11, 11, "a"]
 */
var either = _curry2(function either(f, g) {
  return _isFunction(f) ?
    function _either() {
      return f.apply(this, arguments) || g.apply(this, arguments);
    } :
    lift(or)(f, g);
});
export default either;


text:
const AffineTransform = {
	create,
	map,
	mapRectangle,
	decompose,
	compose,

	determinant,
	isInversible,
	inverse,

	multiply,
	translate,
	scale,
	rotate,
	shear
};

module.exports = AffineTransform;

function create() {
	return [1, 0, 0, 1, 0, 0];
}

function map(matrix, position) {
	return [matrix[0] * position[0] + matrix[2] * position[1] + matrix[4],
			matrix[1] * position[0] + matrix[3] * position[1] + matrix[5]];
}

function mapRectangle(matrix, rectangle) {
	return Rectangle.corner(
		map(matrix, rectangle.origin),
		map(matrix, rectangle.corner));
}

function determinant(matrix) {
	return matrix[0] * matrix[3] - matrix[1] * matrix[2];
}

function isInversible(matrix) {
	return isDeterminantInversible(determinant(matrix));
}

function isDeterminantInversible(determinant) {
	return isFinite(determinant) && determinant !== 0;
}

function inverse(matrix) {
	let det = determinant(matrix);
	if (!isDeterminantInversible(det))
		return identity();

	return [
		matrix[3] / det,
		-matrix[1] / det,
		-matrix[2] / det,
		matrix[0] / det,
		(matrix[2] * matrix[5] - matrix[3] * matrix[4]) / det,
		(matrix[1] * matrix[4] - matrix[0] * matrix[5]) / det];
}

function multiply(a, b) {
	return [
		b[0] * a[0] + b[1] * a[2],
		b[0] * a[1] + b[1] * a[3],
		b[2] * a[0] + b[3] * a[2],
		b[2] * a[1] + b[3] * a[3],
		b[4] * a[0] + b[5] * a[2] + a[4],
		b[4] * a[1] + b[5] * a[3] + a[5]];
}

function translate(matrix, translation) {
	var transformed = matrix.slice();
	transformed[4] += translation[0] * matrix[0] + translation[1] * matrix[2];
	transformed[5] += translation[0] * matrix[1] + translation[1] * matrix[3];
	return transformed;
}

function scale(matrix, scale) {
	var transformed = matrix.slice();
	transformed[0] *= scale[0];
	transformed[1] *= scale[0];
	transformed[2] *= scale[1];
	transformed[3] *= scale[1];
	return transformed;
}

function rotate(matrix, radians) {
    var cosAngle = Math.cos(radians),
    	sinAngle = Math.sin(radians);
    return multiply(matrix, [cosAngle, sinAngle, -sinAngle, cosAngle, 0, 0]);
}

function shear(matrix, shearing) {
	var transformed = matrix.slice();
	transformed[0] += shearing[1] * matrix[2];
	transformed[1] += shearing[1] * matrix[3];
	transformed[2] += shearing[0] * matrix[0];
	transformed[3] += shearing[0] * matrix[1];
	return transformed;
}

function decompose(matrix) {
	// Remove scaling
	var scale = [Math.sqrt(matrix[0] * matrix[0] + matrix[1] * matrix[1]),
    			 Math.sqrt(matrix[2] * matrix[2] + matrix[3] * matrix[3])];
	if ((matrix[0] * matrix[3] - matrix[2] * matrix[1]) < 0) {
		if (matrix[0] < matrix[3])
			scale[0] = -scale[0];
		else
			scale[1] = -scale[1];
	}
    matrix = AffineTransform.scale(matrix, [1 / scale[0], 1 / scale[1]]);

    // Remove rotation
	var angle = Math.atan2(matrix[1], matrix[0]);
	matrix = AffineTransform.rotate(matrix, -angle);

	return {"scale": scale,
			"rotate": angle,
			"translate": [matrix[4], matrix[5]],
			"remainder": matrix};
}

function compose(composition) {
	return AffineTransform.scale(
			AffineTransform.rotate(
				composition.remainder,
				composition.rotate),
			composition.scale);
}


text:
<?php

/**
 * Rollback to previous release.
 */
task('rollback', function () {
    $basePath = config()->getPath();
    $releases = env()->getReleases();
    $currentReleasePath = env()->getReleasePath();

    if (isset($releases[1])) {
        $releaseDir = "{$basePath}/releases/{$releases[1]}";
        // Symlink to old release.
        run("rm -f current");
        run("ln -s $releaseDir current");

        // Remove release
        run("rm -rf $currentReleasePath");
    } else {
        writeln("<comment>No more releases you can revert to.</comment>");
    }
})->desc('Rollback to previous release');

/**
 * Preparing server for deployment.
 */
task('deploy:prepare', function () {
    $basePath = config()->getPath();

    // Check if base path exist.
    run("if [ ! -d $(echo $basePath) ]; then mkdir $basePath; fi", true);

    // Create releases dir.
    run("if [ ! -d \"releases\" ]; then mkdir releases; fi");

    // Create shared dir.
    run("if [ ! -d \"shared\" ]; then mkdir shared; fi");
})->desc('Preparing server for deploy');

/**
 * Update project code
 */
task('deploy:update_code', function () {
    $basePath = config()->getPath();
    $repository = get('repository', false);

    if (false === $repository) {
        throw new \RuntimeException('You have to specify repository.');
    }

    $release = date('Ymd') . substr((string)time(), -5);
    $releasePath = "$basePath/releases/$release";

    env()->setReleasePath($releasePath);
    env()->set('is_new_release', true);

    if (get('branch', false)) {
        $branch = get('branch', false);
        run("git clone --recursive -q $repository --branch $branch $releasePath");
    } else {
        run("git clone --recursive -q $repository $releasePath");
    }

    run("chmod -R g+w $releasePath");
})->desc('Updating code');

/**
 * Delete new release if something goes wrong
 */
task('deploy:rollback', function () {
    if (env()->get('is_new_release', false)) {
        $server = config()->getName();
        writeln("<error>Rolling back to previous release on server $server</error>");

        $releasePath = env()->getReleasePath();
        // Remove release
        run("rm -rf $releasePath");
    } else {
        writeln("<comment>If you want to rollback run \"rollback\" task</comment>");
    }
});

/**
 * Create symlinks for shared directories and files
 */
task('deploy:shared', function () {
    $basePath = config()->getPath();
    $sharedPath = "$basePath/shared";
    $releasePath = env()->getReleasePath();

    // User specified shared directories
    $sharedDirs = (array)get('shared_dirs', []);

    foreach ($sharedDirs as $dir) {
        // Remove dir from source
        run("if [ -d $(echo $releasePath/$dir) ]; then rm -rf $releasePath/$dir; fi");

        // Create shared dir if does not exist
        run("mkdir -p $sharedPath/$dir");

        // Symlink shared dir to release dir
        run("ln -nfs $sharedPath/$dir $releasePath/$dir");
    }

    // User specified shared files
    $sharedFiles = (array)get('shared_files', []);

    foreach ($sharedFiles as $file) {
        // Create dir of shared file
        run("mkdir -p $sharedPath/" . dirname($file));

        // Touch shared file
        run("touch $sharedPath/$file");

        // Symlink shared file to release file
        run("ln -nfs $sharedPath/$file $releasePath/$file");
    }
})->desc('Creating symlinks for shared files');

/**
 * Make writable dirs
 */
task('deploy:writable_dirs', function () {
    $user = config()->getUser();
    $wwwUser = config()->getWwwUser();
    $permissionMethod = get('permission_method', 'acl');
    $releasePath = env()->getReleasePath();

    cd($releasePath);

    // User specified writable dirs
    $dirs = (array)get('writable_dirs', []);

    switch ($permissionMethod) {
        case 'acl':
            $run = run("if which setfacl; then echo \"ok\"; fi");
            if (empty($run)) {
                writeln('<comment>Enable ACL support and install "setfacl"</comment>');
                return;
            }

            $commands = [
                'setfacl -R -m u:' . $user . ':rwX -m u:' . $wwwUser . ':rwX %s',
                'setfacl -dR -m u:' . $user . ':rwx -m u:' . $wwwUser . ':rwx %s'
            ];
            break;
        case 'chmod':
            $commands = [
                'chmod +a "' . $user . ' allow delete,write,append,file_inherit,directory_inherit" %s',
                'chmod +a "' . $wwwUser . ' allow delete,write,append,file_inherit,directory_inherit" %s'
            ];
            break;
        case 'chmod_bad':
            $commands = ['chmod -R a+w %s'];
            break;
    }

    $releasePath = env()->getReleasePath();
    foreach ($dirs as $dir) {
        // Create shared dir if does not exist
        run("mkdir -p $releasePath/$dir");
        foreach ($commands as $command) {
            run(sprintf($command, $dir));
        }
    }
})->desc('Make writable dirs');

/**
 * Vendors
 */
task('deploy:vendors', function () {
    $releasePath = env()->getReleasePath();

    cd($releasePath);
    $prod = get('env', 'prod');
    $php = php();

    // Check if we're to copy the vendors
    if (get('composer_copy_vendors', false)) {
        $releases = env()->getReleases();

        if (isset($releases[1])) {
            // Existing previous release, so copy vendors folder from it
            $basePath = config()->getPath();
            $vendorsDir = "{$basePath}/releases/{$releases[1]}/vendor";

            run("if [ -d $(echo $vendorsDir) ]; then cp -r $vendorsDir $releasePath; fi");
        }
    }

    $options = get('composer_install_options', '--no-dev --verbose --prefer-dist --optimize-autoloader --no-progress');
    run("SYMFONY_ENV=$prod $php composer.phar install $options");

})->desc('Installing vendors');

/**
 * Create symlink to last release
 */
task('deploy:symlink', function () {
    $releasePath = env()->getReleasePath();
    $releaseDir = get('release_dir', null);

    run("rm -f current && ln -s $releasePath current");

})->desc('Creating symlink to release');

/**
 * Cleanup old releases
 */
task('cleanup', function () {
    $releases = env()->getReleasesByTime();

    $keep = get('keep_releases', 3);

    while ($keep > 0) {
        array_shift($releases);
        --$keep;
    }

    foreach ($releases as $release) {
        run("rm -rf releases/$release");
    }

})->desc('Cleaning up old releases');

/**
 * Helper tasks
 */
task('deploy:start', function () {
});
task('deploy:end', function () {
});


text:
using UnityEngine;

namespace Klak.Wiring
{
    [AddComponentMenu("Klak/Wiring/Mixing/Float Mix")]
    public class FloatMix : NodeBase
    {
        #region Editable properties

        public enum ModulationType {
            Off, Add, Subtract, Multiply, Divide, Minimum, Maximum
        }

        [SerializeField]
        ModulationType _modulationType = ModulationType.Add;

        #endregion

        #region Node I/O

        [Inlet]
        public float input {
            set {
                if (!enabled) return;
                _inputValue = value;
                _outputEvent.Invoke(MixValues());
            }
        }

        [Inlet]
        public float modulation {
            set {
                if (!enabled) return;
                _modulationValue = value;
                _outputEvent.Invoke(MixValues());
            }
        }

        [SerializeField, Outlet]
        FloatEvent _outputEvent = new FloatEvent();

        #endregion

        #region Private members

        float _inputValue;
        float _modulationValue;

        float MixValues()
        {
            switch (_modulationType)
            {
                case ModulationType.Add:
                    return _inputValue + _modulationValue;
                case ModulationType.Subtract:
                    return _inputValue - _modulationValue;
                case ModulationType.Multiply:
                    return _inputValue * _modulationValue;
                case ModulationType.Divide:
                    return _inputValue / _modulationValue;
                case ModulationType.Minimum:
                    return Mathf.Min(_inputValue, _modulationValue);
                case ModulationType.Maximum:
                    return Mathf.Max(_inputValue, _modulationValue);
            }
            // Off
            return _inputValue;
        }

        #endregion
    }
}