text:
package eu.mosaic_cloud.connectors.mq.amqp;

import eu.mosaic_cloud.callbacks.core.CallbackMonitor;
import eu.mosaic_cloud.callbacks.core.CallbackTag;
import eu.mosaic_cloud.callbacks.core.CallbackTarget;
import eu.mosaic_cloud.connectors.mq.core.QueueAccesorStatus;
import eu.mosaic_cloud.connectors.mq.core.QueueAccessor;
import eu.mosaic_cloud.connectors.mq.core.callbacks.QueueAccessorCallbackArguments;
import eu.mosaic_cloud.connectors.mq.core.callbacks.QueueAccessorCallbackType;
import eu.mosaic_cloud.core.configuration.core.Configuration;
import eu.mosaic_cloud.core.configuration.core.ConfigurationIdentifier;
import eu.mosaic_cloud.tools.amqp.AmqpWrapper;
import eu.mosaic_cloud.tools.amqp.AmqpWrapperDefaultCallbacks;

public abstract class AmqpQueueAccessor
		implements
			QueueAccessor
{
	protected AmqpQueueAccessor (final Configuration configuration, final Class<?> dataClass)
	{
		super ();
		synchronized (this) {
			this.configuration = configuration;
			this.dataClass = dataClass;
			this.status = QueueAccesorStatus.Creating;
		}
	}

	@Override
	public final void destroy ()
	{
		// FIXME: this should be synchronized
		this.wrapper.invokeConnectionClose (null);
		this.wrapper.destroy ();
	}

	@Override
	public final QueueAccesorStatus getStatus ()
	{
		return (this.status);
	}

	protected final Object deserializeData (final byte[] data)
	{
		if (this.dataClass == byte[].class)
			return (data);
		else
			throw (new UnsupportedOperationException ());
	}

	protected final void initialize (final Callbacks wrapperCallbacks, final CallbackTarget callbackTarget, final CallbackTag callbackTag)
	{
		synchronized (this) {
			this.callbackTarget = callbackTarget;
			this.callbackTag = callbackTag;
			this.wrapper = AmqpWrapper.create (this.configuration, wrapperCallbacks);
			this.wrapper.invokeConnectionOpen (null);
		}
	}

	protected final <_Value_ extends Object> _Value_ resolveParameter (final String identifier, final Class<_Value_> valueClass, final _Value_ defaultValue)
	{
		return (this.configuration.getParameter (ConfigurationIdentifier.resolveRelative (identifier), valueClass).getValue (defaultValue));
	}

	protected final byte[] serializeData (final Object data)
	{
		if (this.dataClass == byte[].class)
			return ((byte[]) data);
		else
			throw (new UnsupportedOperationException ());
	}

	protected final CallbackMonitor trigger (final QueueAccessorCallbackType callbackType, final QueueAccessorCallbackArguments<?, ?> callbackArguments)
	{
		synchronized (this) {
			return (this.callbackTarget.callback (callbackType, callbackArguments, this.callbackTag));
		}
	}

	protected abstract void triggerDestroyFailedCallback ();

	protected abstract void triggerInitializeFailedCallback ();

	protected abstract void triggerInitializeSucceededCallback ();

	protected abstract void tryggerDestroySucceededCallback ();

	protected final Configuration configuration;
	protected AmqpWrapper wrapper;
	private CallbackTag callbackTag;
	private CallbackTarget callbackTarget;
	private boolean closeSucceeded;
	private Class<?> dataClass;
	private QueueAccesorStatus status;

	protected abstract class Callbacks
			extends AmqpWrapperDefaultCallbacks
	{
		@Override
		public final void destroyed (final AmqpWrapper wrapper)
		{
			synchronized (AmqpQueueAccessor.this) {
				if (AmqpQueueAccessor.this.closeSucceeded)
					AmqpQueueAccessor.this.tryggerDestroySucceededCallback ();
				else
					AmqpQueueAccessor.this.triggerDestroyFailedCallback ();
			}
		}

		@Override
		public final void handleConnectionCloseErr (final AmqpWrapper wrapper, final Object extra)
		{
			synchronized (AmqpQueueAccessor.this) {
				AmqpQueueAccessor.this.closeSucceeded = false;
			}
		}

		@Override
		public final void handleConnectionCloseOk (final AmqpWrapper wrapper, final Object extra)
		{
			synchronized (AmqpQueueAccessor.this) {
				AmqpQueueAccessor.this.closeSucceeded = true;
			}
		}

		@Override
		public final void handleConnectionOpenOk (final AmqpWrapper wrapper, final Object extra)
		{
			synchronized (AmqpQueueAccessor.this) {
				AmqpQueueAccessor.this.triggerInitializeSucceededCallback ();
			}
		}
	}
}


text:
<?php

namespace CCBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity(repositoryClass="CCBundle\Entity\Repository\TagRepo")
 * @UniqueEntity(fields="title", message="Эта категория(тег) уже используется")
 * @ORM\Table(name="tag")
 */
class Tag
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=100, unique=true)
     */
    protected $title;

    /**
     * @ORM\Column(type="boolean")
     */
    protected $status;

    /**
     * @ORM\ManyToMany(targetEntity="User")
     * @ORM\JoinTable(name="tag_user",
     *     joinColumns={@ORM\JoinColumn(name="tage_id", referencedColumnName="id")},
     *     inverseJoinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")}
     * )
     *
     * @var ArrayCollection $tagUser
     */
    protected $tagUser; // this is author of Article

    /**
     * @ORM\Column(type="datetime")
     */
    protected $offerAt;

    public function __construct() {
        $this->title = 'новый тег';
        $this->status = FALSE;
        $this->tagUser = new \Doctrine\Common\Collections\ArrayCollection();
        $this->offerAt = new \DateTime('now');
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set title
     *
     * @param string $title
     *
     * @return Tag
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set status
     *
     * @param boolean $status
     *
     * @return Tag
     */
    public function setStatus($status)
    {
        $this->status = $status;

        return $this;
    }

    /**
     * Get status
     *
     * @return boolean
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * Add tagUser
     *
     * @param \CCBundle\Entity\User $tagUser
     *
     * @return Tag
     */
    public function addTagUser(\CCBundle\Entity\User $tagUser)
    {
        $this->tagUser[] = $tagUser;

        return $this;
    }

    /**
     * Remove tagUser
     *
     * @param \CCBundle\Entity\User $tagUser
     */
    public function removeTagUser(\CCBundle\Entity\User $tagUser)
    {
        $this->tagUser->removeElement($tagUser);
    }

    /**
     * Get tagUser
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getTagUser()
    {
        return $this->tagUser;
    }

    /**
     * Set offerAt
     *
     * @param \DateTime $offerAt
     *
     * @return Tag
     */
    public function setOfferAt($offerAt)
    {
        $this->offerAt = $offerAt;

        return $this;
    }

    /**
     * Get offerAt
     *
     * @return \DateTime
     */
    public function getOfferAt()
    {
        return $this->offerAt;
    }
}

redpajama_set_name: RedPajamaGithub


text:
class game
{
    public:
        game();
        void loadGame();
        void saveGame();
    protected:
    private:
};

#endif


text:
import sys
import os

def create_meta_header(folder):
    """
    Add metadata to a converted markdown notebook
    """
    import yaml
    with open('{}/metadata.yml'.format(folder), 'r') as f:
        meta = yaml.load(f)

    meta_objects = ["---"]
    def _add_meta(meta, key, meta_objects, meta_key=None):
        if key in meta:
            meta_key = meta_key or key
            meta_value = meta[key]
            if type(meta_value) is list:
                meta_value = str(map(lambda x: '{}'.format(x), map(str, meta_value)))
            else:
                meta_value = '\"{}\"'.format(meta_value)
            meta_objects.append('{}: {}'.format(meta_key, meta_value))

    meta_objects.append('layout: \"page\"')
    _add_meta(meta, 'title', meta_objects)
    _add_meta(meta, 'description', meta_objects)

    import time
    meta['date'] = time.strftime("%Y-%m-%d %H:%M:%S %z")
    _add_meta(meta, 'date', meta_objects)

    _add_meta(meta, 'keywords', meta_objects, meta_key='categories')

    meta.setdefault('accepted', 'false')
    _add_meta(meta, 'accepted', meta_objects)

    meta.setdefault('notebook_url', '{}/executed_notebook.ipynb'.format(folder))
    _add_meta(meta, 'notebook_url', meta_objects)

    meta_objects.append('---')

    with open('{}/metadata.yml'.format(folder), 'w') as f:
        yaml.dump(meta, f)

    return '\n'.join(meta_objects), time.strftime("%Y-%m-%d-{}".format('-'.join(meta['title'].split(' '))))

def main(argv=None):
    argv = sys.argv[1:]
    import nbformat
    from nbconvert.preprocessors import ExecutePreprocessor
    from nbconvert.preprocessors.execute import CellExecutionError

    notebook = argv[0]
    outfile = argv[1]
    note_folder = os.path.dirname(notebook)

    if not os.path.exists(outfile):
        with open(notebook) as f:
            nb = nbformat.read(f, as_version=4)
        #print('Running notebook {} ...'.format(argv[0]))
        ep = ExecutePreprocessor(timeout=600, kernel_name='python3')
        try:
            nb, resources = ep.preprocess(nb, {'metadata': {'path': note_folder}})
        except CellExecutionError as c:
            print(c)
            return 2
        with open(outfile, 'wt') as f:
            nbformat.write(nb, f)
    #else:
    #    with open(outfile, 'r') as f:
    #        nb = nbformat.read(f, as_version=4)

    #header, filename = create_meta_header(note_folder) # Generate metadata header

    #import codecs
    #with codecs.open('docs/_posts/{}.md'.format(filename), 'w', 'utf-8') as f:
    #    # Write a header for the gh-pages website and safe it for later usage
    #    f.seek(0)
    #    f.write(header)
    #    f.write('\n')

    # from nbconvert.exporters import HTMLExporter
    # htmlexport = HTMLExporter()

    # htmlnb, htmlresources = htmlexport.from_notebook_node(nb, resources=dict(
    #     #output_files_dir='images/'.format(filename),
    #     encoding='utf-8')
    #     )

    # import codecs
    # with codecs.open(os.path.join(note_folder,'executed_notebook.html'), 'w', 'utf-8') as f:
    #     # Write a header for the gh-pages website and safe it for later usage
    #     f.seek(0)
    #     f.write(htmlnb)
    #     #f.write('\n')

    if 0: # following some old code for writing markdown exports:
        from nbconvert.exporters import MarkdownExporter
        mdexport = MarkdownExporter()
        from nbconvert.writers import FilesWriter
        mdnb, mdresources = mdexport.from_notebook_node(nb, resources=dict(output_files_dir='images/'.format(filename), encoding='utf-8'))
        fw = FilesWriter(build_directory=note_folder)
        fw.write(mdnb, mdresources, 'executed_notebook')

        # Make blog post
        mdnb, mdresources = mdexport.from_notebook_node(nb, resources=dict(output_files_dir='../assets/posts/images/{}/'.format(filename), encoding='utf-8'))
        fw = FilesWriter(build_directory='docs/_posts/', relpath='../assets/posts/images/{}/'.format(filename))
        fw.write(mdnb, mdresources, filename)
        import codecs
        with codecs.open('docs/_posts/{}.md'.format(filename), 'w', 'utf-8') as f:
            # Write a header for the gh-pages website and safe it for later usage
            f.seek(0)
            f.write(header)
            f.write('\n')
            if 0: # Markdown export not supported yet:
                adjusted_nb = mdnb.replace('{{', '{ {').replace('<!--', '```').replace('-->', '```')
                adjusted_nb = adjusted_nb.replace('../assets', '{{ site.base_url }}{{ site.url }}/assets')
                adjusted_nb = adjusted_nb.replace('$', '$$')
                adjusted_nb = adjusted_nb.replace('$$$', '$$')
                f.write(adjusted_nb)
    return 0

if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(e)
        sys.exit(2)


text:
namespace ash {
namespace {

class TestAppMenuModelAdapter : public AppMenuModelAdapter {
 public:
  explicit TestAppMenuModelAdapter(std::unique_ptr<ui::SimpleMenuModel> model)
      : AppMenuModelAdapter("test-app-id",
                            std::move(model),
                            nullptr,
                            ui::MENU_SOURCE_MOUSE,
                            base::OnceClosure(),
                            false) {}
  TestAppMenuModelAdapter(const TestAppMenuModelAdapter&) = delete;
  TestAppMenuModelAdapter& operator=(const TestAppMenuModelAdapter&) = delete;
  ~TestAppMenuModelAdapter() override = default;

  int last_executed_command_id() { return last_executed_command_id_; }

 private:
  void ExecuteCommand(int id, int mouse_event_flags) override {
    AppMenuModelAdapter::ExecuteCommand(id, mouse_event_flags);
    last_executed_command_id_ = id;
  }

  void RecordHistogramOnMenuClosed() override {}

  int last_executed_command_id_;
};

}  // namespace

class AppMenuModelAdapterTest : public AshTestBase {
 public:
  AppMenuModelAdapterTest() = default;
  AppMenuModelAdapterTest(const AppMenuModelAdapterTest&) = delete;
  AppMenuModelAdapterTest& operator=(const AppMenuModelAdapterTest&) = delete;
  ~AppMenuModelAdapterTest() override = default;

  // AshTestBase:
  void SetUp() override {
    AshTestBase::SetUp();

    views::test::DisableMenuClosureAnimations();

    auto menu_model = std::make_unique<ui::SimpleMenuModel>(nullptr);
    submenu_model_ = std::make_unique<ui::SimpleMenuModel>(nullptr);
    menu_model->AddItem(MENU_CLOSE, u"item 0");
    submenu_model_->AddItem(USE_LAUNCH_TYPE_REGULAR, u"item 2");
    menu_model->AddActionableSubMenu(LAUNCH_NEW, u"item 1",
                                     submenu_model_.get());
    app_menu_model_adapter_ =
        std::make_unique<TestAppMenuModelAdapter>(std::move(menu_model));
  }

  void ClickOnMenuItemForCommandId(int command_id) {
    auto* target_menu_item =
        app_menu_model_adapter_->root_for_testing()->GetMenuItemByID(
            command_id);
    auto location = target_menu_item->GetBoundsInScreen().CenterPoint();
    auto* event_generator = GetEventGenerator();
    event_generator->MoveMouseTo(location);
    event_generator->ClickLeftButton();
  }

  bool IsShowingSubmenuForCommandId(int command_id) {
    return app_menu_model_adapter()
        ->root_for_testing()
        ->GetMenuItemByID(command_id)
        ->SubmenuIsShowing();
  }

  void OpenMenu() {
    app_menu_model_adapter_->Run(gfx::Rect(),
                                 views::MenuAnchorPosition::kBottomCenter,
                                 views::MenuRunner::CONTEXT_MENU |
                                     views::MenuRunner::USE_ASH_SYS_UI_LAYOUT |
                                     views::MenuRunner::FIXED_ANCHOR);
  }

  void ShowSubmenuForCommandId(int command_id) {
    auto* menu_item_view = app_menu_model_adapter_->root_for_testing();
    menu_item_view->GetMenuController()->SelectItemAndOpenSubmenu(
        menu_item_view->GetMenuItemByID(command_id));
  }

  TestAppMenuModelAdapter* app_menu_model_adapter() {
    return app_menu_model_adapter_.get();
  }

 private:
  std::unique_ptr<TestAppMenuModelAdapter> app_menu_model_adapter_;
  std::unique_ptr<ui::SimpleMenuModel> submenu_model_;
};

TEST_F(AppMenuModelAdapterTest, ShouldCloseMenuOnNonUseLaunchTypeCommand) {
  EXPECT_FALSE(app_menu_model_adapter()->IsShowingMenu());
  OpenMenu();
  EXPECT_TRUE(app_menu_model_adapter()->IsShowingMenu());

  ClickOnMenuItemForCommandId(MENU_CLOSE);
  EXPECT_FALSE(app_menu_model_adapter()->IsShowingMenu());
  EXPECT_EQ(app_menu_model_adapter()->last_executed_command_id(), MENU_CLOSE);
}

TEST_F(AppMenuModelAdapterTest, ShouldCloseMenuOnLaunchNewCommand) {
  EXPECT_FALSE(app_menu_model_adapter()->IsShowingMenu());
  OpenMenu();
  EXPECT_TRUE(app_menu_model_adapter()->IsShowingMenu());

  ClickOnMenuItemForCommandId(LAUNCH_NEW);
  EXPECT_FALSE(app_menu_model_adapter()->IsShowingMenu());
  EXPECT_EQ(app_menu_model_adapter()->last_executed_command_id(), LAUNCH_NEW);
}

TEST_F(AppMenuModelAdapterTest, ShouldKeepMenuOpenOnUseLaunchTypeCommand) {
  EXPECT_FALSE(app_menu_model_adapter()->IsShowingMenu());
  OpenMenu();
  EXPECT_TRUE(app_menu_model_adapter()->IsShowingMenu());

  EXPECT_FALSE(IsShowingSubmenuForCommandId(LAUNCH_NEW));
  ShowSubmenuForCommandId(LAUNCH_NEW);
  EXPECT_TRUE(IsShowingSubmenuForCommandId(LAUNCH_NEW));

  ClickOnMenuItemForCommandId(USE_LAUNCH_TYPE_REGULAR);
  EXPECT_FALSE(IsShowingSubmenuForCommandId(LAUNCH_NEW));
  EXPECT_TRUE(app_menu_model_adapter()->IsShowingMenu());
  EXPECT_EQ(app_menu_model_adapter()->last_executed_command_id(),
            USE_LAUNCH_TYPE_REGULAR);
}

}  // namespace ash


text:
MBInterface *MOAB();
namespace geometry
{
  MBErrorCode measure( const MBEntityHandle set, const MBTag geom_tag, double &size );

  double length( std::vector<MBEntityHandle> edges );

  double dist_between_verts( const MBCartVect v0, const MBCartVect v1 );
  MBErrorCode dist_between_verts( const MBEntityHandle v0, const MBEntityHandle v1,double &d);
  double dist_between_verts( double coords0[], double coords1[] );
  double dist_between_verts( MBEntityHandle vert0, MBEntityHandle vert1 );

  double triangle_area( const MBCartVect a, const MBCartVect b, const MBCartVect c);
  MBErrorCode triangle_area( const MBEntityHandle conn[], double &area );
  MBErrorCode triangle_area( const MBEntityHandle triangle, double &area );
  double triangle_area( MBRange triangles );

  MBErrorCode measure_volume( MBEntityHandle volume, double& result );

  MBErrorCode surface_sense( MBEntityHandle volume, int num_surfaces,const MBEntityHandle* surfaces,int* senses_out );
  MBErrorCode surface_sense( MBEntityHandle volume, MBEntityHandle surface, int& sense_out );

  MBTag get_tag( const char* name, int size, MBTagType store,MBDataType type, const void* def_value, bool create_if_missing);

  bool triangle_degenerate( const MBEntityHandle tri );
  bool triangle_degenerate( const MBEntityHandle v0, const MBEntityHandle v1, const MBEntityHandle v2 );
}


text:
package org.apache.arrow.driver.jdbc;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import org.apache.arrow.driver.jdbc.accessor.ArrowFlightJdbcAccessorFactory;
import org.apache.arrow.util.AutoCloseables;
import org.apache.arrow.vector.FieldVector;
import org.apache.arrow.vector.VectorSchemaRoot;
import org.apache.calcite.avatica.ColumnMetaData;
import org.apache.calcite.avatica.util.AbstractCursor;
import org.apache.calcite.avatica.util.ArrayImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Arrow Flight Jdbc's Cursor class.
 */
public class ArrowFlightJdbcCursor extends AbstractCursor {

  private static final Logger LOGGER;
  private final VectorSchemaRoot root;
  private final int rowCount;
  private int currentRow = -1;

  static {
    LOGGER = LoggerFactory.getLogger(ArrowFlightJdbcCursor.class);
  }

  public ArrowFlightJdbcCursor(VectorSchemaRoot root) {
    this.root = root;
    rowCount = root.getRowCount();
  }

  @Override
  public List<Accessor> createAccessors(List<ColumnMetaData> columns,
                                        Calendar localCalendar,
                                        ArrayImpl.Factory factory) {
    final List<FieldVector> fieldVectors = root.getFieldVectors();

    return IntStream.range(0, fieldVectors.size()).mapToObj(root::getVector)
        .map(this::createAccessor)
        .collect(Collectors.toCollection(() -> new ArrayList<>(fieldVectors.size())));
  }

  private Accessor createAccessor(FieldVector vector) {
    return ArrowFlightJdbcAccessorFactory.createAccessor(vector, this::getCurrentRow,
        (boolean wasNull) -> {
          // AbstractCursor creates a boolean array of length 1 to hold the wasNull value
          this.wasNull[0] = wasNull;
        });
  }

  /**
   * ArrowFlightJdbcAccessors do not use {@link AbstractCursor.Getter}, as it would box primitive types and cause
   * performance issues. Each Accessor implementation works directly on Arrow Vectors.
   */
  @Override
  protected Getter createGetter(int column) {
    throw new UnsupportedOperationException("Not allowed.");
  }

  @Override
  public boolean next() {
    currentRow++;
    return currentRow < rowCount;
  }

  @Override
  public void close() {
    try {
      AutoCloseables.close(root);
    } catch (Exception e) {
      LOGGER.error(e.getMessage(), e);
    }
  }

  private int getCurrentRow() {
    return currentRow;
  }
}


text:
package consulo.dotnet.psi;

import javax.annotation.Nonnull;

import com.intellij.util.ArrayFactory;
import consulo.dotnet.resolve.DotNetTypeRef;

/**
 * @author VISTALL
 * @since 16.12.13.
 */
public interface DotNetExpression extends DotNetElement
{
	public static final DotNetExpression[] EMPTY_ARRAY = new DotNetExpression[0];

	public static ArrayFactory<DotNetExpression> ARRAY_FACTORY = new ArrayFactory<DotNetExpression>()
	{
		@Nonnull
		@Override
		public DotNetExpression[] create(int count)
		{
			return count == 0 ? EMPTY_ARRAY : new DotNetExpression[count];
		}
	};

	@Nonnull
	DotNetTypeRef toTypeRef(boolean resolveFromParent);
}


text:
from __future__ import (absolute_import, unicode_literals, division,
                        print_function)

import inspect
from copy import deepcopy

import pytest
import numpy as np

from numpy.testing.utils import assert_allclose, assert_array_equal

from ...extern.six.moves import cPickle as pickle

from ..core import Model, ModelDefinitionError
from ..parameters import Parameter
from ..models import (Const1D, Shift, Scale, Rotation2D, Gaussian1D,
                      Gaussian2D, Polynomial1D, Polynomial2D,
                      Chebyshev2D, Legendre2D, Chebyshev1D, Legendre1D,
                      AffineTransformation2D, Identity, Mapping)

@pytest.mark.parametrize(('expr', 'result'),
                         [(lambda x, y: x + y, 5.0),
                          (lambda x, y: x - y, -1.0),
                          (lambda x, y: x * y, 6.0),
                          (lambda x, y: x / y, 2.0 / 3.0),
                          (lambda x, y: x ** y, 8.0)])
def test_two_model_class_arithmetic_1d(expr, result):
    # Const1D is perhaps the simplest model to test basic arithmetic with.
    # TODO: Should define more tests later on for more complicated
    # combinations of models

    S = expr(Const1D, Const1D)

    assert issubclass(S, Model)
    assert S.n_inputs == 1
    assert S.n_outputs == 1

    # Initialize an instance of the model, providing values for the two
    # "amplitude" parameters
    s = S(2, 3)

    # It shouldn't matter what input we evaluate on since this is a constant
    # function
    out = s(0)
    assert out == result
    assert isinstance(out, float)

@pytest.mark.parametrize(('expr', 'result'),
                         [(lambda x, y: x + y, [5.0, 5.0]),
                          (lambda x, y: x - y, [-1.0, -1.0]),
                          (lambda x, y: x * y, [6.0, 6.0]),
                          (lambda x, y: x / y, [2.0 / 3.0, 2.0 / 3.0]),
                          (lambda x, y: x ** y, [8.0, 8.0])])
def test_model_set(expr, result):
    s = expr(Const1D((2, 2), n_models=2), Const1D((3, 3), n_models=2))
    out = s(0, model_set_axis=False)

    assert_array_equal(out, result)

@pytest.mark.parametrize(('expr', 'result'),
                         [(lambda x, y: x + y, [5.0, 5.0]),
                          (lambda x, y: x - y, [-1.0, -1.0]),
                          (lambda x, y: x * y, [6.0, 6.0]),
                          (lambda x, y: x / y, [2.0 / 3.0, 2.0 / 3.0]),
                          (lambda x, y: x ** y, [8.0, 8.0])])
def test_model_set_raises_value_error(expr, result):
    """Check that creating model sets with components whose _n_models are
       different raise a value error
    """

    with pytest.raises(ValueError):
        s = expr(Const1D((2, 2), n_models=2), Const1D(3, n_models=1))

@pytest.mark.parametrize(('expr', 'result'),
                         [(lambda x, y: x + y, 5.0),
                          (lambda x, y: x - y, -1.0),
                          (lambda x, y: x * y, 6.0),
                          (lambda x, y: x / y, 2.0 / 3.0),
                          (lambda x, y: x ** y, 8.0)])
def test_two_model_instance_arithmetic_1d(expr, result):
    """
    Like test_two_model_class_arithmetic_1d, but creates a new model from two
    model *instances* with fixed parameters.
    """

    s = expr(Const1D(2), Const1D(3))

    assert isinstance(s, Model)
    assert s.n_inputs == 1
    assert s.n_outputs == 1

    out = s(0)
    assert out == result
    assert isinstance(out, float)

@pytest.mark.parametrize(('expr', 'result'),
                         [(lambda x, y: x + y, 5.0),
                          (lambda x, y: x - y, -1.0),
                          (lambda x, y: x * y, 6.0),
                          (lambda x, y: x / y, 2.0 / 3.0),
                          (lambda x, y: x ** y, 8.0)])
def test_two_model_mixed_arithmetic_1d(expr, result):
    """
    Like test_two_model_class_arithmetic_1d, but creates a new model from an
    expression of one model class with one model instance (and vice-versa).
    """

    S1 = expr(Const1D, Const1D(3))
    S2 = expr(Const1D(2), Const1D)

    for cls in (S1, S2):
        assert issubclass(cls, Model)
        assert cls.n_inputs == 1
        assert cls.n_outputs == 1

    # Requires values for both amplitudes even though one of them them has a
    # default
    # TODO: We may wish to fix that eventually, so that if a parameter has a
    # default it doesn't *have* to be given in the init
    s1 = S1(2, 3)
    s2 = S2(2, 3)

    for out in (s1(0), s2(0)):
        assert out == result
        assert isinstance(out, float)

def test_simple_two_model_class_compose_1d():
    """
    Shift and Scale are two of the simplest models to test model composition
    with.
    """

    S1 = Shift | Scale  # First shift then scale
    assert issubclass(S1, Model)
    assert S1.n_inputs == 1
    assert S1.n_outputs == 1

    s1 = S1(2, 3)  # Shift by 2 and scale by 3
    assert s1(1) == 9.0

    S2 = Scale | Shift  # First scale then shift
    assert issubclass(S2, Model)
    assert S2.n_inputs == 1
    assert S2.n_outputs == 1

    s2 = S2(2, 3)  # Scale by 2 then shift by 3
    assert s2(1) == 5.0

    # Test with array inputs
    assert_array_equal(s2([1, 2, 3]), [5.0, 7.0, 9.0])

def test_simple_two_model_class_compose_2d():
    """
    A simple example consisting of two rotations.
    """

    R = Rotation2D | Rotation2D
    assert issubclass(R, Model)
    assert R.n_inputs == 2
    assert R.n_outputs == 2

    r1 = R(45, 45)  # Rotate twice by 45 degrees
    assert_allclose(r1(0, 1), (-1, 0), atol=1e-10)

    r2 = R(90, 90)  # Rotate twice by 90 degrees
    assert_allclose(r2(0, 1), (0, -1), atol=1e-10)

    # Compose R with itself to produce 4 rotations
    R2 = R | R

    r3 = R2(45, 45, 45, 45)
    assert_allclose(r3(0, 1), (0, -1), atol=1e-10)

def test_n_submodels():
    """
    Test that CompoundModel.n_submodels properly returns the number
    of components.
    """
    g2 = Gaussian1D() + Gaussian1D()
    assert g2.n_submodels() == 2

    g3 = g2 + Gaussian1D()
    assert g3.n_submodels() == 3

    g5 = g3 | g2
    assert g5.n_submodels() == 5

    g7 = g5 / g2
    assert g7.n_submodels() == 7

    # make sure it works as class method
    p = Polynomial1D + Polynomial1D

    assert p.n_submodels() == 2

def test_expression_formatting():
    """
    Test that the expression strings from compound models are formatted
    correctly.
    """

    # For the purposes of this test it doesn't matter a great deal what
    # model(s) are used in the expression, I don't think
    G = Gaussian1D
    G2 = Gaussian2D

    M = G + G
    assert M._format_expression() == '[0] + [1]'

    M = G + G + G
    assert M._format_expression() == '[0] + [1] + [2]'

    M = G + G * G
    assert M._format_expression() == '[0] + [1] * [2]'

    M = G * G + G
    assert M._format_expression() == '[0] * [1] + [2]'

    M = G + G * G + G
    assert M._format_expression() == '[0] + [1] * [2] + [3]'

    M = (G + G) * (G + G)
    assert M._format_expression() == '([0] + [1]) * ([2] + [3])'

    # This example uses parentheses in the expression, but those won't be
    # preserved in the expression formatting since they technically aren't
    # necessary, and there's no way to know that they were originally
    # parenthesized (short of some deep, and probably not worthwhile
    # introspection)
    M = (G * G) + (G * G)
    assert M._format_expression() == '[0] * [1] + [2] * [3]'

    M = G ** G
    assert M._format_expression() == '[0] ** [1]'

    M = G + G ** G
    assert M._format_expression() == '[0] + [1] ** [2]'

    M = (G + G) ** G
    assert M._format_expression() == '([0] + [1]) ** [2]'

    M = G + G | G
    assert M._format_expression() == '[0] + [1] | [2]'

    M = G + (G | G)
    assert M._format_expression() == '[0] + ([1] | [2])'

    M = G & G | G2
    assert M._format_expression() == '[0] & [1] | [2]'

    M = G & (G | G)
    assert M._format_expression() == '[0] & ([1] | [2])'

def test_indexing_on_class():
    """
    Test indexing on compound model class objects, including cases where the
    submodels are classes, as well as instances, or both.
    """

    g = Gaussian1D(1, 2, 3, name='g')
    p = Polynomial1D(2, name='p')

    M = Gaussian1D + Const1D
    assert M[0] is Gaussian1D
    assert M[1] is Const1D
    assert M['Gaussian1D'] is M[0]
    assert M['Const1D'] is M[1]

    M = Gaussian1D + p
    assert M[0] is Gaussian1D
    assert isinstance(M['p'], Polynomial1D)

    m = g + p
    assert isinstance(m[0], Gaussian1D)
    assert isinstance(m[1], Polynomial1D)
    assert isinstance(m['g'], Gaussian1D)
    assert isinstance(m['p'], Polynomial1D)

    # Test negative indexing
    assert isinstance(m[-1], Polynomial1D)
    assert isinstance(m[-2], Gaussian1D)

    with pytest.raises(IndexError):
        m[42]

    with pytest.raises(IndexError):
        m['foobar']

# TODO: It would be good if there were an easier way to interrogate a compound
# model class for what expression it represents.  Not sure what that would look
# like though.
def test_slicing_on_class():
    """
    Test slicing a simple compound model class using integers.
    """

    A = Const1D.rename('A')
    B = Const1D.rename('B')
    C = Const1D.rename('C')
    D = Const1D.rename('D')
    E = Const1D.rename('E')
    F = Const1D.rename('F')

    M = A + B - C * D / E ** F

    assert M[0:1] is A
    # This test will also check that the correct parameter names are generated
    # for each slice (fairly trivial in this case since all the submodels have
    # the same parameter, but if any corner cases are found that aren't covered
    # by this test we can do something different...)
    assert M[0:1].param_names == ('amplitude',)
    # This looks goofy but if you slice by name to the sub-model of the same
    # name it should just return that model, logically.
    assert M['A':'A'] is A
    assert M['A':'A'].param_names == ('amplitude',)
    assert M[5:6] is F
    assert M[5:6].param_names == ('amplitude',)
    assert M['F':'F'] is F
    assert M['F':'F'].param_names == ('amplitude',)

    # 1 + 2
    assert M[:2](1, 2)(0) == 3
    assert M[:2].param_names == ('amplitude_0', 'amplitude_1')
    assert M[:'B'](1, 2)(0) == 3
    assert M[:'B'].param_names == ('amplitude_0', 'amplitude_1')
    # 2 - 3
    assert M[1:3](2, 3)(0) == -1
    assert M[1:3].param_names == ('amplitude_1', 'amplitude_2')
    assert M['B':'C'](2, 3)(0) == -1
    assert M['B':'C'].param_names == ('amplitude_1', 'amplitude_2')
    # 3 * 4
    assert M[2:4](3, 4)(0) == 12
    assert M[2:4].param_names == ('amplitude_2', 'amplitude_3')
    assert M['C':'D'](3, 4)(0) == 12
    assert M['C':'D'].param_names == ('amplitude_2', 'amplitude_3')
    # 4 / 5
    assert M[3:5](4, 5)(0) == 0.8
    assert M[3:5].param_names == ('amplitude_3', 'amplitude_4')
    assert M['D':'E'](4, 5)(0) == 0.8
    assert M['D':'E'].param_names == ('amplitude_3', 'amplitude_4')
    # 5 ** 6
    assert M[4:6](5, 6)(0) == 15625
    assert M[4:6].param_names == ('amplitude_4', 'amplitude_5')
    assert M['E':'F'](5, 6)(0) == 15625
    assert M['E':'F'].param_names == ('amplitude_4', 'amplitude_5')

def test_slicing_on_instance():
    """
    Test slicing a simple compound model class using integers.
    """

    A = Const1D.rename('A')
    B = Const1D.rename('B')
    C = Const1D.rename('C')
    D = Const1D.rename('D')
    E = Const1D.rename('E')
    F = Const1D.rename('F')

    M = A + B - C * D / E ** F
    m = M(1, 2, 3, 4, 5, 6)

    assert isinstance(m[0:1], A)
    assert isinstance(m['A':'A'], A)
    assert isinstance(m[5:6], F)
    assert isinstance(m['F':'F'], F)

    # 1 + 2
    assert m[:'B'](0) == 3
    assert m[:'B'].param_names == ('amplitude_0', 'amplitude_1')
    assert np.all(m[:'B'].parameters == [1, 2])
    # 2 - 3
    assert m['B':'C'](0) == -1
    assert m['B':'C'].param_names == ('amplitude_1', 'amplitude_2')
    assert np.all(m['B':'C'].parameters == [2, 3])
    # 3 * 4
    assert m['C':'D'](0) == 12
    assert m['C':'D'].param_names == ('amplitude_2', 'amplitude_3')
    assert np.all(m['C':'D'].parameters == [3, 4])
    # 4 / 5
    assert m['D':'E'](0) == 0.8
    assert m['D':'E'].param_names == ('amplitude_3', 'amplitude_4')
    assert np.all(m['D':'E'].parameters == [4, 5])
    # 5 ** 6
    assert m['E':'F'](0) == 15625
    assert m['E':'F'].param_names == ('amplitude_4', 'amplitude_5')
    assert np.all(m['E':'F'].parameters == [5, 6])

def test_indexing_on_instance():
    """Test indexing on compound model instances."""

    M = Gaussian1D + Const1D
    m = M(1, 0, 0.1, 2)
    assert isinstance(m[0], Gaussian1D)
    assert isinstance(m[1], Const1D)
    assert isinstance(m['Gaussian1D'], Gaussian1D)
    assert isinstance(m['Const1D'], Const1D)

    # Test parameter equivalence
    assert m[0].amplitude == 1 == m.amplitude_0
    assert m[0].mean == 0 == m.mean_0
    assert m[0].stddev == 0.1 == m.stddev_0
    assert m[1].amplitude == 2 == m.amplitude_1

    # Test that parameter value updates are symmetric between the compound
    # model and the submodel returned by indexing
    const = m[1]
    m.amplitude_1 = 42
    assert const.amplitude == 42
    const.amplitude = 137
    assert m.amplitude_1 == 137

    # Similar couple of tests, but now where the compound model was created
    # from model instances
    g = Gaussian1D(1, 2, 3, name='g')
    p = Polynomial1D(2, name='p')
    m = g + p
    assert m[0].name == 'g'
    assert m[1].name == 'p'
    assert m['g'].name == 'g'
    assert m['p'].name == 'p'

    poly = m[1]
    m.c0_1 = 12345
    assert poly.c0 == 12345
    poly.c1 = 6789
    assert m.c1_1 == 6789

    # Ensure this did *not* modify the original models we used as templates
    assert p.c0 == 0
    assert p.c1 == 0

    # Test negative indexing
    assert isinstance(m[-1], Polynomial1D)
    assert isinstance(m[-2], Gaussian1D)

    with pytest.raises(IndexError):
        m[42]

    with pytest.raises(IndexError):
        m['foobar']

def test_basic_compound_inverse():
    """
    Test basic inversion of compound models in the limited sense supported for
    models made from compositions and joins only.
    """

    t = (Shift(2) & Shift(3)) | (Scale(2) & Scale(3)) | Rotation2D(90)
    assert_allclose(t.inverse(*t(0, 1)), (0, 1))

@pytest.mark.parametrize('model', [
    Shift(0) + Shift(0) | Shift(0),
    Shift(0) - Shift(0) | Shift(0),
    Shift(0) * Shift(0) | Shift(0),
    Shift(0) / Shift(0) | Shift(0),
    Shift(0) ** Shift(0) | Shift(0),
    Gaussian1D(1, 2, 3) | Gaussian1D(4, 5, 6)])
def test_compound_unsupported_inverse(model):
    """
    Ensure inverses aren't supported in cases where it shouldn't be.
    """

    with pytest.raises(NotImplementedError):
        model.inverse

def test_mapping_basic_permutations():
    """
    Tests a couple basic examples of the Mapping model--specifically examples
    that merely permute the outputs.
    """

    x, y = Rotation2D(90)(1, 2)

    RS = Rotation2D | Mapping((1, 0))
    x_prime, y_prime = RS(90)(1, 2)
    assert_allclose((x, y), (y_prime, x_prime))

    # A more complicated permutation
    M = Rotation2D & Scale
    m = M(90, 2)
    x, y, z = m(1, 2, 3)

    MS = M | Mapping((2, 0, 1))
    ms = MS(90, 2)
    x_prime, y_prime, z_prime = ms(1, 2, 3)
    assert_allclose((x, y, z), (y_prime, z_prime, x_prime))

def test_mapping_inverse():
    """Tests inverting a compound model that includes a `Mapping`."""

    RS = Rotation2D & Scale

    # Rotates 2 of the coordinates and scales the third--then rotates on a
    # different axis and scales on the axis of rotation.  No physical meaning
    # here just a simple test
    M = RS | Mapping([2, 0, 1]) | RS

    m = M(12.1, 13.2, 14.3, 15.4)

    assert_allclose((0, 1, 2), m.inverse(*m(0, 1, 2)), atol=1e-08)

def test_identity_input():
    """
    Test a case where an Identity (or Mapping) model is the first in a chain
    of composite models and thus is responsible for handling input broadcasting
    properly.

    Regression test for https://github.com/astropy/astropy/pull/3362
    """

    ident1 = Identity(1)
    shift = Shift(1)
    rotation = Rotation2D(angle=90)
    model = ident1 & shift | rotation
    assert_allclose(model(1, 2), [-3.0, 1.0])

    # Same test case but using class composition
    TestModel = ident1 & Shift | Rotation2D
    model = TestModel(offset_1=1, angle_2=90)
    assert_allclose(model(1, 2), [-3.0, 1.0])

def test_slicing_on_instances_2():
    """
    More slicing tests.

    Regression test for https://github.com/embray/astropy/pull/10
    """

    model_a = Shift(1, name='a')
    model_b = Shift(2, name='b')
    model_c = Rotation2D(3, name='c')
    model_d = Scale(2, name='d')
    model_e = Scale(3, name='e')

    m = (model_a & model_b) | model_c | (model_d & model_e)

    with pytest.raises(ModelDefinitionError):
        # The slice can't actually be taken since the resulting model cannot be
        # evaluated
        assert m[1:].submodel_names == ('b', 'c', 'd', 'e')

    assert m[:].submodel_names == ('a', 'b', 'c', 'd', 'e')
    assert m['a':].submodel_names == ('a', 'b', 'c', 'd', 'e')

    with pytest.raises(ModelDefinitionError):
        assert m['c':'d'].submodel_names == ('c', 'd')

    assert m[1:2].name == 'b'
    assert m[2:7].submodel_names == ('c', 'd', 'e')
    with pytest.raises(IndexError):
        m['x']
    with pytest.raises(IndexError):
        m['a' : 'r']

    with pytest.raises(ModelDefinitionError):
        assert m[-4:4].submodel_names == ('b', 'c', 'd')

    with pytest.raises(ModelDefinitionError):
        assert m[-4:-2].submodel_names == ('b', 'c')

def test_slicing_on_instances_3():
    """
    Like `test_slicing_on_instances_2` but uses a compound model that does not
    have any invalid slices due to the resulting model being invalid
    (originally test_slicing_on_instances_2 passed without any
    ModelDefinitionErrors being raised, but that was before we prevented
    invalid models from being created).
    """

    model_a = Shift(1, name='a')
    model_b = Shift(2, name='b')
    model_c = Gaussian1D(3, 0, 0.1, name='c')
    model_d = Scale(2, name='d')
    model_e = Scale(3, name='e')

    m = (model_a + model_b) | model_c | (model_d + model_e)

    assert m[1:].submodel_names == ('b', 'c', 'd', 'e')
    assert m[:].submodel_names == ('a', 'b', 'c', 'd', 'e')
    assert m['a':].submodel_names == ('a', 'b', 'c', 'd', 'e')
    assert m['c':'d'].submodel_names == ('c', 'd')
    assert m[1:2].name == 'b'
    assert m[2:7].submodel_names == ('c', 'd', 'e')
    with pytest.raises(IndexError):
        m['x']
    with pytest.raises(IndexError):
        m['a' : 'r']
    assert m[-4:4].submodel_names == ('b', 'c', 'd')
    assert m[-4:-2].submodel_names == ('b', 'c')

def test_slicing_on_instance_with_parameterless_model():
    """
    Regression test to fix an issue where the indices attached to parameter
    names on a compound model were not handled properly when one or more
    submodels have no parameters.  This was especially evident in slicing.
    """

    p2 = Polynomial2D(1, c0_0=1, c1_0=2, c0_1=3)
    p1 = Polynomial2D(1, c0_0=1, c1_0=2, c0_1=3)
    mapping = Mapping((0, 1, 0, 1))
    offx = Shift(-2, name='x_translation')
    offy = Shift(-1, name='y_translation')
    aff = AffineTransformation2D(matrix=[[1, 2], [3, 4]], name='rotation')
    model = mapping | (p1 & p2) | (offx & offy) | aff

    assert model.param_names == ('c0_0_1', 'c1_0_1', 'c0_1_1',
                                 'c0_0_2', 'c1_0_2', 'c0_1_2',
                                 'offset_3', 'offset_4',
                                 'matrix_5', 'translation_5')
    assert model(1, 2) == (23.0, 53.0)

    m = model[3:]
    assert m.param_names == ('offset_3', 'offset_4', 'matrix_5',
                             'translation_5')
    assert m(1, 2) == (1.0, 1.0)

def test_compound_model_with_nonstandard_broadcasting():
    """
    Ensure that the ``standard_broadcasting`` flag is properly propagated when
    creating compound models.

    See the commit message for the commit in which this was added for more
    details.
    """

    offx = Shift(1)
    offy = Shift(2)
    rot = AffineTransformation2D([[0, -1], [1, 0]])
    m = (offx & offy) | rot

    x, y = m(0, 0)
    assert x == -2
    assert y == 1

    # make sure conversion back to scalars is working properly
    assert isinstance(x, float)
    assert isinstance(y, float)

    x, y = m([0, 1, 2], [0, 1, 2])
    assert np.all(x == [-2, -3, -4])
    assert np.all(y == [1, 2, 3])

def test_compound_model_classify_attributes():
    """
    Regression test for an issue raised here:
    https://github.com/astropy/astropy/pull/3231#discussion_r22221123

    The issue is that part of the `help` implementation calls a utility
    function called `inspect.classify_class_attrs`, which was leading to an
    infinite recursion.

    This is a useful test in its own right just in that it tests that compound
    models can be introspected in some useful way without crashing--this works
    as sort of a test of its somewhat complicated internal state management.

    This test does not check any of the results of
    `~inspect.classify_class_attrs`, though it might be useful to at some
    point.
    """

    inspect.classify_class_attrs(Gaussian1D + Gaussian1D)

def test_invalid_operands():
    """
    Test that certain operators do not work with models whose inputs/outputs do
    not match up correctly.
    """

    with pytest.raises(ModelDefinitionError):
        Rotation2D | Gaussian1D

    with pytest.raises(ModelDefinitionError):
        Rotation2D(90) | Gaussian1D(1, 0, 0.1)

    with pytest.raises(ModelDefinitionError):
        Rotation2D + Gaussian1D

    with pytest.raises(ModelDefinitionError):
        Rotation2D(90) + Gaussian1D(1, 0, 0.1)

class _ConstraintsTestA(Model):
    stddev = Parameter(default=0, min=0, max=0.3)
    mean = Parameter(default=0, fixed=True)

    @staticmethod
    def evaluate(stddev, mean):
        return stddev, mean

class _ConstraintsTestB(Model):
    mean = Parameter(default=0, fixed=True)

    @staticmethod
    def evaluate(mean):
        return mean

@pytest.mark.parametrize('model',
        [Gaussian1D(bounds={'stddev': (0, 0.3)}, fixed={'mean': True}) +
            Gaussian1D(fixed={'mean': True}),
         (_ConstraintsTestA + _ConstraintsTestB)()])
def test_inherit_constraints(model):
    """
    Various tests for copying of constraint values between compound models and
    their members.

    There are two versions of this test: One where a compound model is created
    from two model instances, and another where a compound model is created
    from two model classes that have default constraints set on some of their
    parameters.

    Regression test for https://github.com/astropy/astropy/issues/3481
    """

    # We have to copy the model before modifying it, otherwise the test fails
    # if it is run twice in a row, because the state of the model instance
    # would be preserved from one run to the next.
    model = deepcopy(model)

    # Lots of assertions in this test as there are multiple interfaces to
    # parameter constraints

    assert 'stddev_0' in model.bounds
    assert model.bounds['stddev_0'] == (0, 0.3)
    assert model.stddev_0.bounds == (0, 0.3)
    assert 'mean_0' in model.fixed
    assert model.fixed['mean_0'] is True
    assert model.mean_0.fixed is True
    assert 'mean_1' in model.fixed
    assert model.fixed['mean_1'] is True
    assert model.mean_1.fixed is True

    # Great, all the constraints were inherited properly
    # Now what about if we update them through the sub-models?
    model[0].stddev.bounds = (0, 0.4)
    assert model.bounds['stddev_0'] == (0, 0.4)
    assert model.stddev_0.bounds == (0, 0.4)
    assert model[0].stddev.bounds == (0, 0.4)
    assert model[0].bounds['stddev'] == (0, 0.4)

    model[0].bounds['stddev'] = (0.1, 0.5)
    assert model.bounds['stddev_0'] == (0.1, 0.5)
    assert model.stddev_0.bounds == (0.1, 0.5)
    assert model[0].stddev.bounds == (0.1, 0.5)
    assert model[0].bounds['stddev'] == (0.1, 0.5)

    model[1].mean.fixed = False
    assert model.fixed['mean_1'] is False
    assert model.mean_1.fixed is False
    assert model[1].mean.fixed is False
    assert model[1].fixed['mean'] is False

    model[1].fixed['mean'] = True
    assert model.fixed['mean_1'] is True
    assert model.mean_1.fixed is True
    assert model[1].mean.fixed is True
    assert model[1].fixed['mean'] is True

def test_compound_custom_inverse():
    """
    Test that a compound model with a custom inverse has that inverse applied
    when the inverse of another model, of which it is a component, is computed.
    Regression test for https://github.com/astropy/astropy/issues/3542
    """

    poly = Polynomial1D(1, c0=1, c1=2)
    scale = Scale(1)
    shift = Shift(1)

    model1 = poly | scale
    model1.inverse = poly

    # model1 now has a custom inverse (the polynomial itself, ignoring the
    # trivial scale factor)
    model2 = shift | model1

    assert_allclose(model2.inverse(1), (poly | shift.inverse)(1))

    # Make sure an inverse is not allowed if the models were combined with the
    # wrong operator, or if one of the models doesn't have an inverse defined
    with pytest.raises(NotImplementedError):
        (shift + model1).inverse

    with pytest.raises(NotImplementedError):
        (model1 & poly).inverse

@pytest.mark.parametrize('poly', [Chebyshev2D(1, 2), Polynomial2D(2), Legendre2D(1, 2),
                                  Chebyshev1D(5), Legendre1D(5), Polynomial1D(5)])
def test_compound_with_polynomials(poly):
    """
    Tests that polynomials are scaled when used in compound models.
    Issue #3699
    """
    poly.parameters = [1, 2, 3, 4, 1, 2]
    shift = Shift(3)
    model = poly | shift
    x, y = np.mgrid[:20, :37]
    result_compound = model(x, y)
    result = shift(poly(x, y))
    assert_allclose(result, result_compound)

# has to be defined at module level since pickling doesn't work right (in
# general) for classes defined in functions
class _TestPickleModel(Gaussian1D + Gaussian1D):
    pass

@pytest.mark.skipif(str("sys.version_info < (2, 7, 3)"))
def test_pickle_compound():
    """
    Regression test for
    https://github.com/astropy/astropy/issues/3867#issuecomment-114547228
    """

    # Test pickling a compound model class
    GG = Gaussian1D + Gaussian1D
    GG2 = pickle.loads(pickle.dumps(GG))
    assert GG.param_names == GG2.param_names
    assert GG.__name__ == GG2.__name__
    # Test that it works, or at least evaluates successfully
    assert GG()(0.12345) == GG2()(0.12345)

    # Test pickling a compound model instance
    g1 = Gaussian1D(1.0, 0.0, 0.1)
    g2 = Gaussian1D([2.0, 3.0], [0.0, 0.0], [0.2, 0.3])
    m = g1 + g2
    m2 = pickle.loads(pickle.dumps(m))
    assert m.param_names == m2.param_names
    assert m.__class__.__name__ == m2.__class__.__name__
    assert np.all(m.parameters == m2.parameters)
    assert np.all(m(0) == m2(0))

    # Test pickling a concrete class
    p = pickle.dumps(_TestPickleModel, protocol=0)
    # Note: This is very dependent on the specific protocol, but the point of
    # this test is that the "concrete" model is pickled in a very simple way
    # that only specifies the module and class name, and is unpickled by
    # re-importing the class from the module in which it was defined.  This
    # should still work for concrete subclasses of compound model classes that
    # were dynamically generated through an expression
    exp = b'castropy.modeling.tests.test_compound\n_TestPickleModel\np0\n.'
    # When testing against the expected value we drop the memo length field
    # at the end, which may differ between runs
    assert p[:p.rfind(b'p')] == exp[:exp.rfind(b'p')]
    assert pickle.loads(p) is _TestPickleModel

@pytest.mark.skipif(str("sys.version_info >= (2, 7, 3)"))
def test_pickle_compound_fallback():
    """
    Test fallback for pickling compound model on old versions of Python
    affected by http://bugs.python.org/issue7689
    """

    gg = (Gaussian1D + Gaussian1D)()
    with pytest.raises(RuntimeError):
        pickle.dumps(gg)

def test_update_parameters():
    offx = Shift(1)
    scl = Scale(2)
    m = offx | scl
    assert(m(1) == 4)

    offx.offset=42
    assert(m(1) == 4)

    m.factor_1 = 100
    assert(m(1) == 200)
    m2 = m | offx
    assert(m2(1) == 242)

def test_name():
    offx = Shift(1)
    scl = Scale(2)
    m = offx | scl
    scl.name = "scale"
    assert m._submodel_names == ('None_0', 'None_1')
    assert m.name is None
    m.name = "M"
    assert m.name == "M"
    m1 = m.rename("M1")
    assert m.name == "M"
    assert m1.name == "M1"


text:
package tv.dyndns.kishibe.qmaclone.client.creation.validater;

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

import tv.dyndns.kishibe.qmaclone.client.game.ProblemType;
import tv.dyndns.kishibe.qmaclone.client.packet.PacketProblem;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSet.Builder;
import com.google.common.collect.Sets;

public final class ValidatorMojiPanel extends Validator {
	public Evaluation check(PacketProblem problem) {
		Preconditions.checkArgument(problem.type == ProblemType.MojiPanel);

		Evaluation eval = super.check(problem);
		List<String> warn = eval.warn;

		List<String> answerList = problem.getAnswerList();
		if (answerList.isEmpty()) {
			warn.add("解答が入力されていません");
			return eval;
		}

		Set<Integer> answerLengths = Sets.newHashSet();
		for (int answerIndex = 0; answerIndex < answerList.size(); ++answerIndex) {
			String answer = answerList.get(answerIndex);

			if (answer.length() < 3) {
				warn.add((answerIndex + 1) + "番目の解答が短すぎます(3文字以上必要です)");
			}

			if (6 < answer.length()) {
				warn.add((answerIndex + 1) + "番目の解答が長すぎます(6文字以下でなければなりません)");
			}

			answerLengths.add(answer.length());
		}

		if (answerLengths.size() != 1) {
			warn.add("解答の長さがそろっていません");
		}

		List<String> choiceList = problem.getChoiceList();

		if (choiceList.isEmpty()) {
			warn.add("選択文字群が入力されていません");
			return eval;
		}

		String answer = answerList.get(0);
		String choice = choiceList.get(0);
		if (answer.length() == 3 && choice.length() != 6 && choice.length() != 8) {
			warn.add("解答が3文字の場合は選択文字群には6文字又は8文字必要です");
		} else if (4 <= answer.length() && answer.length() <= 6 && choice.length() != 10) {
			warn.add("解答が4~6文字の場合は選択文字群には10文字必要です");
		}

		Set<Character> letters = toCharacters(choice);
		if (letters.size() != choice.length()) {
			warn.add("選択文字群に同じ文字が含まれています");
		}

		for (int i = 0; i < answerList.size(); ++i) {
			Set<Character> answerLetters = toCharacters(answerList.get(i));

			if (!letters.containsAll(answerLetters)) {
				warn.add((i + 1) + "番目の解答の文字が選択文字群に含まれていません");
			}
		}

		return eval;
	}

	private Set<Character> toCharacters(String s) {
		// BugTrack-QMAClone/383 - QMAClone wiki
		// http://kishibe.dyndns.tv/qmaclone/wiki/wiki.cgi?page=BugTrack%2DQMAClone%2F383
		Builder<Character> builder = new ImmutableSet.Builder<Character>();
		for (char ch : s.toCharArray()) {
			builder.add(ch);
		}
		return builder.build();
	}
}


text:
package com.velir.newrelic.plugin;

import com.newrelic.metrics.publish.Runner;
import com.newrelic.metrics.publish.configuration.ConfigurationException;

public class Main {
	public static void main(String[] args) {
		try {
			Runner runner = new Runner();
			runner.add(new JVMAgentFactory());
			runner.setupAndRun(); // Never returns
		} catch (ConfigurationException e) {
			System.err.println("ERROR: " + e.getMessage());
			System.exit(-1);
		}
	}
}


text:
#import "ABI9_0_0RCTNativeAnimatedModule.h"

#import "ABI9_0_0RCTAdditionAnimatedNode.h"
#import "ABI9_0_0RCTAnimationDriverNode.h"
#import "ABI9_0_0RCTAnimationUtils.h"
#import "ABI9_0_0RCTBridge.h"
#import "ABI9_0_0RCTConvert.h"
#import "ABI9_0_0RCTInterpolationAnimatedNode.h"
#import "ABI9_0_0RCTLog.h"
#import "ABI9_0_0RCTMultiplicationAnimatedNode.h"
#import "ABI9_0_0RCTPropsAnimatedNode.h"
#import "ABI9_0_0RCTStyleAnimatedNode.h"
#import "ABI9_0_0RCTTransformAnimatedNode.h"
#import "ABI9_0_0RCTValueAnimatedNode.h"

@implementation ABI9_0_0RCTNativeAnimatedModule
{
  NSMutableDictionary<NSNumber *, ABI9_0_0RCTAnimatedNode *> *_animationNodes;
  NSMutableDictionary<NSNumber *, ABI9_0_0RCTAnimationDriverNode *> *_animationDrivers;
  NSMutableSet<ABI9_0_0RCTAnimationDriverNode *> *_activeAnimations;
  NSMutableSet<ABI9_0_0RCTAnimationDriverNode *> *_finishedAnimations;
  NSMutableSet<ABI9_0_0RCTValueAnimatedNode *> *_updatedValueNodes;
  NSMutableSet<ABI9_0_0RCTPropsAnimatedNode *> *_propAnimationNodes;
  CADisplayLink *_displayLink;
}

@synthesize bridge = _bridge;

ABI9_0_0RCT_EXPORT_MODULE()

- (void)setBridge:(ABI9_0_0RCTBridge *)bridge
{
  _bridge = bridge;
  _animationNodes = [NSMutableDictionary new];
  _animationDrivers = [NSMutableDictionary new];
  _activeAnimations = [NSMutableSet new];
  _finishedAnimations = [NSMutableSet new];
  _updatedValueNodes = [NSMutableSet new];
  _propAnimationNodes = [NSMutableSet new];
}

ABI9_0_0RCT_EXPORT_METHOD(createAnimatedNode:(nonnull NSNumber *)tag
                  config:(NSDictionary<NSString *, id> *)config)
{
  static NSDictionary *map;
  static dispatch_once_t mapToken;
  dispatch_once(&mapToken, ^{
    map = @{@"style" : [ABI9_0_0RCTStyleAnimatedNode class],
            @"value" : [ABI9_0_0RCTValueAnimatedNode class],
            @"props" : [ABI9_0_0RCTPropsAnimatedNode class],
            @"interpolation" : [ABI9_0_0RCTInterpolationAnimatedNode class],
            @"addition" : [ABI9_0_0RCTAdditionAnimatedNode class],
            @"multiplication" : [ABI9_0_0RCTMultiplicationAnimatedNode class],
            @"transform" : [ABI9_0_0RCTTransformAnimatedNode class]};
  });

  NSString *nodeType = [ABI9_0_0RCTConvert NSString:config[@"type"]];

  Class nodeClass = map[nodeType];
  if (!nodeClass) {
    ABI9_0_0RCTLogError(@"Animated node type %@ not supported natively", nodeType);
    return;
  }

  ABI9_0_0RCTAnimatedNode *node = [[nodeClass alloc] initWithTag:tag config:config];
  _animationNodes[tag] = node;

  if ([node isKindOfClass:[ABI9_0_0RCTPropsAnimatedNode class]]) {
    [_propAnimationNodes addObject:(ABI9_0_0RCTPropsAnimatedNode *)node];
  }
}

ABI9_0_0RCT_EXPORT_METHOD(connectAnimatedNodes:(nonnull NSNumber *)parentTag
                  childTag:(nonnull NSNumber *)childTag)
{
  ABI9_0_0RCTAssertParam(parentTag);
  ABI9_0_0RCTAssertParam(childTag);

  ABI9_0_0RCTAnimatedNode *parentNode = _animationNodes[parentTag];
  ABI9_0_0RCTAnimatedNode *childNode = _animationNodes[childTag];

  ABI9_0_0RCTAssertParam(parentNode);
  ABI9_0_0RCTAssertParam(childNode);

  [parentNode addChild:childNode];
}

ABI9_0_0RCT_EXPORT_METHOD(disconnectAnimatedNodes:(nonnull NSNumber *)parentTag
                  childTag:(nonnull NSNumber *)childTag)
{
  ABI9_0_0RCTAssertParam(parentTag);
  ABI9_0_0RCTAssertParam(childTag);

  ABI9_0_0RCTAnimatedNode *parentNode = _animationNodes[parentTag];
  ABI9_0_0RCTAnimatedNode *childNode = _animationNodes[childTag];

  ABI9_0_0RCTAssertParam(parentNode);
  ABI9_0_0RCTAssertParam(childNode);

  [parentNode removeChild:childNode];
}

ABI9_0_0RCT_EXPORT_METHOD(startAnimatingNode:(nonnull NSNumber *)animationId
                  nodeTag:(nonnull NSNumber *)nodeTag
                  config:(NSDictionary<NSString *, id> *)config
                  endCallback:(ABI9_0_0RCTResponseSenderBlock)callBack)
{
  if (ABI9_0_0RCT_DEBUG && ![config[@"type"] isEqual:@"frames"]) {
    ABI9_0_0RCTLogError(@"Unsupported animation type: %@", config[@"type"]);
    return;
  }

  NSTimeInterval delay = [ABI9_0_0RCTConvert double:config[@"delay"]];
  NSNumber *toValue = [ABI9_0_0RCTConvert NSNumber:config[@"toValue"]] ?: @1;
  NSArray<NSNumber *> *frames = [ABI9_0_0RCTConvert NSNumberArray:config[@"frames"]];

  ABI9_0_0RCTValueAnimatedNode *valueNode = (ABI9_0_0RCTValueAnimatedNode *)_animationNodes[nodeTag];

  ABI9_0_0RCTAnimationDriverNode *animationDriver =
  [[ABI9_0_0RCTAnimationDriverNode alloc] initWithId:animationId
                                       delay:delay
                                     toValue:toValue.doubleValue
                                      frames:frames
                                     forNode:valueNode
                                    callBack:callBack];
  [_activeAnimations addObject:animationDriver];
  _animationDrivers[animationId] = animationDriver;
  [animationDriver startAnimation];
  [self startAnimation];
}

ABI9_0_0RCT_EXPORT_METHOD(stopAnimation:(nonnull NSNumber *)animationId)
{
  ABI9_0_0RCTAnimationDriverNode *driver = _animationDrivers[animationId];
  if (driver) {
    [driver removeAnimation];
    [_animationDrivers removeObjectForKey:animationId];
    [_activeAnimations removeObject:driver];
    [_finishedAnimations removeObject:driver];
  }
}

ABI9_0_0RCT_EXPORT_METHOD(setAnimatedNodeValue:(nonnull NSNumber *)nodeTag
                  value:(nonnull NSNumber *)value)
{
  ABI9_0_0RCTAnimatedNode *node = _animationNodes[nodeTag];
  if (![node isKindOfClass:[ABI9_0_0RCTValueAnimatedNode class]]) {
    ABI9_0_0RCTLogError(@"Not a value node.");
    return;
  }
  ABI9_0_0RCTValueAnimatedNode *valueNode = (ABI9_0_0RCTValueAnimatedNode *)node;
  valueNode.value = value.floatValue;
  [valueNode setNeedsUpdate];
}

ABI9_0_0RCT_EXPORT_METHOD(connectAnimatedNodeToView:(nonnull NSNumber *)nodeTag
                  viewTag:(nonnull NSNumber *)viewTag)
{
  ABI9_0_0RCTAnimatedNode *node = _animationNodes[nodeTag];
  if (viewTag && [node isKindOfClass:[ABI9_0_0RCTPropsAnimatedNode class]]) {
    [(ABI9_0_0RCTPropsAnimatedNode *)node connectToView:viewTag animatedModule:self];
  }
}

ABI9_0_0RCT_EXPORT_METHOD(disconnectAnimatedNodeFromView:(nonnull NSNumber *)nodeTag
                  viewTag:(nonnull NSNumber *)viewTag)
{
  ABI9_0_0RCTAnimatedNode *node = _animationNodes[nodeTag];
  if (viewTag && node && [node isKindOfClass:[ABI9_0_0RCTPropsAnimatedNode class]]) {
    [(ABI9_0_0RCTPropsAnimatedNode *)node disconnectFromView:viewTag];
  }
}

ABI9_0_0RCT_EXPORT_METHOD(dropAnimatedNode:(nonnull NSNumber *)tag)
{
  ABI9_0_0RCTAnimatedNode *node = _animationNodes[tag];
  if (node) {
    [node detachNode];
    [_animationNodes removeObjectForKey:tag];
    if ([node isKindOfClass:[ABI9_0_0RCTValueAnimatedNode class]]) {
      [_updatedValueNodes removeObject:(ABI9_0_0RCTValueAnimatedNode *)node];
    } else if ([node isKindOfClass:[ABI9_0_0RCTPropsAnimatedNode class]]) {
      [_propAnimationNodes removeObject:(ABI9_0_0RCTPropsAnimatedNode *)node];
    }
  }
}

#pragma mark -- Animation Loop

- (void)startAnimation
{
  if (!_displayLink && _activeAnimations.count > 0) {
    _displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateAnimations)];
    [_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
  }
}

- (void)updateAnimations
{
  // Step Current active animations
  // This also recursively marks children nodes as needing update
  for (ABI9_0_0RCTAnimationDriverNode *animationDriver in _activeAnimations) {
    [animationDriver stepAnimation];
  }

  // Perform node updates for marked nodes.
  // At this point all nodes that are in need of an update are properly marked as such.
  for (ABI9_0_0RCTPropsAnimatedNode *propsNode in _propAnimationNodes) {
    [propsNode updateNodeIfNecessary];
  }

  // Cleanup nodes and prepare for next cycle. Remove updated nodes from bucket.
  for (ABI9_0_0RCTAnimationDriverNode *driverNode in _activeAnimations) {
    [driverNode cleanupAnimationUpdate];
  }
  for (ABI9_0_0RCTValueAnimatedNode *valueNode in _updatedValueNodes) {
    [valueNode cleanupAnimationUpdate];
  }
  [_updatedValueNodes removeAllObjects];

  for (ABI9_0_0RCTAnimationDriverNode *driverNode in _activeAnimations) {
    if (driverNode.animationHasFinished) {
      [driverNode removeAnimation];
      [_finishedAnimations addObject:driverNode];
    }
  }
  for (ABI9_0_0RCTAnimationDriverNode *driverNode in _finishedAnimations) {
    [_activeAnimations removeObject:driverNode];
    [_animationDrivers removeObjectForKey:driverNode.animationId];
  }
  [_finishedAnimations removeAllObjects];

  if (_activeAnimations.count == 0) {
    [_displayLink invalidate];
    _displayLink = nil;
  }
}

@end


text:
'use strict';

var grunt = require('grunt');

/*
 ======== A Handy Little Nodeunit Reference ========
 https://github.com/caolan/nodeunit

 Test methods:
 test.expect(numAssertions)
 test.done()
 Test assertions:
 test.ok(value, [message])
 test.equal(actual, expected, [message])
 test.notEqual(actual, expected, [message])
 test.deepEqual(actual, expected, [message])
 test.notDeepEqual(actual, expected, [message])
 test.strictEqual(actual, expected, [message])
 test.notStrictEqual(actual, expected, [message])
 test.throws(block, [error], [message])
 test.doesNotThrow(block, [error], [message])
 test.ifError(value)
 */

exports.html_imports = {
    setUp: function (done) {
        // setup here if necessary
        done();
    },

    // test two basic imports.
    basic_import: function (test) {
        test.expect(2);

        //index.html
        var actual = grunt.file.read('tmp/output/index.html');
        var expected = grunt.file.read('test/expected/index.html');
        test.equal(actual, expected, 'The import-link tag should be replaced with the according html fragment.');

        //about.html
        actual = grunt.file.read('tmp/output/about.html');
        expected = grunt.file.read('test/expected/about.html');
        test.equal(actual, expected, 'The import-link tag should be replaced with the according html fragment.');

        test.done();
    },

    recursive_import: function (test) {
        test.expect(1);

        var actual = grunt.file.read('tmp/output/recurse/a.html');
        var expected = grunt.file.read('test/expected/a.html');

        test.equal(actual, expected, 'The page should contain all fragment content even imported recursively');

        test.done();
    }
};


text:
export class ExplainResult {
    constructor(public result: any, public explain: any) {}
}

export class PromiseResult<T> extends Promise<T> {
    constructor(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void) {
        super(executor);
    }

    then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2> {
        if (onfulfilled != null) {
            let callback = onfulfilled as any;
            onfulfilled = (args) => {
                if (args instanceof ExplainResult) {
                    return callback(args.result, args.explain);
                } else {
                    return callback(args);
                }
            }
        }
        if (onrejected != null) {
            let callback = onrejected as any;
            onrejected = (args) => {
                if (args instanceof ExplainResult) {
                    return callback(args.result, args.explain);
                } else {
                    return callback(args);
                }
            }
        }
        return super.then(onfulfilled, onrejected);
    }

    catch<TResult2 = never>(onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult2 | T> {
        if (onrejected != null) {
            let callback = onrejected as any;
            onrejected = (args) => {
                if (args instanceof ExplainResult) {
                    return callback(args.result, args.explain);
                } else {
                    return callback(args);
                }
            }
        }
        return super.catch(onrejected);
    }
}


text:
from live import LiveWidget, get_moksha_socket
from placeholder import Placeholder
from selectable import Selectable


text:
package com.company.app;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import sun.awt.AppContext;
import sun.org.mozilla.javascript.tools.shell.ShellLine;

/**
 * Hello world!
 *
 */
public class App
{
    public static void main( String[] args )
    {
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

        HelloWorld helloWorld = (HelloWorld)context.getBean("helloWorld");
        helloWorld.getMessage();
        context.registerShutdownHook();

    }
}


text:
using System;

namespace InsightsSample
{
    public static class Consts
    {
        public const string InsightsApiKey = "5bcafe224ff3dda5a63f749f462606c4bf786de8";
    }
}


text:
from __future__ import print_function

import os
import shutil

import conda_build.build as build_module
from conda_build.metadata import MetaData
import conda_build.config
from conda.lock import Locked
from conda_build.build import bldpkg_path
import binstar_client
from binstar_client.utils.detect import detect_package_type, get_attrs

from . import inspect_binstar

def build(meta, test=True):
    """Build (and optionally test) a recipe directory."""
    with Locked(conda_build.config.croot):
        meta.check_fields()
        if os.path.exists(conda_build.config.config.info_dir):
            shutil.rmtree(conda_build.config.config.info_dir)
        build_module.build(meta, verbose=False, post=None)
        if test:
            build_module.test(meta, verbose=False)
        return meta

def upload(cli, meta, owner, channels=['main']):
    """Upload a distribution, given the build metadata."""
    fname = bldpkg_path(meta)
    package_type = detect_package_type(fname)
    package_attrs, release_attrs, file_attrs = get_attrs(package_type, fname)
    package_name = package_attrs['name']
    version = release_attrs['version']

    # Check the package exists, otherwise create one.
    try:
        cli.package(owner, package_name)
    except binstar_client.NotFound:
        print('Creating the {} package on {}'.format(package_name, owner))
        summary = package_attrs['summary']
        cli.add_package(owner, package_name, summary, package_attrs.get('license'), public=True)

    # Check the release exists, otherwise create one.
    try:
        cli.release(owner, package_name, version)
    except binstar_client.NotFound:
        # TODO: Add readme.md support for descriptions?
        cli.add_release(owner, package_name, version, requirements=[], announce=None,
                        description='')

    try:
        cli.distribution(owner, package_name, version, file_attrs['basename'])
    except binstar_client.NotFound:
        # The file doesn't exist.
        pass
    else:
        print('Distribution %s already exists ... removing' % (file_attrs['basename'],))
        cli.remove_dist(owner, package_name, version, file_attrs['basename'])

    with open(fname, 'rb') as fd:
        print('\nUploading file %s/%s/%s/%s to %s...' % (owner, package_name, version, file_attrs['basename'], channels))
        upload_info = cli.upload(owner, package_name, version, file_attrs['basename'],
                                 fd, package_type, description='',
                                 dependencies=file_attrs.get('dependencies'),
                                 attrs=file_attrs['attrs'],
                                 channels=channels)
        return upload_info


text:
<script src="https://login.persona.org/include.js"></script>
<script type="text/javascript">
(function() {
  var allauth = window.allauth = window.allauth || {};

  function startWatching() {
    navigator.id.watch({
      onlogin: function(assertion) {
        // TODO: next url handling
        document.getElementById("_persona_assertion").value = assertion;
        document.getElementById("_persona_login").submit();
      },
      onlogout: function() {
        // TODO
      }
    })
  };

  allauth.persona = {
    login: function(nextUrl, process) {
        document.getElementById("_persona_next_url").value = nextUrl || '';
        document.getElementById("_persona_process").value = process;
        startWatching();
        navigator.id.request({{ request_parameters|safe }});
    }
  }
})();
</script>

<form id="_persona_login" method="post" action="{% url 'persona_login' %}">
{% csrf_token %}
<input type="hidden" name="next" value="" id="_persona_next_url"/>
<input type="hidden" name="process" value="" id="_persona_process"/>
<input type="hidden" name="assertion" id="_persona_assertion"/>
</form>


text:
Version: 0.0.3

PCG Version: 0.94

A python CFFI wrapper around the pcg random number generator library

# Installation Note
Currently the setup.py script may build the extension module in the wrong
location. If this happens and you get an import error you can fix this by
running python as superuser and importing the library once. This will allow
the required module to be built and all other imports should work.


text:
<template>
	<require from="../address"></require>

				<button type="button" class="btn btn-default" data-toggle="collapse" data-target="#details-${contact.id}">

${contact.first} ${contact.last}

${contact.first} ${contact.last}

						<address model.bind="contact.address" one-line></address>

							<compose view="../phone-number.html"></compose>

				</button>

				<address model.bind="contact.address"></address>

					<compose view="../phone-number.html" model.bind="contact"></compose>

</template>


text:
package org.sp.integration.tests.core.beans;

import java.util.List;

/**
 * Instance URL Bean
 */

public class InstanceUrls {

    private String hostIP;
    private String label;
    private List<Port> ports;

    public String getHostIP() {
        return hostIP;
    }

    public void setHostIP(String hostIP) {
        this.hostIP = hostIP;
    }

    public List<Port> getPorts() {
        return ports;
    }

    public void setPorts(List<Port> ports) {
        this.ports = ports;
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }
}


text:
**tl;dr: Use GitHub issues, include relevant info**

To report an issue with snoowrap, please [create a new issue on GitHub](https://github.com/not-an-aardvark/snoowrap/issues/new). It's usually helpful to include any details that might be relevant to reproducing the issue (the code that causes it, the version of node that you're using, etc.)

## Requesting features

To make a feature request, [create a new issue on GitHub](https://github.com/not-an-aardvark/snoowrap/issues/new).

## Making code contributions

**tl;dr contributions are welcome, make sure the tests pass, keep the linter happy**

Contributions are welcome. To contribute code, fork snoowrap and create a pull request.

Code style is enforced by [ESLint](https://github.com/eslint/eslint) -- please try to make it pass without any warnings/errors. The ESLint configuration can be found [here](https://github.com/not-an-aardvark/snoowrap/blob/master/.eslintrc.json), but it'll probably be easier to just copy the style of the surrounding code.

For bugfixes and new features, it's appreciated if you also add a regression test.

[This guide](https://github.com/not-an-aardvark/snoowrap/blob/master/src/README.md) contains details on how to run the tests, as well as a general overview of the code.


text:
<?php

namespace Razor;

use Razor\Services\Http;
use Symfony\Component\HttpFoundation\Request;
use Rawebone\Injector\RegisterResolver;

class Environment
{
	public $development = true;
	public $testing = false;

	protected $services;

	public function __construct()
	{
		$this->services = new RegisterResolver();

		$this->setupServices();
	}

	/**
	 * The environments service container.
	 *
	 * @return \Rawebone\Injector\RegisterResolver
	 */
	public function services()
	{
		return $this->services;
	}

	/**
	 * Registers a service provider with the Environment.
	 *
	 * @param Provider $provider
	 */
	public function registerProvider(Provider $provider)
	{
		$provider->letResolverBe($this->services);
		$provider->register();
	}

	protected function setupServices()
	{
		// Save the environment instance for use by
		// some of the framework services.
		$this->services->registerObject("razor", $this);

		$this->services->register("request", function ()
		{
			return Request::createFromGlobals();
		});

		$this->services->register("response", function ()
		{
			return new HttpResponse();
		});

		$this->services->register("http", function (HttpResponse $response, Request $request)
		{
			return new Http($request, $response);
		});
	}
}


text:
std::string dir_read_tile(std::string pbfPath);

void dir_write_tile(const char *outdir, int z, int tx, int ty, std::string const &pbf);

void check_dir(const char *d, bool rm);

#endif


text:
title: Al-Mursalat
subtitle: La senditoj
---

En la nomo de Dio, la Kompatema, la Plej Kompata

1. Je tiuj senditaj unu post la alia
2. kaj la ventoj blovantaj perforte
3. kaj la dismetantaj vaste
4. kaj la disigantaj kriterie
5. kaj la malsuprenigantaj la memorigon
6. pravigante aŭ avertante
7. Vere tio promesita al vi certe okazos
8. Do kiam la steloj estingiĝas
9. kaj kiam la ĉielo fendiĝas
10. kaj kiam la montoj forbloviĝas
11. kaj kiam la mesaĝistoj kolektiĝas
12. Por kiu tago prokrastiĝas
13. Por la tago de Juĝo
14. Kaj kio sciigas kio estas la tago de Juĝo
15. Ve tiun tagon al la neantoj
16. Ĉu ne ni detruas la antaŭajn
17. Tiam ni sekvigos la postajn
18. Tiel ni traktas la krimulojn
19. Ve tiun tagon al la neantoj
20. Ĉu ne ni kreis vin el akvo senvalora
21. Tiam ni metis ĝin en sekuran lokon
22. Por periodo konata
23. do ni mezuris kaj plej bone ni mezuras
24. Ve tiun tagon al la neantoj
25. Ĉu ne ni kreis la teron ujo
26. de vivantaj kaj mortaj
27. kaj ni kreis en ĝi montegojn superajn kaj ni trinkigis akvon dolĉan
28. Ve tiun tagon al la neantoj
29. Pluiru al kion vi kutimis en ĝi nei
30. Pluiru al ombro havanta tri kolumnojn
31. Ne freŝa ombro kaj ne servos kontraŭ la flamo
32. Vere, ĝi elĵetas fajrerojn fortikajn
33. Kvazaŭ kameloj flavaj
34. Ve tiun tagon al la neantoj
35. Tiun tagon ne ili parolos
36. Kaj ne permesiĝos al ili senkulpiĝi
37. Ve tiun tagon al la neantoj
38. Tiun tagon de Juĝo ni kolektas vin kaj la antaŭajn
39. Do se havas vi ruzon, al mi ruzu
40. Ve tiun tagon al la neantoj
41. Vere la justa estos en ombroj kaj fontanoj
42. Kaj estos fruktoj el kion ili volas
43. Manĝu kaj trinku kontente por kion vi kutimis fari
44. Vere, ni tiel rekompensos la bonfarantojn
45. Ve tiun tagon al la neantoj
46. Manĝu kaj ĝuu iom, vere vi estas krimuloj
47. Ve tiun tagon al la neantoj
48. Kaj kiam diriĝas al ili kliniĝi, ne ili kliniĝas
49. Ve tiun tagon al la neantoj
50. Do en kiu aserto post ĝi ili kredos


text:
namespace FIX43
{

  class News : public Message
  {
  public:
    News() : Message(MsgType()) {}
    News(const FIX::Message& m) : Message(m) {}
    News(const Message& m) : Message(m) {}
    News(const News& m) : Message(m) {}
    static FIX::MsgType MsgType() { return FIX::MsgType("B"); }

    News(
      const FIX::Headline& aHeadline )
    : Message(MsgType())
    {
      set(aHeadline);
    }

    FIELD_SET(*this, FIX::OrigTime);
    FIELD_SET(*this, FIX::Urgency);
    FIELD_SET(*this, FIX::Headline);
    FIELD_SET(*this, FIX::EncodedHeadlineLen);
    FIELD_SET(*this, FIX::EncodedHeadline);
    FIELD_SET(*this, FIX::URLLink);
    FIELD_SET(*this, FIX::RawDataLength);
    FIELD_SET(*this, FIX::RawData);
    FIELD_SET(*this, FIX::NoRoutingIDs);
    class NoRoutingIDs: public FIX::Group
    {
    public:
    NoRoutingIDs() : FIX::Group(215,216,FIX::message_order(216,217,0)) {}
      FIELD_SET(*this, FIX::RoutingType);
      FIELD_SET(*this, FIX::RoutingID);
    };
    FIELD_SET(*this, FIX::NoRelatedSym);
    class NoRelatedSym: public FIX::Group
    {
    public:
    NoRelatedSym() : FIX::Group(146,55,FIX::message_order(55,65,48,22,454,460,461,167,200,541,224,225,239,226,227,228,255,543,470,471,472,240,202,206,231,223,207,106,348,349,107,350,351,0)) {}
      FIELD_SET(*this, FIX::Symbol);
      FIELD_SET(*this, FIX::SymbolSfx);
      FIELD_SET(*this, FIX::SecurityID);
      FIELD_SET(*this, FIX::SecurityIDSource);
      FIELD_SET(*this, FIX::Product);
      FIELD_SET(*this, FIX::CFICode);
      FIELD_SET(*this, FIX::SecurityType);
      FIELD_SET(*this, FIX::MaturityMonthYear);
      FIELD_SET(*this, FIX::MaturityDate);
      FIELD_SET(*this, FIX::CouponPaymentDate);
      FIELD_SET(*this, FIX::IssueDate);
      FIELD_SET(*this, FIX::RepoCollateralSecurityType);
      FIELD_SET(*this, FIX::RepurchaseTerm);
      FIELD_SET(*this, FIX::RepurchaseRate);
      FIELD_SET(*this, FIX::Factor);
      FIELD_SET(*this, FIX::CreditRating);
      FIELD_SET(*this, FIX::InstrRegistry);
      FIELD_SET(*this, FIX::CountryOfIssue);
      FIELD_SET(*this, FIX::StateOrProvinceOfIssue);
      FIELD_SET(*this, FIX::LocaleOfIssue);
      FIELD_SET(*this, FIX::RedemptionDate);
      FIELD_SET(*this, FIX::StrikePrice);
      FIELD_SET(*this, FIX::OptAttribute);
      FIELD_SET(*this, FIX::ContractMultiplier);
      FIELD_SET(*this, FIX::CouponRate);
      FIELD_SET(*this, FIX::SecurityExchange);
      FIELD_SET(*this, FIX::Issuer);
      FIELD_SET(*this, FIX::EncodedIssuerLen);
      FIELD_SET(*this, FIX::EncodedIssuer);
      FIELD_SET(*this, FIX::SecurityDesc);
      FIELD_SET(*this, FIX::EncodedSecurityDescLen);
      FIELD_SET(*this, FIX::EncodedSecurityDesc);
      FIELD_SET(*this, FIX::NoSecurityAltID);
      class NoSecurityAltID: public FIX::Group
      {
      public:
      NoSecurityAltID() : FIX::Group(454,455,FIX::message_order(455,456,0)) {}
        FIELD_SET(*this, FIX::SecurityAltID);
        FIELD_SET(*this, FIX::SecurityAltIDSource);
      };
    };
    FIELD_SET(*this, FIX::LinesOfText);
    class LinesOfText: public FIX::Group
    {
    public:
    LinesOfText() : FIX::Group(33,58,FIX::message_order(58,354,355,0)) {}
      FIELD_SET(*this, FIX::Text);
      FIELD_SET(*this, FIX::EncodedTextLen);
      FIELD_SET(*this, FIX::EncodedText);
    };
  };

}

#endif


text:
"""A set of utilities used throughout the mongo-connector
"""

import sys
import time
import logging

from bson.timestamp import Timestamp
try:
    from urllib2 import urlopen, URLError
except ImportError:
    from urllib.request import urlopen, URLError

def bson_ts_to_long(timestamp):
    """Convert BSON timestamp into integer.

    Conversion rule is based from the specs
    (http://bsonspec.org/#/specification).
    """
    return ((timestamp.time << 32) + timestamp.inc)

def long_to_bson_ts(val):
    """Convert integer into BSON timestamp.
    """
    seconds = val >> 32
    increment = val & 0xffffffff

    return Timestamp(seconds, increment)

def retry_until_ok(func, *args, **kwargs):
    """Retry code block until it succeeds.

    If it does not succeed in 60 attempts, the
    function simply exits.
    """

    result = True
    count = 0
    while True:
        try:
            result = func(*args, **kwargs)
            break
        except:
            count += 1
            if count > 60:
                string = 'Call to %s failed too many times' % func
                string += ' in retry_until_ok'
                logging.error(string)
                sys.exit(1)
            time.sleep(1)

    return result


text:
import multiprocessing
from six.moves import configparser
import six

class AnswerStore(object):
    """
    AnswerStore handles storing and loading answer files for user questions.
    """
    def __init__(self, manager=None):
        """
        Initialize the answer store.
        :param manager: Passes through a given instance of multiprocessing.Manager() to use, by default it creates
                        an own instance.
        """
        self._manager = manager or multiprocessing.Manager()
        self._storage = self._manager.dict()

    def answer(self, scope, key, value):
        dialog_scope = self._storage.get(scope, {})
        dialog_scope[key] = value
        # As _storage is a dict proxy, we have to explicitly update the object via __setitem__
        # Otherwise we won't get the update propagated to the parent process
        # So don't even bother updating this to some more 'pythonic' coding style
        self._storage[scope] = dialog_scope

    def load(self, answer_file):
        """
        Loads an answer file from the given location and updates the loaded data with it.

        :param answer_file: Path to the answer file to load.
        :return: None
        """
        conf = configparser.SafeConfigParser(allow_no_value=True)
        conf.read(answer_file)
        for section in conf.sections():
            self._storage[section] = self._manager.dict(conf.items(section=section, raw=True))

    def load_and_translate_for_workflow(self, answer_file, workflow):
        """
        Loads an answer file from the given location and updates the loaded data with it and translates the data to
        the correct value types based on the dialogs in the given workflow.

        :param answer_file: Path to the answer file to load.
        :param workflow:
        :return: None
        """
        conf = configparser.SafeConfigParser(allow_no_value=True)
        conf.read(answer_file)
        for section in conf.sections():
            self._storage[section] = dict(conf.items(section=section, raw=True))
        self.translate_for_workflow(workflow)

    def get(self, scope, fallback=None):
        """
        Dict compatible interface to get a sub dictionary by dialog scope.

        :param scope: Scope of the data to retrieve.
        :param fallback: Fallback value to return if not found.
        :return:
        """
        return self._storage.get(scope, fallback)

    def translate_for_workflow(self, workflow):
        """
        Translates the data for all dialogs in the current workflow.

        :param workflow: Instance of a workflow to translate all dialogs from.
        :type workflow: :py:class:`leapp.workflows.Workflow`
        :return: None
        """
        for dialog in self._get_dialogs(workflow):
            self.translate(dialog)

    def translate(self, dialog):
        """
        Translates configuration values from their string form to the corresponding value format based on the given
        dialog.

        :param dialog: A dialog instance to translate the data for.
        :type dialog: :py:class:`leapp.dialogs.dialog.Dialog`
        :return: None
        """
        entry = self._storage.get(dialog.scope)
        if entry:
            for component in dialog.components:
                if component.key in entry and isinstance(entry[component.key], six.string_types):
                    if component.value_type is bool:
                        entry[component.key] = entry[component.key].lower() == 'true'
                    elif component.value_type is int:
                        entry[component.key] = int(entry[component.key])
                    elif component.value_type is tuple:
                        elements = entry[component.key].split(';')
                        entry[component.key] = tuple(set(elements).intersection(component.choices))
                    elif hasattr(component, 'choices'):
                        value = entry[component.key]
                        entry[component.key] = value if value in component.choices else None
                    component.value = entry.get(component.key)
            self._storage.update({dialog.scope: entry})

    @staticmethod
    def _get_dialogs(workflow):
        """
        Retrieve all dialogs from the actors of the given workflow.

        :param workflow: Workflow to retrieve all questions from.

        :return: List of dialogs from the actors.
        """
        dialogs = []
        for phase in workflow.phase_actors:
            for stage in phase[1:]:
                for actor in stage.actors:
                    dialogs.extend(actor.dialogs)
        return dialogs

    def generate_for_workflow(self, workflow, answer_file_path):
        """
        Generates an answer file for the dialogs of the given workflow and stores it to `answer_file_path`.
        :param workflow: Instance of :py:class:`leapp.workflows.Workflow` to retrieve all dialogs from.
        :param answer_file_path: The path of where to store the answer file to.
        :return: None
        """
        self.generate(self._get_dialogs(workflow), answer_file_path)

    def generate(self, dialogs, answer_file_path):
        """
        Generates an answer file for the given dialogs and stores it to `answer_file_path`.
        :param dialogs:
        :param answer_file_path:
        :return:
        """
        with open(answer_file_path, 'w') as f:
            for dialog in dialogs:
                if not dialog.components:
                    # Skip dialogs without questions
                    continue

                f.writelines([
                    '[{}]\n'.format(dialog.scope),
                    '# {:<20}{}\n'.format('Title:', dialog.title),
                    '# {:<20}{}\n'.format('Reason:', dialog.reason)
                ])

                for component in dialog.components:
                    answer = self._storage.get(dialog.scope, {}).get(component.key)
                    default = component.default
                    choices = ''
                    answer_entry = ''
                    if hasattr(component, 'choices'):
                        choices += '# Available choices:\n'
                        for choice in component.choices:
                            choices += '# - {}\n'.format(choice)
                        if component.value_type is tuple:
                            default = ';'.join(component.default)
                            answer = ';'.join(answer) if answer else answer
                            answer_entry = '#\n# Values are separated by semi-colon ";"\n'
                    if answer:
                        answer_entry += '{key} = {value}\n'.format(key=component.key, value=answer)
                    else:
                        answer_entry += '# Unanswered question. Uncomment the following line with your answer\n'
                        answer_entry += '# {key} = {value}\n'.format(key=component.key, value=default or '')

                    f.writelines([
                        '# {}\n'.format(' {}.{} '.format(dialog.scope, component.key).center(77, '=')),
                        '# {:<20}{}\n'.format('Label:', component.label),
                        '# {:<20}{}\n'.format('Description:', component.description),
                        '# {:<20}{}\n'.format('Type:', component.value_type.__name__),
                        '# {:<20}{}\n'.format('Default:', default),
                        choices,
                        answer_entry,
                        '\n'
                    ])


text:
<?php

namespace Magento\Cms\Test\Handler\CmsBlock;

use Magento\Mtf\Handler\HandlerInterface;

/**
 * Interface CmsBlockInterface
 */
interface CmsBlockInterface extends HandlerInterface
{
    //
}


text:
/**
 * OAuth 2.0 utilities that help simplify the authorization flow in HTTP servlets.
 *
 * @since 1.7
 * @author Yaniv Inbar
 */

package com.google.api.client.extensions.servlet.auth.oauth2;


text:
package org.springframework.social.twitter.api.impl;

import java.io.IOException;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.social.twitter.api.DirectMessage;
import org.springframework.social.twitter.api.StreamDeleteEvent;
import org.springframework.social.twitter.api.StreamEvent;
import org.springframework.social.twitter.api.StreamListener;
import org.springframework.social.twitter.api.StreamWarningEvent;
import org.springframework.social.twitter.api.Tweet;
import org.springframework.social.twitter.api.TwitterProfile;

import com.fasterxml.jackson.databind.ObjectMapper;

class StreamDispatcher implements Runnable {
	private static final Log logger = LogFactory.getLog(StreamDispatcher.class);

	private final List<StreamListener> listeners;

	private ObjectMapper objectMapper;

	private AtomicBoolean active;

	private final Queue<String> queue;

	private final ExecutorService pool;

	public StreamDispatcher(Queue<String> queue, List<StreamListener> listeners) {
		this.queue = queue;
		this.listeners = listeners;
		pool = Executors.newCachedThreadPool();
		objectMapper = new ObjectMapper();
		objectMapper.addMixInAnnotations(Tweet.class, TweetMixin.class);
		objectMapper.addMixInAnnotations(StreamDeleteEvent.class, StreamDeleteEventMixin.class);
		objectMapper.addMixInAnnotations(StreamWarningEvent.class, StreamWarningEventMixin.class);
		objectMapper.addMixInAnnotations(StreamEvent.class, StreamEventMixin.class);
		objectMapper.addMixInAnnotations(DirectMessage.class, DirectMessageMixin.class);
		objectMapper.addMixInAnnotations(TwitterProfile.class, TwitterProfileMixin.class);
		active = new AtomicBoolean(true);
	}

	public void run() {
		while(active.get()) {
			String line = queue.poll();
			if(line == null || line.length() == 0) return;

			// TODO: handle scrub_geo, status_withheld, user_withheld, disconnect, friends, events,

			logger.debug(line);

			try {
				if (line.contains("in_reply_to_status_id_str")) { // TODO: This is kinda hacky
					handleTweet(line);
				} else if (line.startsWith("{\"limit")) {
					handleLimit(line);
				} else if (line.startsWith("{\"delete")) {
					handleDelete(line);
				} else if (line.startsWith("{\"warning")) {
					handleWarning(line);
				} else if (line.startsWith("{\"event")) {
					handleEvent(line);
				}
				else if (line.startsWith("{\"direct_message")) {
					handleDirectMessage(line);
				}
			} catch (IOException e) {
				// TODO: Should only happen if Jackson doesn't know how to map the line
			}
		}
	}

	public void stop() {
		active.set(false);
		pool.shutdown();
	}

	private void handleDelete(String line) throws IOException {
		final StreamDeleteEvent deleteEvent = objectMapper.readValue(line, StreamDeleteEvent.class);
		for (final StreamListener listener : listeners) {
			Future<?> result = pool.submit((new Runnable() {
				public void run() {
					listener.onDelete(deleteEvent);
				}
			}));
		}
	}

	private void handleLimit(String line) throws IOException {
		final TrackLimitEvent limitEvent = objectMapper.readValue(line, TrackLimitEvent.class);
		for (final StreamListener listener : listeners) {
			Future<?> result = pool.submit((new Runnable() {
				public void run() {
					listener.onLimit(limitEvent.getNumberOfLimitedTweets());
				}
			}));
		}
	}

	private void handleTweet(String line) throws IOException {
		final Tweet tweet = objectMapper.readValue(line, Tweet.class);
		for (final StreamListener listener : listeners) {
			Future<?> result = pool.submit((new Runnable() {
				public void run() {
					listener.onTweet(tweet);
				}
			}));
		}
	}

	private void handleWarning(String line) throws IOException {
		final StreamWarningEvent warningEvent = objectMapper.readValue(line, StreamWarningEvent.class);
		for (final StreamListener listener : listeners) {
			Future<?> result = pool.submit((new Runnable() {
				public void run() {
					listener.onWarning(warningEvent);
				}
			}));
		}
	}

	private void handleEvent(String line) throws IOException {
		final StreamEvent event = objectMapper.readValue(line, StreamEvent.class);
		for (final StreamListener listener : listeners) {
			Future<?> result = pool.submit((new Runnable() {
				public void run() {
					listener.onEvent(event);
				}
			}));
		}
	}

	private void handleDirectMessage(String line) throws IOException {
		String messagePart = objectMapper.readTree(line).get("direct_message").toString();
		final DirectMessage directMessage = objectMapper.readValue(messagePart, DirectMessage.class);
		for (final StreamListener listener : listeners) {
			Future<?> result = pool.submit((new Runnable() {
				public void run() {
					listener.onDirectMessage(directMessage);
				}
			}));
		}
	}

}


text:
def applicability_condition(self,agent,Place=-1):
	if not checkCapability(agent,self.id):
		return FAILURE
	return SUCCESS

def preparatory_spec(self,agent,Place=-1):
	return SUCCESS

def execution_steps(self,agent,Place=-1):
	return {'PRIMITIVE':('play',{'agents':agent,'objects':(Place)})}

def culmination_condition(self,agent,Place=-1):
	if finishedAction(self.id):
		return SUCCESS
	return INCOMPLETE


text:
<?php

namespace Timiki\Bundle\RpcServerBundle\Serializer;

use Symfony\Component\Serializer\Encoder\JsonEncode;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

class BaseSerializer implements SerializerInterface
{
    /**
     * @var Serializer|null
     */
    protected $serializer;

    /**
     * BaseSerializer constructor.
     */
    public function __construct(Serializer $serializer = null)
    {
        $this->serializer = $serializer;

        if (null === $this->serializer) {
            $this->serializer = new Serializer([new ObjectNormalizer()], [new JsonEncode()]);
        }
    }

    /**
     * Serialize data.
     *
     * @param mixed $data
     *
     * @return array
     */
    public function serialize($data)
    {
        if ($this->serializer) {
            return \json_decode($this->serializer->serialize($data, 'json'), true);
        }

        return $data;
    }
}


text:
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib

# Look pretty...
# matplotlib.style.use('ggplot')
plt.style.use('ggplot')

#
# TODO: Load up the Seeds Dataset into a Dataframe
# It's located at 'Datasets/wheat.data'
#
file_path = "/Users/szabolcs/dev/git/DAT210x/Module3/Datasets/"
file_name = "wheat.data"

df = pd.read_csv(file_path + file_name)
print(df.shape)
print(df.head(3))

#
# TODO: Create a slice of your dataframe (call it s1)
# that only includes the 'area' and 'perimeter' features
#
s1 = df[["area", "perimeter"]]

#
# TODO: Create another slice of your dataframe (call it s2)
# that only includes the 'groove' and 'asymmetry' features
#
s2 = df[["groove", "asymmetry"]]

#
# TODO: Create a histogram plot using the first slice,
# and another histogram plot using the second slice.
# Be sure to set alpha=0.75
#
plt.figure()
s1.plot.hist(alpha=0.75)
s2.plot.hist(alpha=0.75)

# Display the graphs:
plt.show()


text:
namespace Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.Implementation
{
    using System;
    using System.IO;

    internal interface IPlatformFile
    {
        string Name { get; }

        string Extension { get; }

        long Length { get; }

        DateTimeOffset DateCreated { get; }

        bool Exists { get; }

        void Delete();

        void Rename(string newName);

        Stream Open();
    }
}


text:
module Instrument
  ( requestDuration
  , instrumentApp
  ) where

import           ClassyPrelude
import qualified Data.ByteString.Char8 as B8
import qualified Data.Text as T
import qualified Network.HTTP.Types as HTTP
import qualified Network.Wai as Wai
import qualified Prometheus as Prom
import qualified System.Clock as Clock

-- | Core information about HTTP requests:
--
-- Labels:
-- * handler: the name of the application
-- * method: the HTTP method requested
-- * status_code: the HTTP response code
--
-- Actual metric is the latency of the request.
type RequestDuration = Prom.Metric (Prom.Vector Prom.Label3 Prom.Summary)

requestDuration :: IO RequestDuration
requestDuration =
  Prom.vector ("handler", "method", "status_code") $ Prom.summary info Prom.defaultQuantiles
  where
    info =
      Prom.Info
        "http_request_duration_seconds"
        "The HTTP request latencies in seconds."

-- | Instrument a WAI app with the default WAI metrics.
instrumentApp
  :: RequestDuration -- ^ The metric to instrument
  -> Text -- ^ The label used to identify this app
  -> Wai.Application -- ^ The app to instrument
  -> Wai.Application -- ^ The instrumented app
instrumentApp metric handler app req respond = do
  start <- Clock.getTime Clock.Monotonic
  app
    req
    (\res -> do
       recordResult start (HTTP.statusCode (Wai.responseStatus res))
       respond res) `onException`
    recordResult start 500
  where
    recordResult start statusCode = do
      end <- Clock.getTime Clock.Monotonic
      let latency = fromRational . (/ 1000000000) . toRational . Clock.toNanoSecs $
            end `Clock.diffTimeSpec` start
      Prom.withLabel (T.unpack handler, method, status) (Prom.observe latency) metric
      where
        method = B8.unpack (Wai.requestMethod req)
        status = show statusCode


text:
#undef NDEBUG
#include "HTTPIntegrationBase.h"
#include "HTTPHandlers.h"
#include "utils/gsl.h"
#include "utils/IntegrationTestUtils.h"

using namespace std::literals::chrono_literals;

int main(int argc, char **argv) {
  const cmd_args args = parse_cmdline_args(argc, argv, "update");
  C2UpdateHandler handler(args.test_file);
  VerifyC2Update harness(10s);
  harness.setKeyDir(args.key_dir);
  harness.setUrl(args.url, &handler);
  handler.setC2RestResponse(harness.getC2RestUrl(), "configuration");

  const auto start = std::chrono::steady_clock::now();

  harness.run(args.test_file);

  const auto then = std::chrono::steady_clock::now();
  const auto seconds = std::chrono::duration_cast<std::chrono::seconds>(then - start).count();
  assert(handler.getCallCount() <= gsl::narrow<size_t>(seconds + 1));
  return 0;
}