text:
<?php

namespace Grid\Paragraph\Controller;

use Zork\Stdlib\Message;
use Grid\Core\Controller\AbstractListController;

/**
 * LayoutController
 *
 * @author David Pozsar <david.pozsar@megaweb.hu>
 */
class LayoutController extends AbstractListController
{

    /**
     * Get paginator list
     *
     * @return \Zend\Paginator\Paginator
     */
    protected function getPaginator()
    {
        return $this->getServiceLocator()
                    ->get( 'Grid\Paragraph\Model\Paragraph\Model' )
                    ->getPaginator( 'layout' );
    }

    /**
     * Edit a layout
     */
    public function editAction()
    {
        $params     = $this->params();
        $request    = $this->getRequest();
        $locator    = $this->getServiceLocator();
        $model      = $locator->get( 'Grid\Paragraph\Model\Paragraph\Model' )
                              ->setLocale( $this->getAdminLocale() );
        $form       = $locator->get( 'Form' )
                              ->create( 'Grid\Paragraph\Layout' );

        if ( ( $id = $params->fromRoute( 'id' ) ) )
        {
            $paragraph = $model->find( $id );

            if ( empty( $paragraph ) )
            {
                $this->getResponse()
                     ->setStatusCode( 404 );

                return;
            }

            if ( ! $paragraph->isEditable() )
            {
                $this->getResponse()
                     ->setStatusCode( 403 );

                return;
            }
        }
        else
        {
            if ( ! $this->getPermissionsModel()
                        ->isAllowed( 'paragraph.layout', 'create' ) )
            {
                $this->getResponse()
                     ->setStatusCode( 403 );

                return;
            }

            $paragraph = $model->create( array(
                'type'      => 'layout',
                'created'   => time(),
            ) );
        }

        /* @var $form \Zend\Form\Form */
        $form->setHydrator( $model->getMapper() )
             ->bind( $paragraph );

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

            if ( $form->isValid() && $paragraph->save() )
            {
                $this->messenger()
                     ->add( 'paragraph.form.layout.success',
                            'paragraph', Message::LEVEL_INFO );

                return $this->redirect()
                            ->toRoute( 'Grid\Paragraph\Layout\List', array(
                                'locale' => (string) $this->locale(),
                            ) );
            }
            else
            {
                $this->messenger()
                     ->add( 'paragraph.form.layout.failed',
                            'paragraph', Message::LEVEL_ERROR );
            }
        }

        $form->setCancel(
            $this->url()
                 ->fromRoute( 'Grid\Paragraph\Layout\List', array(
                        'locale' => (string) $this->locale(),
                    ) )
        );

        return array(
            'form'      => $form,
            'paragraph' => $paragraph,
        );
    }

    /**
     * Clone a layout
     */
    public function cloneAction()
    {
        if ( ! $this->getPermissionsModel()
                    ->isAllowed( 'paragraph.layout', 'create' ) )
        {
            $this->getResponse()
                 ->setStatusCode( 403 );

            return;
        }

        $params     = $this->params();
        $locator    = $this->getServiceLocator();
        $model      = $locator->get( 'Grid\Paragraph\Model\Paragraph\Model' )
                              ->setLocale( $this->getAdminLocale() );
        $paragraph  = $model->find( $params->fromRoute( 'id' ) );

        if ( empty( $paragraph ) || $paragraph->type !== 'layout' )
        {
            $this->getResponse()
                 ->setStatusCode( 404 );

            return;
        }

        $cloneId = $model->cloneFrom( $paragraph->id );

        if ( $cloneId )
        {
            $clone = $model->find( $cloneId );

            if ( ! empty( $clone ) )
            {
                $clone->name = rtrim( $clone->name ) . ' '
                             . $locator->get( 'Zork\I18n\Translator\Translator' )
                                       ->translate( 'default.cloned', 'default' );

                $clone->save();
            }

            $this->messenger()
                 ->add( 'paragraph.action.clone.success',
                        'paragraph', Message::LEVEL_INFO );
        }
        else
        {
            $this->messenger()
                 ->add( 'paragraph.action.clone.failed',
                        'paragraph', Message::LEVEL_ERROR );
        }

        return $this->redirect()
                    ->toRoute( 'Grid\Paragraph\Layout\List', array(
                        'locale' => (string) $this->locale(),
                    ) );
    }

    /**
     * Delete a layout
     */
    public function deleteAction()
    {
        $params     = $this->params();
        $locator    = $this->getServiceLocator();
        $model      = $locator->get( 'Grid\Paragraph\Model\Paragraph\Model' );
        $paragraph  = $model->find( $params->fromRoute( 'id' ) );

        if ( empty( $paragraph ) || $paragraph->type !== 'layout' )
        {
            $this->getResponse()
                 ->setStatusCode( 404 );

            return;
        }

        if ( ! $paragraph->isDeletable() )
        {
            $this->getResponse()
                 ->setStatusCode( 403 );

            return;
        }

        if ( $paragraph->delete() )
        {
            $this->messenger()
                 ->add( 'paragraph.action.delete.success',
                        'paragraph', Message::LEVEL_INFO );
        }
        else
        {
            $this->messenger()
                 ->add( 'paragraph.action.delete.failed',
                        'paragraph', Message::LEVEL_ERROR );
        }

        return $this->redirect()
                    ->toRoute( 'Grid\Paragraph\Layout\List', array(
                        'locale' => (string) $this->locale(),
                    ) );
    }

}

redpajama_set_name: RedPajamaGithub


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 org.jctools.queues.atomic;

import org.junit.Test;

import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.sameInstance;
import static org.jctools.queues.matchers.Matchers.emptyAndZeroSize;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

public class AtomicSpscArrayQueueTest {
    @Test
    public void shouldWorkAfterWrap(){
        // Arrange
        final SpscAtomicArrayQueue<Object> q = new SpscAtomicArrayQueue<Object>(1024);
        // starting point for empty queue at max long, next offer will wrap the producerIndex
        q.consumerIndex.set(Long.MAX_VALUE);
        q.producerIndex.set(Long.MAX_VALUE);
        q.producerLookAhead = Long.MAX_VALUE;
        // valid starting point
        assertThat(q, emptyAndZeroSize());

        // Act
        // assert offer is successful
        final Object e = new Object();
        assertTrue(q.offer(e));
        // size is computed correctly after wrap
        assertThat(q, not(emptyAndZeroSize()));
        assertThat(q, hasSize(1));

        // now consumer index wraps
        final Object poll = q.poll();
        assertThat(poll, sameInstance(e));
        assertThat(q, emptyAndZeroSize());

        // let's go again
        assertTrue(q.offer(e));
        assertThat(q, not(emptyAndZeroSize()));

        final Object poll2 = q.poll();
        assertThat(poll2, sameInstance(e));
        assertThat(q, emptyAndZeroSize());
    }
}


text:
namespace syncer {

typedef std::map<ModelType, size_t> TypeToIndexMap;

CommitProcessor::CommitProcessor(CommitContributorMap* commit_contributor_map)
    : commit_contributor_map_(commit_contributor_map) {}

CommitProcessor::~CommitProcessor() {}

void CommitProcessor::GatherCommitContributions(
    ModelTypeSet commit_types,
    size_t max_entries,
    bool cookie_jar_mismatch,
    bool cookie_jar_empty,
    Commit::ContributionMap* contributions) {
  size_t num_entries = 0;
  for (ModelTypeSet::Iterator it = commit_types.First();
       it.Good(); it.Inc()) {
    CommitContributorMap::iterator cm_it =
        commit_contributor_map_->find(it.Get());
    if (cm_it == commit_contributor_map_->end()) {
      NOTREACHED()
          << "Could not find requested type " << ModelTypeToString(it.Get())
          << " in contributor map.";
      continue;
    }
    size_t spaces_remaining = max_entries - num_entries;
    std::unique_ptr<CommitContribution> contribution =
        cm_it->second->GetContribution(spaces_remaining);
    if (contribution) {
      num_entries += contribution->GetNumEntries();
      contributions->insert(std::make_pair(it.Get(), std::move(contribution)));

      if (it.Get() == SESSIONS) {
        UMA_HISTOGRAM_BOOLEAN("Sync.CookieJarMatchOnNavigation",
                              !cookie_jar_mismatch);
        if (cookie_jar_mismatch) {
          UMA_HISTOGRAM_BOOLEAN("Sync.CookieJarEmptyOnMismatch",
                                cookie_jar_empty);
        }
      }
    }
    if (num_entries >= max_entries) {
      DCHECK_EQ(num_entries, max_entries)
          << "Number of commit entries exceeeds maximum";
      break;
    }
  }
}

}  // namespace syncer


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
  Module: Rcurse

    — Documentation by YARD 0.8.7.4

</title>

  <link rel="stylesheet" href="css/style.css" type="text/css" charset="utf-8" />

  <link rel="stylesheet" href="css/common.css" type="text/css" charset="utf-8" />

  <link rel="stylesheet" href="css/docs.css" type="text/css" charset="utf-8" />

    Index (R) »

    Rcurse

(no frames)

      Class List

      Method List

      File List

Module: Rcurse

Defined in:

lib/rcurse.rb,

  lib/rcurse/engine.rb,
 lib/rcurse/helper.rb,
 lib/rcurse/context.rb

Overview

Rcurse - super simple template engine

Defined Under Namespace

      Classes: Context, Engine, Helper

      Class Method Summary
      (collapse)

      + (Object) add_helper(helper)

Add a helper to Rcurse, called automatically when creating a helper.

      + (Hash<Rcurse::Helper>) helpers

Available helpers.

      + (String) render(content, context = Context.new)

Render a template.

      + (String) render_file(filename, out_filename, context = Context.new)

Render a template file, optionally writing output to another file.

Class Method Details

    + (<tt>Object</tt>) add_helper(helper)

Add a helper to Rcurse, called automatically when creating a helper

5
6
7

# File 'lib/rcurse/helper.rb', line 5

def self.add_helper helper
    @helpers[helper.name] = helper
end

    + (<tt>Hash<Rcurse::Helper></tt>) helpers

Available helpers

Returns:

        (<tt>Hash<Rcurse::Helper></tt>)

        —

Available helpers, with helper names as keys

12
13
14

# File 'lib/rcurse/helper.rb', line 12

def self.helpers
    @helpers
end

    + (<tt>String</tt>) render(content, context = Context.new)

Render a template

Parameters:

        content

        (<tt>String</tt>)

        —

A String containing the Rcurse template

        context

        (<tt>Rcurse::Context</tt>)

        (defaults to: <tt>Context.new</tt>)

        —

a context for the template

Returns:

        (<tt>String</tt>)

        —

The rendered template

73
74
75
76

# File 'lib/rcurse/engine.rb', line 73

def self.render content, context = Context.new
    # proxy
    Rcurse::Engine.render content, context
end

    + (<tt>String</tt>) render_file(filename, out_filename, context = Context.new)

Render a template file, optionally writing output to another file

Parameters:

        filename

        (<tt>String</tt>)

        —

A String containing the Rcurse template

        out_filename

        (<tt>String</tt>)

        —

Optional, file to write output to

        context

        (<tt>Rcurse::Context</tt>)

        (defaults to: <tt>Context.new</tt>)

        —

a context for the template

Returns:

        (<tt>String</tt>)

        —

The rendered template

79
80
81
82

# File 'lib/rcurse/engine.rb', line 79

def self.render_file filename, out_filename, context = Context.new
    # proxy
    Rcurse::Engine.render_file filename, out_filename, context
end


text:
module Language.CIL.Goto (goto) where

import Control.Monad.State

import Language.CIL.StmtCore
import qualified Language.CIL.StmtGoto as G
import Language.CIL.Types
import Language.CIL.Utils

-- | Given a max call depth and a 'Stmt' program, reduces a program to assignments, if statements, and goto jumps.
--   The function errors out if during function inlining process, the call depth exceeds the max depth.
goto :: Int -> Stmt -> G.Stmt
goto maxDepth stmt = convert $ evalState (reduce maxDepth [] stmt) (0, [])

type Label = State (Int, [(Name, Name)])

nextLabel :: Label Name
nextLabel = do
  (n, t) <- get
  put (n + 1, t)
  return $ "__label_" ++ show n

label :: Name -> Label Name
label name = do
  (_, t) <- get
  case lookup name t of
    Nothing -> do
      l <- nextLabel
      (n, t) <- get
      put (n, t ++ [(name, l)])
      return l
    Just l -> return l

withScope :: Label a -> Label a
withScope scope = do
  (n, t) <- get
  put (n, [])
  a <- scope
  (n, _) <- get
  put (n, t)
  return a

convert :: Stmt -> G.Stmt
convert a = case a of
  Null -> G.Null
  Label name stmt p -> G.Label name (convert stmt) p
  Compound stmts p -> G.Compound (map convert stmts) p
  TypeDecl name typ p -> G.TypeDecl name typ p
  VariableDef name typ init p -> G.VariableDef name typ init p
  AssignExpr a b p -> G.AssignExpr a b p
  If a b c p -> G.If a (convert b) (convert c) p
  Goto name p -> G.Goto name p
  a -> err' a $ "goto reduction failed: " ++ show a

reduce :: Int -> [Name] -> Stmt -> Label Stmt
reduce maxDepth callTrace a = case a of
  Null -> return Null
  TypeDecl _ _ _ -> return a
  VariableDef _ _ _ _ -> return a
  AssignExpr _ _ _ -> return a
  Goto name p -> do
    name <- label name
    return $ Goto name p
  Compound stmts p -> do
    stmts <- mapM (reduce maxDepth callTrace) stmts
    return $ Compound stmts p
  If a b c p -> do
    b <- reduce maxDepth callTrace b
    c <- reduce maxDepth callTrace c
    return $ If a b c p
  While cond stmt p -> do
    before <- nextLabel
    after  <- nextLabel
    stmt <- reduceWhile maxDepth callTrace after stmt
    return $ Label before (Compound [If cond (Compound [stmt, Goto before p] p) Null p, Label after Null p] p) p
  Break _ -> notSupported' a "break outside of loop or switch"
  Case _ _ _ -> notSupported' a "case outside of switch"
  Default _ _ -> notSupported' a "default outside of switch"
  Switch cond stmt p -> do
    after <- nextLabel
    (cases, stmts) <- rewriteCases (Label after p) stmts
  _ -> notSupported' a "statement for goto transform"

  {-
  FunctionDef Name Type [(Name, Type)] Stmt Position
  AssignApply Expr Apply Position
  StmtApply Apply Position
  Return (Maybe Expr) Position
  -}

reduceWhile :: Int -> [Name] -> Name -> Stmt -> Label Stmt
reduceWhile maxDepth callTrace after a = case a of
  Break p -> return $ Goto after p
  Compound stmts p -> do
    stmts <- mapM (reduceWhile maxDepth callTrace after) stmts
    return $ Compound stmts p
  If a b c p -> do
    b <- reduceWhile maxDepth callTrace after b
    c <- reduceWhile maxDepth callTrace after c
    return $ If a b c p
  a -> reduce maxDepth callTrace a

rewriteCases :: Name -> [Stmt] -> ([(Expr, Name)], [Stmt])
rewriteCases end [] = []


text:
<?php

namespace NowyBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class NowyBundle extends Bundle
{
}


text:
package gui;

import java.util.List;

import javax.swing.ComboBoxModel;
import javax.swing.event.ListDataListener;

/**
 *
This class provides a <tt>ComboModel</tt> for a <tt>JComboBox</tt>. Underneath the model lies a
 * data matrix that must be implemented by a <tt>List<Object[]></tt> with elements of the
 * <tt>List</tt> containing the rows and <tt>Object[]</tt>, which must all have the same
 * length, containing the columns.
 *
 *
During instantiation, one column of the table has to be
 * selected as the column to be displayed. But every entry of the table can later be retrieved
 * by calling {@link #getValue(int, int) getValue} method.
 *
 * @author Lasse Osterhagen
 *
 */

public class MatrixComboBoxModel {

	private int displayColumn;
	private List<Object[]> rows;
	private ComboModel comboModel = new ComboModel();

	private class ComboModel implements ComboBoxModel<Object> {
		private int index = 0;

		@Override
		public Object getElementAt(int index) {
			return rows.get(index)[displayColumn];
		}

		@Override
		public int getSize() {
			return rows.size();
		}

		@Override
		public Object getSelectedItem() {
			if(index<0) return null;
			return rows.get(index)[displayColumn];
		}

		@Override
		public void setSelectedItem(Object obj) {
			for(int i=0; i<rows.size(); ++i) {
				if(obj.equals(rows.get(i)[displayColumn])) {
					index = i;
					break;
				}
			}
		}

		@Override
		public void addListDataListener(ListDataListener arg0) {}
		@Override
		public void removeListDataListener(ListDataListener arg0) {}
	}

	/**
	 * Instantiate a MatrixComboBox.
	 * @param rows the content of the table. All <tt>Object[]</tt> must have the same size.
	 * @param displayColumn the column of the table to be displayed
	 */
	public MatrixComboBoxModel(List<Object[]> rows, int displayColumn) {
		this.rows = rows;
		this.displayColumn = displayColumn;
	}

	/**
	 * Get the implementation of <tt>ComboModel</tt>.
	 * @return the implementation of <tt>ComboModel</tt>
	 */
	public ComboModel getComboModel() {
		return comboModel;
	}

	/**
	 * Get the value of the underlying data matrix at the specified position
	 * @param row row index (starting at 0)
	 * @param column column index (starting at 0)
	 * @return the value
	 */
	public Object getValue(int row, int column) {
		return rows.get(row)[column];
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>io.oasp.java.dev</groupId>
    <artifactId>oasp4j-modules</artifactId>
    <version>dev-SNAPSHOT</version>
  </parent>
  <groupId>io.oasp.java.modules</groupId>
  <artifactId>oasp4j-json</artifactId>
  <version>${oasp4j.version}</version>
  <packaging>jar</packaging>
  <name>${project.artifactId}</name>
  <description>JSON Support Module of the Open Application Standard Platform for Java (OASP4J).</description>

  <dependencies>
    <dependency>
      <groupId>com.fasterxml.jackson.jaxrs</groupId>
      <artifactId>jackson-jaxrs-json-provider</artifactId>
    </dependency>
    <dependency>
      <groupId>javax.inject</groupId>
      <artifactId>javax.inject</artifactId>
    </dependency>
    <dependency>
      <groupId>net.sf.m-m-m</groupId>
      <artifactId>mmm-util-core</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
    </dependency>
    <!-- Optional, only for mapping Pageable to/from JSON -->
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-commons</artifactId>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>io.oasp.java.modules</groupId>
      <artifactId>oasp4j-test</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

</project>


text:
{% extends "jqmobile/base.html" %}
{% load i18n %}

{% block content %}
{% spaceless %}
<form action="{{ app_path }}" class="panel" method="post" selected="true">{% csrf_token %}
    {% if error_message %}
{{ error_message }}
{% endif %}

            {% trans "Username:" %}
            <input type="text" name="username" id="id_username" value="" />

            {% trans "Password:" %}
            <input type="password" name="password" id="id_password" value="" />
            <input type="hidden" name="this_is_the_login_form" value="1" />
            <input type="hidden" name="post_data" value="{{ post_data }}" />

            <input type="submit" data-theme="b" value="{% trans "Log in" %}">

</form>

{% endspaceless %}
{% endblock %}


text:
var platform = require('../everlive.platform');
var WebFileStore = require('./WebFileStore');
var NativeScriptFileStore = require('./NativeScriptFileStore');
var _ = require('../common')._;

'use strict';

if (platform.isNativeScript) {
    module.exports = NativeScriptFileStore;
} else if (platform.isCordova || platform.isDesktop) {
    module.exports = WebFileStore;
} else {
    module.exports = _.noop;
}


text:
package glass.phil.monzo.presentation.login;

import android.os.Parcelable;

import com.google.auto.value.AutoValue;

import glass.phil.monzo.presentation.base.BasePresenter;

interface LoginContract {
  abstract class Presenter extends BasePresenter<LoginView, SavedState> {
    abstract void onLoginResult(String code, String state);
    abstract void retry();
  }

  interface LoginView {
    void render(ViewModel model);
  }

  @AutoValue abstract class ViewModel {
    static ViewModel just(String state) {
      return new AutoValue_LoginContract_ViewModel(state, false, false, false);
    }

    abstract String state();
    abstract boolean loading();
    abstract boolean error();
    abstract boolean loginComplete();

    abstract ViewModel withState(String state);
    abstract ViewModel withLoading(boolean loading);
    abstract ViewModel withError(boolean error);
    abstract ViewModel withLoginComplete(boolean loginComplete);
  }

  @AutoValue abstract class SavedState implements Parcelable {
    static SavedState create(String state, boolean error) {
      return new AutoValue_LoginContract_SavedState(state, error);
    }

    abstract String state();
    abstract boolean error();
  }
}


text:
package org.iotp.infomgt.data.id;

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

import java.util.UUID;

import org.iotp.infomgt.data.common.ThingType;

public class AlarmId extends UUIDBased implements EntityId {

    private static final long serialVersionUID = 1L;

    @JsonCreator
    public AlarmId(@JsonProperty("id") UUID id) {
        super(id);
    }

    public static AlarmId fromString(String alarmId) {
        return new AlarmId(UUID.fromString(alarmId));
    }

    @JsonIgnore
    @Override
    public ThingType getEntityType() {
        return ThingType.ALARM;
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycotaxon 60: 424 (1996)

#### Original name
Milospium lacoizquetae Etayo & Diederich, 1996

### Remarks
null


text:
<?php
    //var_dump($this);
    $images = $this->serviceManager()->get('AceLibrary\Service\ViatorService')->getProductPhotos($this->code); ?>

            <a href="<?php echo $this->thumbnailURL; ?>" class="preview" target="_blank" title="<?php echo $this->title; ?>">
                <img class="product-primary-image" src="<?php echo $this->thumbnailURL; ?>"/>

<?php echo $this->title; ?>

<?php echo $this->primaryDestinationName;?>

<?php echo $this->shortDescription; ?>

                <a href="<?php echo $this->url("tours", array("action"=>"viewviator", "id"=>$this->code));?>" class="btn btn-info">Read More
                Add to Planner

<?php if ($images):?>

        <?php foreach ($images->data as $image): ?>
            <?php //var_dump($image);?>
            <a href="<?php echo $image->photoURL; ?>" class="preview" target="_blank">
                <img class="product-gallery-image" src="<?php echo $image->thumbnailURL; ?>"/>

        <?php endforeach;?>

<?php  endif; ?>


text:
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/core/css/cssom/css_skew_y.h"

#include "third_party/blink/renderer/core/css/css_function_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
#include "third_party/blink/renderer/core/css/cssom/css_numeric_value.h"
#include "third_party/blink/renderer/core/css/cssom/css_style_value.h"
#include "third_party/blink/renderer/core/css/cssom/css_unit_value.h"
#include "third_party/blink/renderer/core/geometry/dom_matrix.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"

namespace blink {

namespace {

bool IsValidSkewYAngle(CSSNumericValue* value) {
  return value &&
         value->Type().MatchesBaseType(CSSNumericValueType::BaseType::kAngle);
}

}  // namespace

CSSSkewY* CSSSkewY::Create(CSSNumericValue* ay,
                           ExceptionState& exception_state) {
  if (!IsValidSkewYAngle(ay)) {
    exception_state.ThrowTypeError("CSSSkewY does not support non-angles");
    return nullptr;
  }
  return MakeGarbageCollected<CSSSkewY>(ay);
}

void CSSSkewY::setAy(CSSNumericValue* value, ExceptionState& exception_state) {
  if (!IsValidSkewYAngle(value)) {
    exception_state.ThrowTypeError("Must specify an angle unit");
    return;
  }
  ay_ = value;
}

CSSSkewY* CSSSkewY::FromCSSValue(const CSSFunctionValue& value) {
  DCHECK_GT(value.length(), 0U);
  DCHECK_EQ(value.FunctionType(), CSSValueID::kSkewY);
  if (value.length(), 1U) {
    return CSSSkewY::Create(
        CSSNumericValue::FromCSSValue(To<CSSPrimitiveValue>(value.Item(0))));
  }
  NOTREACHED();
  return nullptr;
}

DOMMatrix* CSSSkewY::toMatrix(ExceptionState&) const {
  CSSUnitValue* ay = ay_->to(CSSPrimitiveValue::UnitType::kDegrees);
  DCHECK(ay);
  DOMMatrix* result = DOMMatrix::Create();
  result->skewYSelf(ay->value());
  return result;
}

const CSSFunctionValue* CSSSkewY::ToCSSValue() const {
  const CSSValue* ay = ay_->ToCSSValue();
  if (!ay)
    return nullptr;

  CSSFunctionValue* result =
      MakeGarbageCollected<CSSFunctionValue>(CSSValueID::kSkewY);
  result->Append(*ay);
  return result;
}

CSSSkewY::CSSSkewY(CSSNumericValue* ay)
    : CSSTransformComponent(true /* is2D */), ay_(ay) {
  DCHECK(ay);
}

}  // namespace blink


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rop.control.step;

import com.rop.control.action.ShuttleToBottomXSecsAction;
import com.rop.control.action.DelayAction;

/**
 * Step 3 - Shuttle to top
 *
 * @author robotics
 */
public class ClimbStep6a extends Step
{
    protected void stepInit()
    {
        actions.addElement( new ShuttleToBottomXSecsAction( 3.0 ) );
        actions.addElement( new DelayAction( 6.0 ) );
    }
}


text:
/**
 * Created by Mehmet Ali Peker on 29.12.2016.
 */
tinymce.PluginManager.add('smileys', function (editor,url) {

    var defaultSmileys = [
        [
            { shortcut: '(^^^)', url: url + '/img/shark.gif', title: 'shark' },
            { shortcut: 'O:)', url: url + '/img/angel.png', title: 'angel' },
            { shortcut: 'o.O', url: url + '/img/confused.png', title: 'confused' },
            { shortcut: '3:)', url: url + '/img/devil.png', title: 'devil' },
            { shortcut: ':-O', url: url + '/img/gasp.png', title: 'gasp' },
            { shortcut: '8-)', url: url + '/img/glasses.png', title: 'glasses' },
            { shortcut: ':-D', url: url + '/img/grin.png', title: 'grin' }
        ],
        [
            { shortcut: ':-)', url: url + '/img/smile.png', title: 'smile' },
            { shortcut: ":'(", url: url + '/img/cry.png', title: 'cry' },
            { shortcut: '<3', url: url + '/img/heart.png', title: 'heart' },
            { shortcut: '^_^', url: url + '/img/kiki.png', title: 'kiki' },
            { shortcut: ':-*', url: url + '/img/kiss.png', title: 'kiss' },
            { shortcut: ':v', url: url + '/img/pacman.png', title: 'pacman' },
            { shortcut: '<(�)', url: url + '/img/penguin.gif', title: 'penguin' }
        ],
        [
            { shortcut: ':|]', url: url + '/img/robot.gif', title: 'robot' },
            { shortcut: '-_-', url: url + '/img/squint.png', title: 'squint' },
            { shortcut: '8-|', url: url + '/img/sunglasses.png', title: 'sunglasses' },
            { shortcut: ':-P', url: url + '/img/tongue.png', title: 'tongue' },
            { shortcut: ':/', url: url + '/img/unsure.png', title: 'unsure' },
            { shortcut: '>:O', url: url + '/img/upset.png', title: 'upset' },
            { shortcut: '>:(', url: url + '/img/grumpy.png', title: 'grumpy' }
        ]
    ];

    var smileys = editor.settings.smileys || defaultSmileys, fullSmileysList = editor.settings.extended_smileys ? smileys.concat(editor.settings.extended_smileys) : smileys;

    function getHtml() {
        var smileysHtml;

        smileysHtml = '
';

        tinymce.each(fullSmileysList, function (row) {
            smileysHtml += '
';

            tinymce.each(row, function (icon) {
                smileysHtml += '	';
            });

            smileysHtml += '
';
        });

        smileysHtml += '
';

        return smileysHtml;
    }

    function concatArray(array) {
        var each = tinymce.each, result = [];
        each(array, function (item) {
            result = result.concat(item);
        });
        return result.length > 0 ? result : array;
    }

    function findAndReplaceDOMText(regex, node, replacementNode, captureGroup, schema) {
        var m, matches = [], text, count = 0, doc;
        var blockElementsMap, hiddenTextElementsMap, shortEndedElementsMap;

        doc = node.ownerDocument;
        blockElementsMap = schema.getBlockElements(); // H1-H6, P, TD etc
        hiddenTextElementsMap = schema.getWhiteSpaceElements(); // TEXTAREA, PRE, STYLE, SCRIPT
        shortEndedElementsMap = schema.getShortEndedElements(); // BR, IMG, INPUT

        function getMatchIndexes(m, captureGroup) {
            captureGroup = captureGroup || 0;

            var index = m.index;

            if (captureGroup > 0) {
                var cg = m[captureGroup];
                index += m[0].indexOf(cg);
                m[0] = cg;
            }

            return [index, index + m[0].length, [m[0]]];
        }

        function getText(node) {
            var txt;

            if (node.nodeType === 3) {
                return node.data;
            }

            if (hiddenTextElementsMap[node.nodeName] && !blockElementsMap[node.nodeName]) {
                return '';
            }

            txt = '';

            if (blockElementsMap[node.nodeName] || shortEndedElementsMap[node.nodeName]) {
                txt += '\n';
            }

            if ((node = node.firstChild)) {
                do {
                    txt += getText(node);
                } while ((node = node.nextSibling));
            }

            return txt;
        }

        function stepThroughMatches(node, matches, replaceFn) {
            var startNode, endNode, startNodeIndex,
                endNodeIndex, innerNodes = [], atIndex = 0, curNode = node,
                matchLocation = matches.shift(), matchIndex = 0;

            out: while (true) {
                if (blockElementsMap[curNode.nodeName] || shortEndedElementsMap[curNode.nodeName]) {
                    atIndex++;
                }

                if (curNode.nodeType === 3) {
                    if (!endNode && curNode.length + atIndex >= matchLocation[1]) {
                        // We've found the ending
                        endNode = curNode;
                        endNodeIndex = matchLocation[1] - atIndex;
                    } else if (startNode) {
                        // Intersecting node
                        innerNodes.push(curNode);
                    }

                    if (!startNode && curNode.length + atIndex > matchLocation[0]) {
                        // We've found the match start
                        startNode = curNode;
                        startNodeIndex = matchLocation[0] - atIndex;
                    }

                    atIndex += curNode.length;
                }

                if (startNode && endNode) {
                    curNode = replaceFn({
                        startNode: startNode,
                        startNodeIndex: startNodeIndex,
                        endNode: endNode,
                        endNodeIndex: endNodeIndex,
                        innerNodes: innerNodes,
                        match: matchLocation[2],
                        matchIndex: matchIndex
                    });

                    // replaceFn has to return the node that replaced the endNode
                    // and then we step back so we can continue from the end of the
                    // match:
                    atIndex -= (endNode.length - endNodeIndex);
                    startNode = null;
                    endNode = null;
                    innerNodes = [];
                    matchLocation = matches.shift();
                    matchIndex++;

                    if (!matchLocation) {
                        break; // no more matches
                    }
                } else if ((!hiddenTextElementsMap[curNode.nodeName] || blockElementsMap[curNode.nodeName]) && curNode.firstChild) {
                    // Move down
                    curNode = curNode.firstChild;
                    continue;
                } else if (curNode.nextSibling) {
                    // Move forward:
                    curNode = curNode.nextSibling;
                    continue;
                }

                // Move forward or up:
                while (true) {
                    if (curNode.nextSibling) {
                        curNode = curNode.nextSibling;
                        break;
                    } else if (curNode.parentNode !== node) {
                        curNode = curNode.parentNode;
                    } else {
                        break out;
                    }
                }
            }
        }

        /**
         * Generates the actual replaceFn which splits up text nodes
         * and inserts the replacement element.
         */
        function genReplacer(nodeName) {
            var makeReplacementNode;

            if (typeof nodeName != 'function') {
                var stencilNode = nodeName.nodeType ? nodeName : doc.createElement(nodeName);

                makeReplacementNode = function () {
                    var clone = stencilNode.cloneNode(false);
                    return clone;
                };
            } else {
                makeReplacementNode = nodeName;
            }

            return function replace(range) {
                var before, after, parentNode, startNode = range.startNode,
                    endNode = range.endNode;

                if (startNode === endNode) {
                    var node = startNode;

                    parentNode = node.parentNode;
                    if (range.startNodeIndex > 0) {
                        // Add `before` text node (before the match)
                        before = doc.createTextNode(node.data.substring(0, range.startNodeIndex));
                        parentNode.insertBefore(before, node);
                    }

                    // Create the replacement node:
                    var el = makeReplacementNode();
                    parentNode.insertBefore(el, node);
                    if (range.endNodeIndex < node.length) {
                        // Add `after` text node (after the match)
                        after = doc.createTextNode(node.data.substring(range.endNodeIndex));
                        parentNode.insertBefore(after, node);
                    }

                    node.parentNode.removeChild(node);

                    return el;
                }
            };
        }

        text = getText(node);
        if (!text) {
            return;
        }
        while ((m = regex.exec(text))) {
            matches.push(getMatchIndexes(m, captureGroup));
        }

        if (matches.length) {
            count = matches.length;
            stepThroughMatches(node, matches, genReplacer(replacementNode));
        }

        return count;
    }

    function replaceAllMatches(smiley) {
        var each = tinymce.each, node = editor.selection.getNode(), marker, text;
        if (typeof (smiley.shortcut) === 'string') {
            text = smiley.shortcut.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");

            marker = editor.dom.create('img', { "src": smiley.url,"data-mce-src": smiley.url, "title": smiley.title });

            return findAndReplaceDOMText(new RegExp(text, 'gi'), node, marker, false, editor.schema);
        }
        else if (Array.isArray(smiley.shortcut)) {
            each(smiley.shortcut, function(item) {

                marker = editor.dom.create('img', { "src": smiley.url, "title": smiley.title });

                return findAndReplaceDOMText(new RegExp(item.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), 'gi'), node, marker, false, editor.schema);
            });
        }
    }

    editor.on("keyup", function (e) {
        if (!!editor.settings.auto_convert_smileys) {
            var each = tinymce.each, selection = editor.selection, node = selection.getNode();
            if (node) {
                each(concatArray(fullSmileysList), function (smiley) {
                    replaceAllMatches(smiley);
                });
            }
        }
    });

    editor.addButton('smileys', {
        type: 'panelbutton',
        icon: 'emoticons',
        panel: {
            autohide: true,
            html: getHtml,
            onclick: function (e) {
                var linkElm = editor.dom.getParent(e.target, 'a');

                if (linkElm) {
                    editor.insertContent('');
                    this.hide();
                }
            }
        },
        tooltip: 'Gülücükler'
    });
});


text:
<bill session="110" type="sr" number="645" updated="2009-01-09T21:19:00-05:00">
	<status><vote date="1221019200" datetime="2008-09-10" where="s" result="pass" how="by Unanimous Consent" roll=""/></status>

	<introduced date="1217563200" datetime="2008-08-01"/>
	<titles>
		<title type="official" as="introduced">A resolution honoring the life of Anne Legendre Armstrong.</title>
	</titles>
	<sponsor id="300027"/>
	<cosponsors>
		<cosponsor id="300054" joined="2008-08-01"/>
	</cosponsors>
	<actions>
		<action date="1217563200" datetime="2008-08-01"><text>Referred to the Committee on the Judiciary.</text><reference label="text of measure as introduced" ref="CR S8049"/></action>
		<action date="1221019200" datetime="2008-09-10"><text>Senate Committee on the Judiciary discharged by Unanimous Consent.</text><reference label="consideration" ref="CR S8326"/></action>
		<vote date="1221019200" how="by Unanimous Consent" datetime="2008-09-10" where="s" type="vote" result="pass" ><text>Resolution agreed to in Senate without amendment and with a preamble by Unanimous Consent.</text><reference label="text" ref="CR S8326"/></vote>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>

	9/10/2008--Passed Senate without amendment. (This measure has not been amended since it was introduced. The summary of that version is repeated here.)
Honors the life of Anne Legendre Armstrong (first female co-chair of the Republican National Committee and former U.S. Ambassador to the United Kingdom).

</bill>


text:
DROP DATABASE IF EXISTS crave;
CREATE DATABASE crave;

use crave;

DROP TABLE IF NOT EXISTS resturants;
CREATE TABLE resturants (
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(255) NOT NULL,
  address varchar(255) NOT NULL,
  phone varchar(10),
);

DROP TABLE IF EXISTS dishes;
CREATE TABLE dishes (
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(255),
  rating int(1),
  resturant_id int(11) NOT NULL,
);


text:
const { pickKey } = require('../../utils/functionalHelpers')
const getDmTasks = require('./taskLists/dmTasks')
const { getRoTasksPostApproval, getRoTasks } = require('./taskLists/roTasks')
const { getCaTasksEligibility, getCaTasksFinalChecks, getCaTasksPostApproval } = require('./taskLists/caTasks')
const getVaryTasks = require('./taskLists/varyTasks')

const taskListsConfig = {
  caTasksEligibility: {
    stages: ['ELIGIBILITY', 'UNSTARTED'],
    role: 'CA',
  },
  caTasksPostApproval: {
    stages: ['DECIDED', 'MODIFIED', 'MODIFIED_APPROVAL'],
    role: 'CA',
  },
  caTasksFinalChecks: {
    stages: ['PROCESSING_CA', 'PROCESSING_RO', 'APPROVAL'],
    role: 'CA',
  },
  roTasks: {
    stages: ['PROCESSING_RO', 'PROCESSING_CA', 'APPROVAL', 'ELIGIBILITY'],
    role: 'RO',
  },
  roTasksPostApproval: {
    stages: ['DECIDED', 'MODIFIED', 'MODIFIED_APPROVAL'],
    role: 'RO',
  },
  dmTasks: {
    role: 'DM',
  },
}

module.exports = (
  role,
  postRelease,
  { decisions, tasks, stage },
  { version, versionDetails, approvedVersion = {}, approvedVersionDetails = {} } = {},
  allowedTransition
) => {
  const taskList = getTaskList(role, stage, postRelease)

  const getTaskListTasksMethod = {
    dmTasks: getDmTasks,
    roTasks: getRoTasks,
    roTasksPostApproval: getRoTasksPostApproval,
    caTasksEligibility: getCaTasksEligibility,
    caTasksFinalChecks: getCaTasksFinalChecks,
    caTasksPostApproval: getCaTasksPostApproval(stage),
    vary: getVaryTasks({ version, versionDetails, approvedVersion, approvedVersionDetails }),
  }

  if (!getTaskListTasksMethod[taskList]) {
    return [
      {
        title: 'No active licence',
        action: { type: 'link', text: 'Return to case list', href: '/caseList/' },
      },
    ]
  }

  return getTaskListTasksMethod[taskList]({ decisions, tasks, stage, allowedTransition })
}

function getTaskList(role, stage, postRelease) {
  if (postRelease) {
    return 'vary'
  }

  function roleAndStageMatch(view) {
    if (view.role !== role) {
      return false
    }
    if (!view.stages) {
      return true
    }
    return view.stages.includes(stage)
  }

  return pickKey(roleAndStageMatch, taskListsConfig) || 'noTaskList'
}


text:
if (Posts.find().count() === 0) {
  var now   = new Date().getTime();

  var tomId = Meteor.users.insert({
    profile: {name:'Tom Coleman'}
  });
  var tom = Meteor.users.findOne(tomId);

  var sachaId = Meteor.users.insert({
    profile: { name:'Sacha Greif'}
  });
  var sacha = Meteor.users.findOne(sachaId);

  var telescopeId = Posts.insert({
    title : 'Introducing Telescope' ,
    url : 'http://sachagreif.com/introducing-telescope' ,
    userId: sacha._id ,
    author:sacha.profile.name ,
    submitted: now - 7*3600 * 1000
  });

  Comments.insert({
    postId: telescopeId ,
    userId: tom._id ,
    author: tom.profile.name,
    submitted: now - 5*3600*1000 ,
    body: 'interesting projects sacha, can I get involved?'
  });

  Comments.insert({
    postId: telescopeId,
    userId: sacha._id ,
    author: sacha.profile.name,
    submitted: now - 3*3600*1000,
    body: 'You sure can Tom!'
  });

  Posts.insert({
    title : 'Meteor' ,
    url : 'http://meteor.com',
    userId: tom._id ,
    author: tom.profile.name ,
    submitted: now - 10*3600*1000
  });

  Posts.insert({
    title : 'The Meteor Book' ,
    url : 'http://themeteorbook.com' ,
    userId: tom._id,
    author: tom.profile.name,
    submitted: now - 12*3600*1000
  });

}


text:
package mezz.jei.util;

import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.google.common.base.Throwables;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandGive;
import net.minecraft.command.CommandResultStats;
import net.minecraft.command.ICommand;
import net.minecraft.command.ICommandManager;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.CommandEvent;

/**
 * Server-side-safe utilities for commands.
 */
public final class CommandUtilServer {
	private CommandUtilServer() {
	}

	public static String[] getGiveCommandParameters(EntityPlayer sender, ItemStack itemStack, int amount) {
		String senderName = sender.getName();
		Item item = itemStack.getItem();
		ResourceLocation itemResourceLocation = item.getRegistryName();
		if (itemResourceLocation == null) {
			String stackInfo = ErrorUtil.getItemStackInfo(itemStack);
			throw new IllegalArgumentException("item.getRegistryName() returned null for: " + stackInfo);
		}

		List<String> commandStrings = new ArrayList<String>();
		commandStrings.add(senderName);
		commandStrings.add(itemResourceLocation.toString());
		commandStrings.add(String.valueOf(amount));
		commandStrings.add(String.valueOf(itemStack.getMetadata()));

		NBTTagCompound tagCompound = itemStack.getTagCompound();
		if (tagCompound != null) {
			commandStrings.add(tagCompound.toString());
		}

		return commandStrings.toArray(new String[commandStrings.size()]);
	}

	public static void writeChatMessage(EntityPlayer player, String translationKey, TextFormatting color) {
		TextComponentTranslation component = new TextComponentTranslation(translationKey);
		component.getStyle().setColor(color);
		player.sendMessage(component);
	}

	public static boolean hasPermission(EntityPlayerMP sender, ItemStack itemStack) {
		if (sender.isCreative()) {
			return true;
		}

		MinecraftServer minecraftServer = sender.mcServer;
		ICommand giveCommand = getGiveCommand(sender);
		if (giveCommand != null && giveCommand.checkPermission(minecraftServer, sender)) {
			String[] commandParameters = getGiveCommandParameters(sender, itemStack, itemStack.getCount());
			CommandEvent event = new CommandEvent(giveCommand, sender, commandParameters);
			if (MinecraftForge.EVENT_BUS.post(event)) {
				Throwable exception = event.getException();
				if (exception != null) {
					Throwables.propagateIfPossible(exception);
				}
				return false;
			}
			return true;
		} else {
			return sender.canUseCommand(minecraftServer.getOpPermissionLevel(), "give");
		}
	}

	/**
	 * Gives a player an item. Similar to vanilla but without the "fake" itemStack popping into the player's face.
	 * (no {@link EntityItem#makeFakeItem()}
	 *
	 * @see CommandGive#execute(MinecraftServer, ICommandSender, String[])
	 */
	public static void executeGive(EntityPlayerMP sender, ItemStack itemStack) {
		int count = itemStack.getCount();
		boolean addedToInventory = sender.inventory.addItemStackToInventory(itemStack);

		if (addedToInventory) {
			sender.world.playSound(null, sender.posX, sender.posY, sender.posZ, SoundEvents.ENTITY_ITEM_PICKUP, SoundCategory.PLAYERS, 0.2F, ((sender.getRNG().nextFloat() - sender.getRNG().nextFloat()) * 0.7F + 1.0F) * 2.0F);
			sender.inventoryContainer.detectAndSendChanges();
		}

		if (addedToInventory && itemStack.isEmpty()) {
			sender.setCommandStat(CommandResultStats.Type.AFFECTED_ITEMS, count);
		} else {
			sender.setCommandStat(CommandResultStats.Type.AFFECTED_ITEMS, count - itemStack.getCount());
			EntityItem entityitem = sender.dropItem(itemStack, false);
			if (entityitem != null) {
				entityitem.setNoPickupDelay();
				entityitem.setOwner(sender.getName());
			}
		}

		ICommand giveCommand = getGiveCommand(sender);
		if (giveCommand != null) {
			itemStack.setCount(1);
			CommandBase.notifyCommandListener(sender, giveCommand, "commands.give.success", itemStack.getTextComponent(), count, sender.getName());
		}
	}

	@Nullable
	private static ICommand getGiveCommand(EntityPlayerMP sender) {
		MinecraftServer minecraftServer = sender.mcServer;
		ICommandManager commandManager = minecraftServer.getCommandManager();
		Map<String, ICommand> commands = commandManager.getCommands();
		return commands.get("give");
	}
}


text:
VER=$1
PROJECT=$2

DOTCNT=$(echo $VER | grep -o "\." | wc -l)
if [ "$DOTCNT" -gt 1 ]; then
  PRE="true"
else
  PRE="false"
  VER="${VER}.0"
fi

if [ -z "$PROJECT" ]; then
  echo "Project not specified. Exiting..."
  exit 0
fi

echo Creating a new release: $VER

IFS="." read -a PARTS <<< "$VER"
MAJOR=${PARTS[0]}
MINOR=${PARTS[1]}
MINOR=$((MINOR+1))
VERN=${MAJOR}.${MINOR}

pushd $GOPATH/src/v2ray.com/core
echo "Adding a new tag: " "v$VER"
git tag -s -a "v$VER" -m "Version ${VER}"
sed -i '' "s/\(version *= *\"\).*\(\"\)/\1$VERN\2/g" core.go
echo "Committing core.go (may not necessary)"
git commit core.go -S -m "Update version"
echo "Pushing changes"
git push --follow-tags
popd

echo "Launching build machine."
DIR="$(dirname "$0")"
RAND="$(openssl rand -hex 5)"
gcloud compute instances create "v2raycore-${RAND}" \
    --machine-type=n1-standard-2 \
    --metadata=release_tag=v${VER},prerelease=${PRE} \
    --metadata-from-file=startup-script=${DIR}/release-ci.sh \
    --zone=europe-west4-c \
    --project ${PROJECT} \
    --scopes "https://www.googleapis.com/auth/compute,https://www.googleapis.com/auth/devstorage.read_write" \


text:
ActiveAdmin.register ITSF::FundReports::ExecutionImport do
  menu :parent => Proc.new { I18n.t('itsf.fund_reports.active_admin.executions.menu') }.call

  action_item :only => :show do
    link_to('Import', [:import, :admin, itsf_fund_reports_execution_import])
  end # action_item

  form :html => { :enctype => "multipart/form-data" } do |f|
    f.inputs do
      f.input :day
      f.input :asset, :as => :file
    end

    f.actions
  end # form

  member_action :import do
    execution_import = ITSF::FundReports::ExecutionImport.find(params[:id])
    if execution_import.import
      redirect_to({:action => :show}, {:notice => "Imported!"})
    else
      redirect_to({:action => :show}, {:notice => "Not imported!"})
    end
  end # member_action
end # ActiveAdmin.register


text:
package com.nicolasdu.pick_n_eat;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

public class RestaurantActivity extends ActionBarActivity {
Restaurant restaurant;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_restaurant);
        restaurant = (Restaurant) getIntent().getSerializableExtra("Restaurant");
        setViewContents();
    }

    public void setViewContents(){
        String displayAddress = "";
        TextView title = (TextView)findViewById(R.id.textView2);
        TextView address = (TextView)findViewById(R.id.textView);
        TextView phone = (TextView)findViewById(R.id.textView4);
        title.setText(restaurant.getTitle());
        phone.setText(restaurant.getDisplayPhone());
        for (int i = 0; i < restaurant.getAddress().size(); i++) {
            displayAddress += restaurant.getAddress().get(i)+ System.getProperty ("line.separator");
        }
        address.setText(displayAddress);
    }

    public void openMapDirections(View view){
        Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                Uri.parse("http://maps.google.com/maps?daddr="+restaurant.getLatitude()+","+restaurant.getLongitude()));
        startActivity(intent);
    }

    public void callRestaurant(View view){
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:"+restaurant.getPhone()));
        startActivity(intent);
    }

    public void openWebsite(View view){
        Intent i = new Intent(android.content.Intent.ACTION_VIEW,
                Uri.parse(restaurant.getWebsite().toString()));
        startActivity(i);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        switch (item.getItemId()) {
            case R.id.action_settings:
                Intent intent = new Intent(RestaurantActivity.this, SettingsActivity.class);
                startActivity(intent);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}


text:
from .client import Client
from .exceptions import (
    HTTPError,
    BadRequestsError,
    UnauthorizedError,
    ForbiddenError,
    NotFoundError,
    MethodNotAllowedError,
    PayloadTooLargeError,
    UnsupportedMediaTypeError,
    TooManyRequestsError,
    InternalServerError,
    ServiceUnavailableError,
    GatewayTimeoutError
)


text:
Given /^I (only )?have a page titled "([^"]*)" with a custom url "([^"]*)"?$/ do |only, title, link_url|
  Page.delete_all if only

  Page.create(:title => title,
              :link_url => link_url)
end

Given /^I (only )?have pages titled "?([^"]*)"?$/ do |only, titles|
  Page.delete_all if only
  titles.split(', ').each do |title|
    Page.create(:title => title)
  end
end

Given /^I have no pages$/ do
  Page.delete_all
end

Given /^I have test page titled "([^"]*)"$/ do |title|
  Page.create(:title => title)
end

Then /^I should have ([0-9]+) pages?$/ do |count|
  Page.count.should == count.to_i
end

Then /^I should have a page at \/(.+)$/ do |url|
  Page.all.count{|page| page.url[:path].to_s.include?(url)}.should == 1
end


text:
"""
Testing for the bagging ensemble module (sklearn.ensemble.bagging).
"""

# Author: Gilles Louppe
# License: BSD 3 clause

import numpy as np

from sklearn.base import BaseEstimator

from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_array_almost_equal
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_raises
from sklearn.utils.testing import assert_greater
from sklearn.utils.testing import assert_less
from sklearn.utils.testing import assert_true
from sklearn.utils.testing import assert_false
from sklearn.utils.testing import assert_warns
from sklearn.utils.testing import assert_warns_message

from sklearn.dummy import DummyClassifier, DummyRegressor
from sklearn.grid_search import GridSearchCV, ParameterGrid
from sklearn.ensemble import BaggingClassifier, BaggingRegressor
from sklearn.linear_model import Perceptron, LogisticRegression
from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
from sklearn.svm import SVC, SVR
from sklearn.pipeline import make_pipeline
from sklearn.feature_selection import SelectKBest
from sklearn.cross_validation import train_test_split
from sklearn.datasets import load_boston, load_iris, make_hastie_10_2
from sklearn.utils import check_random_state

from scipy.sparse import csc_matrix, csr_matrix

rng = check_random_state(0)

# also load the iris dataset
# and randomly permute it
iris = load_iris()
perm = rng.permutation(iris.target.size)
iris.data = iris.data[perm]
iris.target = iris.target[perm]

# also load the boston dataset
# and randomly permute it
boston = load_boston()
perm = rng.permutation(boston.target.size)
boston.data = boston.data[perm]
boston.target = boston.target[perm]

def test_classification():
    # Check classification for various parameter settings.
    rng = check_random_state(0)
    X_train, X_test, y_train, y_test = train_test_split(iris.data,
                                                        iris.target,
                                                        random_state=rng)
    grid = ParameterGrid({"max_samples": [0.5, 1.0],
                          "max_features": [1, 2, 4],
                          "bootstrap": [True, False],
                          "bootstrap_features": [True, False]})

    for base_estimator in [None,
                           DummyClassifier(),
                           Perceptron(),
                           DecisionTreeClassifier(),
                           KNeighborsClassifier(),
                           SVC()]:
        for params in grid:
            BaggingClassifier(base_estimator=base_estimator,
                              random_state=rng,
                              **params).fit(X_train, y_train).predict(X_test)

def test_sparse_classification():
    # Check classification for various parameter settings on sparse input.

    class CustomSVC(SVC):
        """SVC variant that records the nature of the training set"""

        def fit(self, X, y):
            super(CustomSVC, self).fit(X, y)
            self.data_type_ = type(X)
            return self

    rng = check_random_state(0)
    X_train, X_test, y_train, y_test = train_test_split(iris.data,
                                                        iris.target,
                                                        random_state=rng)
    parameter_sets = [
        {"max_samples": 0.5,
         "max_features": 2,
         "bootstrap": True,
         "bootstrap_features": True},
        {"max_samples": 1.0,
         "max_features": 4,
         "bootstrap": True,
         "bootstrap_features": True},
        {"max_features": 2,
         "bootstrap": False,
         "bootstrap_features": True},
        {"max_samples": 0.5,
         "bootstrap": True,
         "bootstrap_features": False},
    ]

    for sparse_format in [csc_matrix, csr_matrix]:
        X_train_sparse = sparse_format(X_train)
        X_test_sparse = sparse_format(X_test)
        for params in parameter_sets:
            for f in ['predict', 'predict_proba', 'predict_log_proba', 'decision_function']:
                # Trained on sparse format
                sparse_classifier = BaggingClassifier(
                    base_estimator=CustomSVC(decision_function_shape='ovr'),
                    random_state=1,
                    **params
                ).fit(X_train_sparse, y_train)
                sparse_results = getattr(sparse_classifier, f)(X_test_sparse)

                # Trained on dense format
                dense_classifier = BaggingClassifier(
                    base_estimator=CustomSVC(decision_function_shape='ovr'),
                    random_state=1,
                    **params
                ).fit(X_train, y_train)
                dense_results = getattr(dense_classifier, f)(X_test)
                assert_array_equal(sparse_results, dense_results)

            sparse_type = type(X_train_sparse)
            types = [i.data_type_ for i in sparse_classifier.estimators_]

            assert all([t == sparse_type for t in types])

def test_regression():
    # Check regression for various parameter settings.
    rng = check_random_state(0)
    X_train, X_test, y_train, y_test = train_test_split(boston.data[:50],
                                                        boston.target[:50],
                                                        random_state=rng)
    grid = ParameterGrid({"max_samples": [0.5, 1.0],
                          "max_features": [0.5, 1.0],
                          "bootstrap": [True, False],
                          "bootstrap_features": [True, False]})

    for base_estimator in [None,
                           DummyRegressor(),
                           DecisionTreeRegressor(),
                           KNeighborsRegressor(),
                           SVR()]:
        for params in grid:
            BaggingRegressor(base_estimator=base_estimator,
                             random_state=rng,
                             **params).fit(X_train, y_train).predict(X_test)

def test_sparse_regression():
    # Check regression for various parameter settings on sparse input.
    rng = check_random_state(0)
    X_train, X_test, y_train, y_test = train_test_split(boston.data[:50],
                                                        boston.target[:50],
                                                        random_state=rng)

    class CustomSVR(SVR):
        """SVC variant that records the nature of the training set"""

        def fit(self, X, y):
            super(CustomSVR, self).fit(X, y)
            self.data_type_ = type(X)
            return self

    parameter_sets = [
        {"max_samples": 0.5,
         "max_features": 2,
         "bootstrap": True,
         "bootstrap_features": True},
        {"max_samples": 1.0,
         "max_features": 4,
         "bootstrap": True,
         "bootstrap_features": True},
        {"max_features": 2,
         "bootstrap": False,
         "bootstrap_features": True},
        {"max_samples": 0.5,
         "bootstrap": True,
         "bootstrap_features": False},
    ]

    for sparse_format in [csc_matrix, csr_matrix]:
        X_train_sparse = sparse_format(X_train)
        X_test_sparse = sparse_format(X_test)
        for params in parameter_sets:

            # Trained on sparse format
            sparse_classifier = BaggingRegressor(
                base_estimator=CustomSVR(),
                random_state=1,
                **params
            ).fit(X_train_sparse, y_train)
            sparse_results = sparse_classifier.predict(X_test_sparse)

            # Trained on dense format
            dense_results = BaggingRegressor(
                base_estimator=CustomSVR(),
                random_state=1,
                **params
            ).fit(X_train, y_train).predict(X_test)

            sparse_type = type(X_train_sparse)
            types = [i.data_type_ for i in sparse_classifier.estimators_]

            assert_array_equal(sparse_results, dense_results)
            assert all([t == sparse_type for t in types])
            assert_array_equal(sparse_results, dense_results)

def test_bootstrap_samples():
    # Test that bootstraping samples generate non-perfect base estimators.
    rng = check_random_state(0)
    X_train, X_test, y_train, y_test = train_test_split(boston.data,
                                                        boston.target,
                                                        random_state=rng)

    base_estimator = DecisionTreeRegressor().fit(X_train, y_train)

    # without bootstrap, all trees are perfect on the training set
    ensemble = BaggingRegressor(base_estimator=DecisionTreeRegressor(),
                                max_samples=1.0,
                                bootstrap=False,
                                random_state=rng).fit(X_train, y_train)

    assert_equal(base_estimator.score(X_train, y_train),
                 ensemble.score(X_train, y_train))

    # with bootstrap, trees are no longer perfect on the training set
    ensemble = BaggingRegressor(base_estimator=DecisionTreeRegressor(),
                                max_samples=1.0,
                                bootstrap=True,
                                random_state=rng).fit(X_train, y_train)

    assert_greater(base_estimator.score(X_train, y_train),
                   ensemble.score(X_train, y_train))

def test_bootstrap_features():
    # Test that bootstraping features may generate dupplicate features.
    rng = check_random_state(0)
    X_train, X_test, y_train, y_test = train_test_split(boston.data,
                                                        boston.target,
                                                        random_state=rng)

    ensemble = BaggingRegressor(base_estimator=DecisionTreeRegressor(),
                                max_features=1.0,
                                bootstrap_features=False,
                                random_state=rng).fit(X_train, y_train)

    for features in ensemble.estimators_features_:
        assert_equal(boston.data.shape[1], np.unique(features).shape[0])

    ensemble = BaggingRegressor(base_estimator=DecisionTreeRegressor(),
                                max_features=1.0,
                                bootstrap_features=True,
                                random_state=rng).fit(X_train, y_train)

    for features in ensemble.estimators_features_:
        assert_greater(boston.data.shape[1], np.unique(features).shape[0])

def test_probability():
    # Predict probabilities.
    rng = check_random_state(0)
    X_train, X_test, y_train, y_test = train_test_split(iris.data,
                                                        iris.target,
                                                        random_state=rng)

    with np.errstate(divide="ignore", invalid="ignore"):
        # Normal case
        ensemble = BaggingClassifier(base_estimator=DecisionTreeClassifier(),
                                     random_state=rng).fit(X_train, y_train)

        assert_array_almost_equal(np.sum(ensemble.predict_proba(X_test),
                                         axis=1),
                                  np.ones(len(X_test)))

        assert_array_almost_equal(ensemble.predict_proba(X_test),
                                  np.exp(ensemble.predict_log_proba(X_test)))

        # Degenerate case, where some classes are missing
        ensemble = BaggingClassifier(base_estimator=LogisticRegression(),
                                     random_state=rng,
                                     max_samples=5).fit(X_train, y_train)

        assert_array_almost_equal(np.sum(ensemble.predict_proba(X_test),
                                         axis=1),
                                  np.ones(len(X_test)))

        assert_array_almost_equal(ensemble.predict_proba(X_test),
                                  np.exp(ensemble.predict_log_proba(X_test)))

def test_oob_score_classification():
    # Check that oob prediction is a good estimation of the generalization
    # error.
    rng = check_random_state(0)
    X_train, X_test, y_train, y_test = train_test_split(iris.data,
                                                        iris.target,
                                                        random_state=rng)

    for base_estimator in [DecisionTreeClassifier(), SVC()]:
        clf = BaggingClassifier(base_estimator=base_estimator,
                                n_estimators=100,
                                bootstrap=True,
                                oob_score=True,
                                random_state=rng).fit(X_train, y_train)

        test_score = clf.score(X_test, y_test)

        assert_less(abs(test_score - clf.oob_score_), 0.1)

        # Test with few estimators
        assert_warns(UserWarning,
                     BaggingClassifier(base_estimator=base_estimator,
                                       n_estimators=1,
                                       bootstrap=True,
                                       oob_score=True,
                                       random_state=rng).fit,
                     X_train,
                     y_train)

def test_oob_score_regression():
    # Check that oob prediction is a good estimation of the generalization
    # error.
    rng = check_random_state(0)
    X_train, X_test, y_train, y_test = train_test_split(boston.data,
                                                        boston.target,
                                                        random_state=rng)

    clf = BaggingRegressor(base_estimator=DecisionTreeRegressor(),
                           n_estimators=50,
                           bootstrap=True,
                           oob_score=True,
                           random_state=rng).fit(X_train, y_train)

    test_score = clf.score(X_test, y_test)

    assert_less(abs(test_score - clf.oob_score_), 0.1)

    # Test with few estimators
    assert_warns(UserWarning,
                 BaggingRegressor(base_estimator=DecisionTreeRegressor(),
                                  n_estimators=1,
                                  bootstrap=True,
                                  oob_score=True,
                                  random_state=rng).fit,
                 X_train,
                 y_train)

def test_single_estimator():
    # Check singleton ensembles.
    rng = check_random_state(0)
    X_train, X_test, y_train, y_test = train_test_split(boston.data,
                                                        boston.target,
                                                        random_state=rng)

    clf1 = BaggingRegressor(base_estimator=KNeighborsRegressor(),
                            n_estimators=1,
                            bootstrap=False,
                            bootstrap_features=False,
                            random_state=rng).fit(X_train, y_train)

    clf2 = KNeighborsRegressor().fit(X_train, y_train)

    assert_array_equal(clf1.predict(X_test), clf2.predict(X_test))

def test_error():
    # Test that it gives proper exception on deficient input.
    X, y = iris.data, iris.target
    base = DecisionTreeClassifier()

    # Test max_samples
    assert_raises(ValueError,
                  BaggingClassifier(base, max_samples=-1).fit, X, y)
    assert_raises(ValueError,
                  BaggingClassifier(base, max_samples=0.0).fit, X, y)
    assert_raises(ValueError,
                  BaggingClassifier(base, max_samples=2.0).fit, X, y)
    assert_raises(ValueError,
                  BaggingClassifier(base, max_samples=1000).fit, X, y)
    assert_raises(ValueError,
                  BaggingClassifier(base, max_samples="foobar").fit, X, y)

    # Test max_features
    assert_raises(ValueError,
                  BaggingClassifier(base, max_features=-1).fit, X, y)
    assert_raises(ValueError,
                  BaggingClassifier(base, max_features=0.0).fit, X, y)
    assert_raises(ValueError,
                  BaggingClassifier(base, max_features=2.0).fit, X, y)
    assert_raises(ValueError,
                  BaggingClassifier(base, max_features=5).fit, X, y)
    assert_raises(ValueError,
                  BaggingClassifier(base, max_features="foobar").fit, X, y)

    # Test support of decision_function
    assert_false(hasattr(BaggingClassifier(base).fit(X, y), 'decision_function'))

def test_parallel_classification():
    # Check parallel classification.
    rng = check_random_state(0)

    # Classification
    X_train, X_test, y_train, y_test = train_test_split(iris.data,
                                                        iris.target,
                                                        random_state=rng)

    ensemble = BaggingClassifier(DecisionTreeClassifier(),
                                 n_jobs=3,
                                 random_state=0).fit(X_train, y_train)

    # predict_proba
    ensemble.set_params(n_jobs=1)
    y1 = ensemble.predict_proba(X_test)
    ensemble.set_params(n_jobs=2)
    y2 = ensemble.predict_proba(X_test)
    assert_array_almost_equal(y1, y2)

    ensemble = BaggingClassifier(DecisionTreeClassifier(),
                                 n_jobs=1,
                                 random_state=0).fit(X_train, y_train)

    y3 = ensemble.predict_proba(X_test)
    assert_array_almost_equal(y1, y3)

    # decision_function
    ensemble = BaggingClassifier(SVC(decision_function_shape='ovr'),
                                 n_jobs=3,
                                 random_state=0).fit(X_train, y_train)

    ensemble.set_params(n_jobs=1)
    decisions1 = ensemble.decision_function(X_test)
    ensemble.set_params(n_jobs=2)
    decisions2 = ensemble.decision_function(X_test)
    assert_array_almost_equal(decisions1, decisions2)

    ensemble = BaggingClassifier(SVC(decision_function_shape='ovr'),
                                 n_jobs=1,
                                 random_state=0).fit(X_train, y_train)

    decisions3 = ensemble.decision_function(X_test)
    assert_array_almost_equal(decisions1, decisions3)

def test_parallel_regression():
    # Check parallel regression.
    rng = check_random_state(0)

    X_train, X_test, y_train, y_test = train_test_split(boston.data,
                                                        boston.target,
                                                        random_state=rng)

    ensemble = BaggingRegressor(DecisionTreeRegressor(),
                                n_jobs=3,
                                random_state=0).fit(X_train, y_train)

    ensemble.set_params(n_jobs=1)
    y1 = ensemble.predict(X_test)
    ensemble.set_params(n_jobs=2)
    y2 = ensemble.predict(X_test)
    assert_array_almost_equal(y1, y2)

    ensemble = BaggingRegressor(DecisionTreeRegressor(),
                                n_jobs=1,
                                random_state=0).fit(X_train, y_train)

    y3 = ensemble.predict(X_test)
    assert_array_almost_equal(y1, y3)

def test_gridsearch():
    # Check that bagging ensembles can be grid-searched.
    # Transform iris into a binary classification task
    X, y = iris.data, iris.target
    y[y == 2] = 1

    # Grid search with scoring based on decision_function
    parameters = {'n_estimators': (1, 2),
                  'base_estimator__C': (1, 2)}

    GridSearchCV(BaggingClassifier(SVC()),
                 parameters,
                 scoring="roc_auc").fit(X, y)

def test_base_estimator():
    # Check base_estimator and its default values.
    rng = check_random_state(0)

    # Classification
    X_train, X_test, y_train, y_test = train_test_split(iris.data,
                                                        iris.target,
                                                        random_state=rng)

    ensemble = BaggingClassifier(None,
                                 n_jobs=3,
                                 random_state=0).fit(X_train, y_train)

    assert_true(isinstance(ensemble.base_estimator_, DecisionTreeClassifier))

    ensemble = BaggingClassifier(DecisionTreeClassifier(),
                                 n_jobs=3,
                                 random_state=0).fit(X_train, y_train)

    assert_true(isinstance(ensemble.base_estimator_, DecisionTreeClassifier))

    ensemble = BaggingClassifier(Perceptron(),
                                 n_jobs=3,
                                 random_state=0).fit(X_train, y_train)

    assert_true(isinstance(ensemble.base_estimator_, Perceptron))

    # Regression
    X_train, X_test, y_train, y_test = train_test_split(boston.data,
                                                        boston.target,
                                                        random_state=rng)

    ensemble = BaggingRegressor(None,
                                n_jobs=3,
                                random_state=0).fit(X_train, y_train)

    assert_true(isinstance(ensemble.base_estimator_, DecisionTreeRegressor))

    ensemble = BaggingRegressor(DecisionTreeRegressor(),
                                n_jobs=3,
                                random_state=0).fit(X_train, y_train)

    assert_true(isinstance(ensemble.base_estimator_, DecisionTreeRegressor))

    ensemble = BaggingRegressor(SVR(),
                                n_jobs=3,
                                random_state=0).fit(X_train, y_train)
    assert_true(isinstance(ensemble.base_estimator_, SVR))

def test_bagging_with_pipeline():
    estimator = BaggingClassifier(make_pipeline(SelectKBest(k=1),
                                                DecisionTreeClassifier()),
                                  max_features=2)
    estimator.fit(iris.data, iris.target)

class DummyZeroEstimator(BaseEstimator):

    def fit(self, X, y):
        self.classes_ = np.unique(y)
        return self

    def predict(self, X):
        return self.classes_[np.zeros(X.shape[0], dtype=int)]

def test_bagging_sample_weight_unsupported_but_passed():
    estimator = BaggingClassifier(DummyZeroEstimator())
    rng = check_random_state(0)

    estimator.fit(iris.data, iris.target).predict(iris.data)
    assert_raises(ValueError, estimator.fit, iris.data, iris.target,
                  sample_weight=rng.randint(10, size=(iris.data.shape[0])))

def test_warm_start(random_state=42):
    # Test if fitting incrementally with warm start gives a forest of the
    # right size and the same results as a normal fit.
    X, y = make_hastie_10_2(n_samples=20, random_state=1)

    clf_ws = None
    for n_estimators in [5, 10]:
        if clf_ws is None:
            clf_ws = BaggingClassifier(n_estimators=n_estimators,
                                       random_state=random_state,
                                       warm_start=True)
        else:
            clf_ws.set_params(n_estimators=n_estimators)
        clf_ws.fit(X, y)
        assert_equal(len(clf_ws), n_estimators)

    clf_no_ws = BaggingClassifier(n_estimators=10, random_state=random_state,
                                  warm_start=False)
    clf_no_ws.fit(X, y)

    assert_equal(set([tree.random_state for tree in clf_ws]),
                 set([tree.random_state for tree in clf_no_ws]))

def test_warm_start_smaller_n_estimators():
    # Test if warm start'ed second fit with smaller n_estimators raises error.
    X, y = make_hastie_10_2(n_samples=20, random_state=1)
    clf = BaggingClassifier(n_estimators=5, warm_start=True)
    clf.fit(X, y)
    clf.set_params(n_estimators=4)
    assert_raises(ValueError, clf.fit, X, y)

def test_warm_start_equal_n_estimators():
    # Test that nothing happens when fitting without increasing n_estimators
    X, y = make_hastie_10_2(n_samples=20, random_state=1)
    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=43)

    clf = BaggingClassifier(n_estimators=5, warm_start=True, random_state=83)
    clf.fit(X_train, y_train)

    y_pred = clf.predict(X_test)
    # modify X to nonsense values, this should not change anything
    X_train += 1.

    assert_warns_message(UserWarning,
                         "Warm-start fitting without increasing n_estimators does not",
                         clf.fit, X_train, y_train)
    assert_array_equal(y_pred, clf.predict(X_test))

def test_warm_start_equivalence():
    # warm started classifier with 5+5 estimators should be equivalent to
    # one classifier with 10 estimators
    X, y = make_hastie_10_2(n_samples=20, random_state=1)
    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=43)

    clf_ws = BaggingClassifier(n_estimators=5, warm_start=True,
                               random_state=3141)
    clf_ws.fit(X_train, y_train)
    clf_ws.set_params(n_estimators=10)
    clf_ws.fit(X_train, y_train)
    y1 = clf_ws.predict(X_test)

    clf = BaggingClassifier(n_estimators=10, warm_start=False,
                            random_state=3141)
    clf.fit(X_train, y_train)
    y2 = clf.predict(X_test)

    assert_array_almost_equal(y1, y2)

def test_warm_start_with_oob_score_fails():
    # Check using oob_score and warm_start simultaneously fails
    X, y = make_hastie_10_2(n_samples=20, random_state=1)
    clf = BaggingClassifier(n_estimators=5, warm_start=True, oob_score=True)
    assert_raises(ValueError, clf.fit, X, y)

def test_oob_score_removed_on_warm_start():
    X, y = make_hastie_10_2(n_samples=2000, random_state=1)

    clf = BaggingClassifier(n_estimators=50, oob_score=True)
    clf.fit(X, y)

    clf.set_params(warm_start=True, oob_score=False, n_estimators=100)
    clf.fit(X, y)

    assert_raises(AttributeError, getattr, clf, "oob_score_")


text:
package com.github.anba.es6draft.ast;

import java.util.List;

/**
 *
12 ECMAScript Language: Expressions

 *
12.2 Primary Expression

 *

 *
Extension: Native call expression
 *

 */
public final class NativeCallExpression extends Expression {
    private final IdentifierReference base;
    private final List<Expression> arguments;

    public NativeCallExpression(long beginPosition, long endPosition, IdentifierReference base,
            List<Expression> arguments) {
        super(beginPosition, endPosition);
        this.base = base;
        this.arguments = arguments;
    }

    public IdentifierReference getBase() {
        return base;
    }

    public List<Expression> getArguments() {
        return arguments;
    }

    @Override
    public <R, V> R accept(NodeVisitor<R, V> visitor, V value) {
        return visitor.visit(this, value);
    }

    @Override
    public <V> int accept(IntNodeVisitor<V> visitor, V value) {
        return visitor.visit(this, value);
    }

    @Override
    public <V> void accept(VoidNodeVisitor<V> visitor, V value) {
        visitor.visit(this, value);
    }
}


text:
import concurrent.futures
import itertools
import logging
import os
import queue
import shutil
import subprocess
import tempfile
import threading
import time
import traceback
from typing import TYPE_CHECKING
from typing import List
from typing import Optional

import grpc
from google.protobuf import json_format
from google.protobuf import text_format  # type: ignore # not in typeshed

from apache_beam import pipeline
from apache_beam.metrics import monitoring_infos
from apache_beam.options import pipeline_options
from apache_beam.portability.api import beam_artifact_api_pb2_grpc
from apache_beam.portability.api import beam_fn_api_pb2_grpc
from apache_beam.portability.api import beam_job_api_pb2
from apache_beam.portability.api import beam_job_api_pb2_grpc
from apache_beam.portability.api import beam_provision_api_pb2
from apache_beam.portability.api import endpoints_pb2
from apache_beam.runners.job import utils as job_utils
from apache_beam.runners.portability import abstract_job_service
from apache_beam.runners.portability import artifact_service
from apache_beam.runners.portability import portable_runner
from apache_beam.runners.portability.fn_api_runner import fn_runner
from apache_beam.runners.portability.fn_api_runner import worker_handlers
from apache_beam.runners.worker.log_handler import LOGENTRY_TO_LOG_LEVEL_MAP
from apache_beam.utils import thread_pool_executor

if TYPE_CHECKING:
  from google.protobuf import struct_pb2  # pylint: disable=ungrouped-imports
  from apache_beam.portability.api import beam_runner_api_pb2

_LOGGER = logging.getLogger(__name__)

def _iter_queue(q):
  while True:
    yield q.get(block=True)

class LocalJobServicer(abstract_job_service.AbstractJobServiceServicer):
  """Manages one or more pipelines, possibly concurrently.
    Experimental: No backward compatibility guaranteed.
    Servicer for the Beam Job API.

    This JobService uses a basic local implementation of runner to run the job.
    This JobService is not capable of managing job on remote clusters.

    By default, this JobService executes the job in process but still uses GRPC
    to communicate pipeline and worker state.  It can also be configured to use
    inline calls rather than GRPC (for speed) or launch completely separate
    subprocesses for the runner and worker(s).
    """
  def __init__(self, staging_dir=None, beam_job_type=None):
    super().__init__()
    self._cleanup_staging_dir = staging_dir is None
    self._staging_dir = staging_dir or tempfile.mkdtemp()
    self._artifact_service = artifact_service.ArtifactStagingService(
        artifact_service.BeamFilesystemHandler(self._staging_dir).file_writer)
    self._artifact_staging_endpoint = None  # type: Optional[endpoints_pb2.ApiServiceDescriptor]
    self._beam_job_type = beam_job_type or BeamJob

  def create_beam_job(self,
                      preparation_id,  # stype: str
                      job_name,  # type: str
                      pipeline,  # type: beam_runner_api_pb2.Pipeline
                      options  # type: struct_pb2.Struct
                     ):
    # type: (...) -> BeamJob
    self._artifact_service.register_job(
        staging_token=preparation_id,
        dependency_sets={
            id: env.dependencies
            for (id, env) in pipeline.components.environments.items()
        })
    provision_info = fn_runner.ExtendedProvisionInfo(
        beam_provision_api_pb2.ProvisionInfo(pipeline_options=options),
        self._staging_dir,
        job_name=job_name)
    return self._beam_job_type(
        preparation_id,
        pipeline,
        options,
        provision_info,
        self._artifact_staging_endpoint,
        self._artifact_service)

  def get_bind_address(self):
    """Return the address used to open the port on the gRPC server.

    This is often, but not always the same as the service address.  For
    example, to make the service accessible to external machines, override this
    to return '[::]' and override `get_service_address()` to return a publicly
    accessible host name.
    """
    return self.get_service_address()

  def get_service_address(self):
    """Return the host name at which this server will be accessible.

    In particular, this is provided to the client upon connection as the
    artifact staging endpoint.
    """
    return 'localhost'

  def start_grpc_server(self, port=0):
    options = [("grpc.max_receive_message_length", -1),
               ("grpc.max_send_message_length", -1),
               ("grpc.http2.max_pings_without_data", 0),
               ("grpc.http2.max_ping_strikes", 0)]
    self._server = grpc.server(
        thread_pool_executor.shared_unbounded_instance(), options=options)
    port = self._server.add_insecure_port(
        '%s:%d' % (self.get_bind_address(), port))
    beam_job_api_pb2_grpc.add_JobServiceServicer_to_server(self, self._server)
    beam_artifact_api_pb2_grpc.add_ArtifactStagingServiceServicer_to_server(
        self._artifact_service, self._server)
    hostname = self.get_service_address()
    self._artifact_staging_endpoint = endpoints_pb2.ApiServiceDescriptor(
        url='%s:%d' % (hostname, port))
    self._server.start()
    _LOGGER.info('Grpc server started at %s on port %d' % (hostname, port))
    return port

  def stop(self, timeout=1):
    self._server.stop(timeout)
    if os.path.exists(self._staging_dir) and self._cleanup_staging_dir:
      shutil.rmtree(self._staging_dir, ignore_errors=True)

  def GetJobMetrics(self, request, context=None):
    if request.job_id not in self._jobs:
      raise LookupError("Job {} does not exist".format(request.job_id))

    result = self._jobs[request.job_id].result
    monitoring_info_list = []
    if result is not None:
      for mi in result._monitoring_infos_by_stage.values():
        monitoring_info_list.extend(mi)

    # Filter out system metrics
    user_monitoring_info_list = [
        x for x in monitoring_info_list
        if monitoring_infos.is_user_monitoring_info(x)
    ]

    return beam_job_api_pb2.GetJobMetricsResponse(
        metrics=beam_job_api_pb2.MetricResults(
            committed=user_monitoring_info_list))

class SubprocessSdkWorker(object):
  """Manages a SDK worker implemented as a subprocess communicating over grpc.
  """
  def __init__(
      self,
      worker_command_line,  # type: bytes
      control_address,
      provision_info,
      worker_id=None):
    # worker_command_line is of bytes type received from grpc. It was encoded in
    # apache_beam.transforms.environments.SubprocessSDKEnvironment earlier.
    # decode it back as subprocess.Popen does not support bytes args in win32.
    self._worker_command_line = worker_command_line.decode('utf-8')
    self._control_address = control_address
    self._provision_info = provision_info
    self._worker_id = worker_id

  def run(self):
    options = [("grpc.http2.max_pings_without_data", 0),
               ("grpc.http2.max_ping_strikes", 0)]
    logging_server = grpc.server(
        thread_pool_executor.shared_unbounded_instance(), options=options)
    logging_port = logging_server.add_insecure_port('[::]:0')
    logging_server.start()
    logging_servicer = BeamFnLoggingServicer()
    beam_fn_api_pb2_grpc.add_BeamFnLoggingServicer_to_server(
        logging_servicer, logging_server)
    logging_descriptor = text_format.MessageToString(
        endpoints_pb2.ApiServiceDescriptor(url='localhost:%s' % logging_port))

    control_descriptor = text_format.MessageToString(
        endpoints_pb2.ApiServiceDescriptor(url=self._control_address))
    pipeline_options = json_format.MessageToJson(
        self._provision_info.provision_info.pipeline_options)

    env_dict = dict(
        os.environ,
        CONTROL_API_SERVICE_DESCRIPTOR=control_descriptor,
        LOGGING_API_SERVICE_DESCRIPTOR=logging_descriptor,
        PIPELINE_OPTIONS=pipeline_options)
    # only add worker_id when it is set.
    if self._worker_id:
      env_dict['WORKER_ID'] = self._worker_id

    with worker_handlers.SUBPROCESS_LOCK:
      p = subprocess.Popen(self._worker_command_line, shell=True, env=env_dict)
    try:
      p.wait()
      if p.returncode:
        raise RuntimeError(
            'Worker subprocess exited with return code %s' % p.returncode)
    finally:
      if p.poll() is None:
        p.kill()
      logging_server.stop(0)

class BeamJob(abstract_job_service.AbstractBeamJob):
  """This class handles running and managing a single pipeline.

    The current state of the pipeline is available as self.state.
    """

  def __init__(self,
               job_id,  # type: str
               pipeline,
               options,
               provision_info,  # type: fn_runner.ExtendedProvisionInfo
               artifact_staging_endpoint,  # type: Optional[endpoints_pb2.ApiServiceDescriptor]
               artifact_service,  # type: artifact_service.ArtifactStagingService
              ):
    super().__init__(job_id, provision_info.job_name, pipeline, options)
    self._provision_info = provision_info
    self._artifact_staging_endpoint = artifact_staging_endpoint
    self._artifact_service = artifact_service
    self._state_queues = []  # type: List[queue.Queue]
    self._log_queues = JobLogQueues()
    self.daemon = True
    self.result = None

  def pipeline_options(self):
    def from_urn(key):
      assert key.startswith('beam:option:')
      assert key.endswith(':v1')
      return key[12:-3]

    return pipeline_options.PipelineOptions(
        **{
            from_urn(key): value
            for (key, value
                 ) in job_utils.struct_to_dict(self._pipeline_options).items()
        })

  def set_state(self, new_state):
    """Set the latest state as an int enum and notify consumers"""
    timestamp = super().set_state(new_state)
    if timestamp is not None:
      # Inform consumers of the new state.
      for queue in self._state_queues:
        queue.put((new_state, timestamp))

  def prepare(self):
    pass

  def artifact_staging_endpoint(self):
    return self._artifact_staging_endpoint

  def run(self):
    self.set_state(beam_job_api_pb2.JobState.STARTING)
    self._run_thread = threading.Thread(target=self._run_job)
    self._run_thread.start()

  def _run_job(self):
    with JobLogHandler(self._log_queues) as log_handler:
      self._update_dependencies()
      pipeline.Pipeline.merge_compatible_environments(self._pipeline_proto)
      try:
        start = time.time()
        self.result = self._invoke_runner()
        self.result.wait_until_finish()
        _LOGGER.info(
            'Completed job in %s seconds with state %s.',
            time.time() - start,
            self.result.state)
        self.set_state(
            portable_runner.PipelineResult.pipeline_state_to_runner_api_state(
                self.result.state))
      except:  # pylint: disable=bare-except
        self._log_queues.put(
            beam_job_api_pb2.JobMessage(
                message_id=log_handler._next_id(),
                time=time.strftime('%Y-%m-%d %H:%M:%S.'),
                importance=beam_job_api_pb2.JobMessage.JOB_MESSAGE_ERROR,
                message_text=traceback.format_exc()))
        _LOGGER.exception('Error running pipeline.')
        self.set_state(beam_job_api_pb2.JobState.FAILED)
        raise

  def _invoke_runner(self):
    self.set_state(beam_job_api_pb2.JobState.RUNNING)
    return fn_runner.FnApiRunner(
        provision_info=self._provision_info).run_via_runner_api(
            self._pipeline_proto, self.pipeline_options())

  def _update_dependencies(self):
    try:
      for env_id, deps in self._artifact_service.resolved_deps(
          self._job_id, timeout=0).items():
        # Slice assignment not supported for repeated fields.
        env = self._pipeline_proto.components.environments[env_id]
        del env.dependencies[:]
        env.dependencies.extend(deps)
      self._provision_info.provision_info.ClearField('retrieval_token')
    except concurrent.futures.TimeoutError:
      # TODO(https://github.com/apache/beam/issues/20267): Require this once
      # all SDKs support it.
      pass

  def cancel(self):
    if not self.is_terminal_state(self.state):
      self.set_state(beam_job_api_pb2.JobState.CANCELLING)
      # TODO(robertwb): Actually cancel...
      self.set_state(beam_job_api_pb2.JobState.CANCELLED)

  def get_state_stream(self):
    # Register for any new state changes.
    state_queue = queue.Queue()
    self._state_queues.append(state_queue)

    for state, timestamp in self.with_state_history(_iter_queue(state_queue)):
      yield state, timestamp
      if self.is_terminal_state(state):
        break

  def get_message_stream(self):
    # Register for any new messages.
    log_queue = queue.Queue()
    self._log_queues.append(log_queue)
    self._state_queues.append(log_queue)

    for msg in itertools.chain(self._log_queues.cache(),
                               self.with_state_history(_iter_queue(log_queue))):
      if isinstance(msg, tuple):
        assert len(msg) == 2 and isinstance(msg[0], int)
        current_state = msg[0]
        yield msg
        if self.is_terminal_state(current_state):
          break
      else:
        yield msg

class BeamFnLoggingServicer(beam_fn_api_pb2_grpc.BeamFnLoggingServicer):
  def Logging(self, log_bundles, context=None):
    for log_bundle in log_bundles:
      for log_entry in log_bundle.log_entries:
        _LOGGER.log(
            LOGENTRY_TO_LOG_LEVEL_MAP[log_entry.severity],
            'Worker: %s',
            str(log_entry).replace('\n', ' '))
    return iter([])

class JobLogQueues(object):
  def __init__(self):
    self._queues = []  # type: List[queue.Queue]
    self._cache = []
    self._cache_size = 10
    self._lock = threading.Lock()

  def cache(self):
    with self._lock:
      return list(self._cache)

  def append(self, queue):
    with self._lock:
      self._queues.append(queue)

  def put(self, msg):
    with self._lock:
      if len(self._cache) < self._cache_size:
        self._cache.append(msg)
      else:
        min_level = min(m.importance for m in self._cache)
        if msg.importance >= min_level:
          self._cache.append(msg)
          for ix, m in enumerate(self._cache):
            if m.importance == min_level:
              del self._cache[ix]
              break

      for queue in self._queues:
        queue.put(msg)

class JobLogHandler(logging.Handler):
  """Captures logs to be returned via the Beam Job API.

    Enabled via the with statement."""

  # Mapping from logging levels to LogEntry levels.
  LOG_LEVEL_MAP = {
      logging.FATAL: beam_job_api_pb2.JobMessage.JOB_MESSAGE_ERROR,
      logging.CRITICAL: beam_job_api_pb2.JobMessage.JOB_MESSAGE_ERROR,
      logging.ERROR: beam_job_api_pb2.JobMessage.JOB_MESSAGE_ERROR,
      logging.WARNING: beam_job_api_pb2.JobMessage.JOB_MESSAGE_WARNING,
      logging.INFO: beam_job_api_pb2.JobMessage.JOB_MESSAGE_BASIC,
      logging.DEBUG: beam_job_api_pb2.JobMessage.JOB_MESSAGE_DEBUG,
  }

  def __init__(self, log_queues):
    super().__init__()
    self._last_id = 0
    self._logged_thread = None
    self._log_queues = log_queues

  def __enter__(self):
    # Remember the current thread to demultiplex the logs of concurrently
    # running pipelines (as Python log handlers are global).
    self._logged_thread = threading.current_thread()
    logging.getLogger().addHandler(self)
    return self

  def __exit__(self, *args):
    self._logged_thread = None
    self.close()

  def _next_id(self):
    self._last_id += 1
    return str(self._last_id)

  def emit(self, record):
    if self._logged_thread is threading.current_thread():
      msg = beam_job_api_pb2.JobMessage(
          message_id=self._next_id(),
          time=time.strftime(
              '%Y-%m-%d %H:%M:%S.', time.localtime(record.created)),
          importance=self.LOG_LEVEL_MAP[record.levelno],
          message_text=self.format(record))

      # Inform all message consumers.
      self._log_queues.put(msg)