text:
package cz.filipekt.jdcv.plugins.filter;

import java.io.InputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import cz.filipekt.jdcv.plugins.PluginWithPreferences;
import cz.filipekt.jdcv.prefs.LinkPrefs;
import cz.filipekt.jdcv.prefs.MembershipPrefs;
import cz.filipekt.jdcv.prefs.NodePrefs;
import cz.filipekt.jdcv.prefs.PreferencesBuilder;
import cz.filipekt.jdcv.util.Resources;

/**
 * The side panel allowing the user to filter out some of the visualization
 * elements. Only simple filters are supported - for more elaborate ones,
 * use the scripting console.
 *
 * @author Tomas Filipek <tom.filipek@seznam.cz>
 */
public class FilterPanel extends PluginWithPreferences {

	/**
	 * Short name of this plugin
	 */
	private final String pluginName = "Filter";

	/**
	 * @return Short name of this plugin
	 */
	@Override
	public String getName() {
		return pluginName;
	}

	/**
	 * @return Input stream opened on a file containing a small image representing this plugin
	 */
	@Override
	public InputStream getThumbnail() {
		return Resources.getResourceInputStream("filter.png");
	}

	/**
	 * @return The main panel of the plugin
	 * @see {@link FilterPanel#panel}
	 */
	@Override
	public Node getPanel() {
		return panel;
	}

	/**
	 * The main panel of the plugin
	 */
	private final Node panel;

	/**
	 * This is a singleton class, so uncontrolled instantiation is forbidden.
	 * Initializes the main panel.
	 */
	public FilterPanel() {
		panel = createPanel();
		initializeAttributes();
	}

	/**
	 * The graphical view of the filters that are currently in use
	 */
	private final ListView<Filter> filters = new ListView<>();

	/**
	 * Constructs the main panel of the plugin, later held in {@link FilterPanel#panel}
	 * @return The main panel of the plugin
	 */
	private Node createPanel(){
		VBox vGrid = new VBox();
		Button addButton = new Button("Add Filter");
		Button removeButton = new Button("Remove Selected");
		HBox buttons = new HBox(addButton, removeButton);
		VBox.setVgrow(buttons, Priority.NEVER);
		VBox.setVgrow(filters, Priority.ALWAYS);
		filters.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
		vGrid.getChildren().addAll(buttons, filters);
		addButton.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent arg0) {
				showCreateFilter();
			}
		});
		removeButton.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent arg0) {
				deleteSelectedFilters();
			}
		});
		return vGrid;
	}

	/**
	 * Name of the node visualization, as viewed in the "create filter" window.
	 */
	private final String nodeElementName = "Node";

	/**
	 * Name of the link visualization, as viewed in the "create filter" window.
	 */
	private final String linkElementName = "Link";

	/**
	 * Name of the person visualization, as viewed in the "create filter" window.
	 */
	private final String personElementName = "Person";

	/**
	 * Name of the ensemble membership visualization, as viewed in the "create filter" window.
	 */
	private final String ensembleElementName = "Ensemble Membership";

	/**
	 * Names of the elements of the visualization that can be filtered
	 */
	private final List<String> elementNames = Arrays.asList(
			nodeElementName, linkElementName, /* personElementName,*/ ensembleElementName
			);

	/**
	 * Maps each visualization element to the list of attributes by which we can filter
	 */
	private final Map<String,List<String>> attributesForElement = new HashMap<>();

	/**
	 * Attributes associated with nodes
	 */
	private final List<String> attributesForNode = Arrays.asList("ID", "x-coordinate", "y-coordinate");

	/**
	 * Attributes associated with links
	 */
	private final List<String> attributesForLink = Arrays.asList("ID", "From ID", "To ID");

	/**
	 * Attributes associated with persons
	 */
	private final List<String> attributesForPerson = Arrays.asList("ID");

	/**
	 * Attributes associated with ensembles
	 */
	private final List<String> attributesForEnsemble = Arrays.asList("Ensemble Name", "Coordinator ID", "Member ID");

	/**
	 * Builds and shows the "create new filter" window
	 */
	private void showCreateFilter(){
		final Stage stage = new Stage();
		GridPane pane = new GridPane();
		Scene scene = new Scene(pane);
		stage.setScene(scene);
		int row = 0;
		Label elementLabel = new Label("Element Type:");
		final ComboBox<String> elementBox = new ComboBox<>();
		elementBox.getItems().addAll(elementNames);
		pane.add(elementLabel, 0, row);
		pane.add(elementBox, 1, row);
		row += 1;
		Label attributeLabel = new Label("Attribute");
		final ComboBox<String> attributeBox = new ComboBox<>();
		elementBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {

			@Override
			public void changed(ObservableValue<? extends String> arg0,
					String oldElement, String newElement) {
				provideAttributes(newElement, attributeBox);
			}
		});
		elementBox.getSelectionModel().select(0);
		pane.add(attributeLabel, 0, row);
		pane.add(attributeBox, 1, row);
		row += 1;
		Label valueLabel = new Label("Value:");
		final TextField valueField = new TextField();
		pane.add(valueLabel, 0, row);
		pane.add(valueField, 1, row);
		row += 1;
		Button okButton = new Button("OK");
		okButton.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent arg0) {
				String selected = elementBox.getSelectionModel().getSelectedItem();
				String attribute = attributeBox.getSelectionModel().getSelectedItem();
				switch(selected){
					case nodeElementName:
						processNodeRequest(attribute, valueField.getText());
						break;
					case linkElementName:
						processLinkRequest(attribute, valueField.getText());
						break;
					case personElementName:
						break;
					case ensembleElementName:
						processEnsembleRequest(attribute, valueField.getText());
						break;
					default:
						break;
				}
				stage.close();
			}
		});
		Button cancelButton = new Button("Cancel");
		cancelButton.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent arg0) {
				stage.close();
			}
		});
		pane.setHgap(5);
		pane.setVgap(5);
		pane.add(okButton, 0, row);
		pane.add(cancelButton, 1, row);
		row += 1;
		decorateCreateFilterWindow(stage);
		stage.show();
	}

	/**
	 * Decorates the "create new filter" window
	 * @param stage The main {@link Stage} of the window
	 */
	private void decorateCreateFilterWindow(Stage stage){
		if (stage != null){
			stage.sizeToScene();
			stage.initModality(Modality.APPLICATION_MODAL);
			stage.initStyle(StageStyle.DECORATED);
			stage.setResizable(false);
			stage.setTitle("Create New Filter");
			InputStream iconStream = Resources.getResourceInputStream("filter.png");
			if (iconStream != null){
				Image icon = new Image(iconStream);
				stage.getIcons().add(icon);
			}
		}
	}

	/**
	 * Given the node attribute and its value, this method builds and applies the filter
	 * which filters out any nodes not having the specified attribute value.
	 * @param attribute Name of a node attribute, such as "x-coordinate"
	 * @param value Value of the specified attribute
	 */
	private void processNodeRequest(String attribute, final String value){
		if ((attribute != null) && (value != null)){
			PreferencesBuilder prefs = getPreferences();
			if (prefs != null){
				final Map<String,NodePrefs> nodePrefs = prefs.nodePrefs(null);
				if (nodePrefs != null){
					Filter filter = null;
					switch(attribute){
						case "ID":
							filter = new VisibilityFilter(){

								@Override
								public void initializeSelection() {
									for (String nodeID : nodePrefs.keySet()){
										if (!nodeID.equals(value)){
											NodePrefs prefs = nodePrefs.get(nodeID);
											affectedNodes.add(prefs);
										}
									}
								}

								@Override
								public String toString(){
									return "Nodes with ID equal to " + value;
								}

							};
							break;
						case "x-coordinate":
							try {
								final double xCoord = Double.parseDouble(value);
								filter = new VisibilityFilter() {

									@Override
									public void initializeSelection() {
										for (String nodeID : nodePrefs.keySet()){
											NodePrefs prefs = nodePrefs.get(nodeID);
											if (prefs.getX() != xCoord){
												affectedNodes.add(prefs);
											}
										}
									}

									@Override
									public String toString() {
										return "Nodes with x-coord equal to " + xCoord;
									}

								};
							} catch (NumberFormatException ex) {}
							break;
						case "y-coordinate":
							try {
								final double yCoord = Double.parseDouble(value);
								filter = new VisibilityFilter() {

									@Override
									public void initializeSelection() {
										for (String nodeID : nodePrefs.keySet()){
											NodePrefs prefs = nodePrefs.get(nodeID);
											if (prefs.getY() != yCoord){
												affectedNodes.add(prefs);
											}
										}
									}

									@Override
									public String toString() {
										return "Nodes with x-coord equal to " + yCoord;
									}

								};
							} catch (NumberFormatException ex) {}
							break;
						default:
							break;
					}
					if (filter != null){
						filters.getItems().add(filter);
						filter.apply();
					}
				}
			}
		}
	}

	/**
	 * Given the link attribute and its value, this method builds and applies the filter
	 * which filters out any links not having the specified attribute value.
	 * @param attribute Name of a link attribute, such as "From node"
	 * @param value Value of the specified attribute
	 */
	private void processLinkRequest(String attribute, final String value){
		if ((attribute != null) && (value != null)){
			PreferencesBuilder prefs = getPreferences();
			if (prefs != null){
				final Map<String,LinkPrefs> linkPrefs = prefs.linkPrefs(null);
				if (linkPrefs != null){
					Filter filter = null;
					switch(attribute){
						case "ID":
							filter = new VisibilityFilter() {

								@Override
								public void initializeSelection() {
									for (String linkID : linkPrefs.keySet()){
										if (!linkID.equals(value)){
											LinkPrefs prefs = linkPrefs.get(linkID);
											affectedNodes.add(prefs);
										}
									}
								}

								@Override
								public String toString() {
									return "Links with ID equal to " + value;
								}
							};
							break;
						case "From ID":
							filter = new VisibilityFilter() {

								@Override
								public String toString() {
									return "Links from node " + value;
								}

								@Override
								public void initializeSelection() {
									for (String linkID : linkPrefs.keySet()){
										LinkPrefs prefs = linkPrefs.get(linkID);
										if (!prefs.getFromNode().equals(value)){
											affectedNodes.add(prefs);
										}
									}
								}
							};
							break;
						case "To ID":
							filter = new VisibilityFilter() {

								@Override
								public String toString() {
									return "Links to node " + value;
								}

								@Override
								public void initializeSelection() {
									for (String linkID : linkPrefs.keySet()){
										LinkPrefs prefs = linkPrefs.get(linkID);
										if (!prefs.getToNode().equals(value)){
											affectedNodes.add(prefs);
										}
									}
								}
							};
							break;
						default:
							break;
					}
					if (filter != null){
						filters.getItems().add(filter);
						filter.apply();
					}
				}
			}
		}
	}

	/**
	 * Given the ensemble membership attribute and its value, this method builds and applies the
	 * filter which filters out any ensemble memberships not having the specified attribute value.
	 * @param attribute Name of an ensemble membership attribute, such as "Coordinator"
	 * @param value Value of the specified attribute
	 */
	private void processEnsembleRequest(String attribute, final String value){
		if ((attribute != null) && (value != null)){
			PreferencesBuilder prefs = getPreferences();
			if (prefs != null){
				final Set<MembershipPrefs> ensemblePrefs = prefs.membershipPrefs(null);
				if (ensemblePrefs != null){
					Filter filter = null;
					switch(attribute){
						case "Ensemble Name":
							filter = new VisibilityFilter() {

								@Override
								public String toString() {
									return "Ensembles with name " + value;
								}

								@Override
								public void initializeSelection() {
									for (MembershipPrefs prefs : ensemblePrefs){
										if (!prefs.getEnsembleName().equals(value)){
											affectedNodes.add(prefs);
										}
									}
								}
							};
							break;
						case "Coordinator ID":
							filter = new VisibilityFilter() {

								@Override
								public String toString() {
									return "Ensembles with coordinator " + value;
								}

								@Override
								public void initializeSelection() {
									for (MembershipPrefs prefs : ensemblePrefs){
										if (!prefs.getCoordinator().equals(value)){
											affectedNodes.add(prefs);
										}
									}
								}
							};
							break;
						case "Member ID":
							filter = new VisibilityFilter() {

								@Override
								public String toString() {
									return "Ensembles with member " + value;
								}

								@Override
								public void initializeSelection() {
									for (MembershipPrefs prefs : ensemblePrefs){
										if (!prefs.getMember().equals(value)){
											affectedNodes.add(prefs);
										}
									}
								}
							};
							break;
						default:
							break;
					}
					if (filter != null){
						filters.getItems().add(filter);
						filter.apply();
					}
				}
			}
		}
	}

	/**
	 * Un-applies the filters selected by the user and removes them from the filter list.
	 */
	private void deleteSelectedFilters(){
		Collection<Filter> selected = filters.getSelectionModel().getSelectedItems();
		for (Filter filter : selected){
			filter.unapply();
		}
		filters.getItems().removeAll(selected);
	}

	/**
	 * Fills the combobox with attributes corresponding to the specified visualization element.
	 * @param element Element whose attributes will be put into the combobox
	 * @param attributeBox Combobox to be filled with the attributes corresponding to the element
	 */
	private void provideAttributes(String element, ComboBox<String> attributeBox){
		if ((element != null) && (attributeBox != null)){
			List<String> attributes = attributesForElement.get(element);
			attributeBox.getItems().clear();
			if (attributes != null){
				attributeBox.getItems().addAll(attributes);
				attributeBox.getSelectionModel().select(0);
			}
		}
	}

	/**
	 * Initializer for {@link FilterPanel#attributesForElement}. It fills the map
	 * with elements mapped to their corresponding attributes.
	 */
	private void initializeAttributes(){
		attributesForElement.clear();
		for (String element : elementNames){
			switch (element){
				case nodeElementName:
					attributesForElement.put(element, attributesForNode);
					break;
				case linkElementName:
					attributesForElement.put(element, attributesForLink);
					break;
				case personElementName:
					attributesForElement.put(element, attributesForPerson);
					break;
				case ensembleElementName:
					attributesForElement.put(element, attributesForEnsemble);
					break;
			}
		}
	}

}


text:
import React, {Component} from 'react'
import style from './style.css'

class Footer extends Component {

  render() {
    return (
      <footer className={style.containerFooter}>
        <a href='http://www.cytoscape.org/' target='_blank'>
          © 2016 University of California, San Diego Trey Ideker Lab
        </a>
      </footer>
    )
  }
}

export default Footer

redpajama_set_name: RedPajamaGithub


text:
#ifndef _SCI_BASE_STATE_MACHINE_OBSERVER_H_
#define _SCI_BASE_STATE_MACHINE_OBSERVER_H_

/**
 * @file
 *
 * @brief This file contains all of the structures, constants, and methods
 *        common to all state machine observer object definitions.
 */

#ifdef __cplusplus
extern "C" {
#endif // __cplusplus

#include <dev/isci/scil/sci_base_observer.h>
#include <dev/isci/scil/sci_base_subject.h>

#if defined(SCI_LOGGING)

/**
 * @struct SCI_BASE_STATE_MACHINE_OBSERVER
 *
 * @brief The base state machine observer structure defines the fields
 *        necessary for a user that wishes to observe the behavior (i.e.
 *        state changes) of a state machine.
 */
typedef struct SCI_BASE_STATE_MACHINE_OBSERVER
{
   /**
    * The field specifies that the parent object for the base state
    * machine observer is the base observer itself.
    */
   SCI_BASE_OBSERVER_T parent;

   /**
    * This field contains the state recorded during the last state machine
    * update.
    */
   U32  subject_state;

} SCI_BASE_STATE_MACHINE_OBSERVER_T;

/**
 * @brief This method provides default behavior for a state machine observer.
 *        This method records the state of the subject (i.e. the state
 *        machine) and returns.
 *
 * @param[in]  this_observer This parameter specifes the state machine
 *             observer in which to record the state change from the subject.
 * @param[in]  the_subject This parameter evaluates to the state machine
 *             object under observation.
 *
 * @return none
 */
void sci_base_state_machine_observer_default_update(
   SCI_BASE_OBSERVER_T *this_observer,
   SCI_BASE_SUBJECT_T  *the_subject
);

/**
 * @brief This method constructs the supplied state machine observer.
 *
 * @param[in]  this_observer This parameter specifes the state machine
 *             observer to be constructed.
 *
 * @return none
 */
void sci_base_state_machine_observer_construct(
   SCI_BASE_STATE_MACHINE_OBSERVER_T *this_observer
);

#else // defined(SCI_LOGGING)

typedef U8 SCI_BASE_STATE_MACHINE_OBSERVER_T;

#define sci_base_state_machine_observer_default_update
#define sci_base_state_machine_observer_construct

#endif // defined(SCI_LOGGING)

#ifdef __cplusplus
}
#endif // __cplusplus

#endif // _SCI_BASE_STATE_MACHINE_OBSERVER_H_


text:
"""Functions copypasted from newer versions of numpy.

"""
from __future__ import division, print_function, absolute_import

import warnings
import sys
from warnings import WarningMessage
import re
from functools import wraps
import numpy as np

from scipy._lib._version import NumpyVersion

def import_nose():
    """ Import nose only when needed.
    """
    nose_is_good = True
    minimum_nose_version = (1, 0, 0)
    try:
        import nose
    except ImportError:
        nose_is_good = False
    else:
        if nose.__versioninfo__ < minimum_nose_version:
            nose_is_good = False

    if not nose_is_good:
        msg = ('Need nose >= %d.%d.%d for tests - see '
               'http://nose.readthedocs.io' %
               minimum_nose_version)
        raise ImportError(msg)

    return nose

if NumpyVersion(np.__version__) > '1.7.0.dev':
    _assert_warns = np.testing.assert_warns
else:
    def _assert_warns(warning_class, func, *args, **kw):
        r"""
        Fail unless the given callable throws the specified warning.

        This definition is copypasted from numpy 1.9.0.dev.
        The version in earlier numpy returns None.

        Parameters
        ----------
        warning_class : class
            The class defining the warning that `func` is expected to throw.
        func : callable
            The callable to test.
        *args : Arguments
            Arguments passed to `func`.
        **kwargs : Kwargs
            Keyword arguments passed to `func`.

        Returns
        -------
        The value returned by `func`.

        """
        with warnings.catch_warnings(record=True) as l:
            warnings.simplefilter('always')
            result = func(*args, **kw)
            if not len(l) > 0:
                raise AssertionError("No warning raised when calling %s"
                        % func.__name__)
            if not l[0].category is warning_class:
                raise AssertionError("First warning for %s is not a "
                        "%s( is %s)" % (func.__name__, warning_class, l[0]))
        return result

def assert_raises_regex(exception_class, expected_regexp,
                        callable_obj=None, *args, **kwargs):
    """
    Fail unless an exception of class exception_class and with message that
    matches expected_regexp is thrown by callable when invoked with arguments
    args and keyword arguments kwargs.
    Name of this function adheres to Python 3.2+ reference, but should work in
    all versions down to 2.6.
    Notes
    -----
    .. versionadded:: 1.8.0
    """
    __tracebackhide__ = True  # Hide traceback for py.test
    nose = import_nose()

    if sys.version_info.major >= 3:
        funcname = nose.tools.assert_raises_regex
    else:
        # Only present in Python 2.7, missing from unittest in 2.6
            funcname = nose.tools.assert_raises_regexp

    return funcname(exception_class, expected_regexp, callable_obj,
                    *args, **kwargs)

if NumpyVersion(np.__version__) >= '1.10.0':
    from numpy import broadcast_to
else:
    # Definition of `broadcast_to` from numpy 1.10.0.

    def _maybe_view_as_subclass(original_array, new_array):
        if type(original_array) is not type(new_array):
            # if input was an ndarray subclass and subclasses were OK,
            # then view the result as that subclass.
            new_array = new_array.view(type=type(original_array))
            # Since we have done something akin to a view from original_array, we
            # should let the subclass finalize (if it has it implemented, i.e., is
            # not None).
            if new_array.__array_finalize__:
                new_array.__array_finalize__(original_array)
        return new_array

    def _broadcast_to(array, shape, subok, readonly):
        shape = tuple(shape) if np.iterable(shape) else (shape,)
        array = np.array(array, copy=False, subok=subok)
        if not shape and array.shape:
            raise ValueError('cannot broadcast a non-scalar to a scalar array')
        if any(size < 0 for size in shape):
            raise ValueError('all elements of broadcast shape must be non-'
                             'negative')
        broadcast = np.nditer(
            (array,), flags=['multi_index', 'refs_ok', 'zerosize_ok'],
            op_flags=['readonly'], itershape=shape, order='C').itviews[0]
        result = _maybe_view_as_subclass(array, broadcast)
        if not readonly and array.flags.writeable:
            result.flags.writeable = True
        return result

    def broadcast_to(array, shape, subok=False):
        return _broadcast_to(array, shape, subok=subok, readonly=True)

if NumpyVersion(np.__version__) >= '1.9.0':
    from numpy import unique
else:
    # the return_counts keyword was added in 1.9.0
    def unique(ar, return_index=False, return_inverse=False, return_counts=False):
        """
        Find the unique elements of an array.

        Returns the sorted unique elements of an array. There are three optional
        outputs in addition to the unique elements: the indices of the input array
        that give the unique values, the indices of the unique array that
        reconstruct the input array, and the number of times each unique value
        comes up in the input array.

        Parameters
        ----------
        ar : array_like
            Input array. This will be flattened if it is not already 1-D.
        return_index : bool, optional
            If True, also return the indices of `ar` that result in the unique
            array.
        return_inverse : bool, optional
            If True, also return the indices of the unique array that can be used
            to reconstruct `ar`.
        return_counts : bool, optional
            If True, also return the number of times each unique value comes up
            in `ar`.

            .. versionadded:: 1.9.0

        Returns
        -------
        unique : ndarray
            The sorted unique values.
        unique_indices : ndarray, optional
            The indices of the first occurrences of the unique values in the
            (flattened) original array. Only provided if `return_index` is True.
        unique_inverse : ndarray, optional
            The indices to reconstruct the (flattened) original array from the
            unique array. Only provided if `return_inverse` is True.
        unique_counts : ndarray, optional
            The number of times each of the unique values comes up in the
            original array. Only provided if `return_counts` is True.

            .. versionadded:: 1.9.0

        Notes
        -----
        Taken over from numpy 1.12.0-dev (c8408bf9c).  Omitted examples,
        see numpy documentation for those.

        """
        ar = np.asanyarray(ar).flatten()

        optional_indices = return_index or return_inverse
        optional_returns = optional_indices or return_counts

        if ar.size == 0:
            if not optional_returns:
                ret = ar
            else:
                ret = (ar,)
                if return_index:
                    ret += (np.empty(0, np.bool),)
                if return_inverse:
                    ret += (np.empty(0, np.bool),)
                if return_counts:
                    ret += (np.empty(0, np.intp),)
            return ret

        if optional_indices:
            perm = ar.argsort(kind='mergesort' if return_index else 'quicksort')
            aux = ar[perm]
        else:
            ar.sort()
            aux = ar
        flag = np.concatenate(([True], aux[1:] != aux[:-1]))

        if not optional_returns:
            ret = aux[flag]
        else:
            ret = (aux[flag],)
            if return_index:
                ret += (perm[flag],)
            if return_inverse:
                iflag = np.cumsum(flag) - 1
                inv_idx = np.empty(ar.shape, dtype=np.intp)
                inv_idx[perm] = iflag
                ret += (inv_idx,)
            if return_counts:
                idx = np.concatenate(np.nonzero(flag) + ([ar.size],))
                ret += (np.diff(idx),)
        return ret

if NumpyVersion(np.__version__) > '1.12.0.dev':
    polyvalfromroots = np.polynomial.polynomial.polyvalfromroots
else:
    def polyvalfromroots(x, r, tensor=True):
        """
        Evaluate a polynomial specified by its roots at points x.

        This function is copypasted from numpy 1.12.0.dev.

        If `r` is of length `N`, this function returns the value

        .. math:: p(x) = \prod_{n=1}^{N} (x - r_n)

        The parameter `x` is converted to an array only if it is a tuple or a
        list, otherwise it is treated as a scalar. In either case, either `x`
        or its elements must support multiplication and addition both with
        themselves and with the elements of `r`.

        If `r` is a 1-D array, then `p(x)` will have the same shape as `x`.  If
        `r` is multidimensional, then the shape of the result depends on the
        value of `tensor`. If `tensor is ``True`` the shape will be r.shape[1:]
        + x.shape; that is, each polynomial is evaluated at every value of `x`.
        If `tensor` is ``False``, the shape will be r.shape[1:]; that is, each
        polynomial is evaluated only for the corresponding broadcast value of
        `x`. Note that scalars have shape (,).

        Parameters
        ----------
        x : array_like, compatible object
            If `x` is a list or tuple, it is converted to an ndarray, otherwise
            it is left unchanged and treated as a scalar. In either case, `x`
            or its elements must support addition and multiplication with with
            themselves and with the elements of `r`.
        r : array_like
            Array of roots. If `r` is multidimensional the first index is the
            root index, while the remaining indices enumerate multiple
            polynomials. For instance, in the two dimensional case the roots of
            each polynomial may be thought of as stored in the columns of `r`.
        tensor : boolean, optional
            If True, the shape of the roots array is extended with ones on the
            right, one for each dimension of `x`. Scalars have dimension 0 for
            this action. The result is that every column of coefficients in `r`
            is evaluated for every element of `x`. If False, `x` is broadcast
            over the columns of `r` for the evaluation.  This keyword is useful
            when `r` is multidimensional. The default value is True.

        Returns
        -------
        values : ndarray, compatible object
            The shape of the returned array is described above.

        See Also
        --------
        polyroots, polyfromroots, polyval

        Examples
        --------
        >>> from numpy.polynomial.polynomial import polyvalfromroots
        >>> polyvalfromroots(1, [1,2,3])
        0.0
        >>> a = np.arange(4).reshape(2,2)
        >>> a
        array([[0, 1],
               [2, 3]])
        >>> polyvalfromroots(a, [-1, 0, 1])
        array([[ -0.,   0.],
               [  6.,  24.]])
        >>> r = np.arange(-2, 2).reshape(2,2) # multidimensional coefficients
        >>> r # each column of r defines one polynomial
        array([[-2, -1],
               [ 0,  1]])
        >>> b = [-2, 1]
        >>> polyvalfromroots(b, r, tensor=True)
        array([[-0.,  3.],
               [ 3., 0.]])
        >>> polyvalfromroots(b, r, tensor=False)
        array([-0.,  0.])
        """
        r = np.array(r, ndmin=1, copy=0)
        if r.dtype.char in '?bBhHiIlLqQpP':
            r = r.astype(np.double)
        if isinstance(x, (tuple, list)):
            x = np.asarray(x)
        if isinstance(x, np.ndarray):
            if tensor:
                r = r.reshape(r.shape + (1,)*x.ndim)
            elif x.ndim >= r.ndim:
                raise ValueError("x.ndim must be < r.ndim when tensor == "
                                 "False")
        return np.prod(x - r, axis=0)

try:
    from numpy.testing import suppress_warnings
except ImportError:
    class suppress_warnings(object):
        """
        Context manager and decorator doing much the same as
        ``warnings.catch_warnings``.

        However, it also provides a filter mechanism to work around
        http://bugs.python.org/issue4180.

        This bug causes Python before 3.4 to not reliably show warnings again
        after they have been ignored once (even within catch_warnings). It
        means that no "ignore" filter can be used easily, since following
        tests might need to see the warning. Additionally it allows easier
        specificity for testing warnings and can be nested.

        Parameters
        ----------
        forwarding_rule : str, optional
            One of "always", "once", "module", or "location". Analogous to
            the usual warnings module filter mode, it is useful to reduce
            noise mostly on the outmost level. Unsuppressed and unrecorded
            warnings will be forwarded based on this rule. Defaults to "always".
            "location" is equivalent to the warnings "default", match by exact
            location the warning warning originated from.

        Notes
        -----
        Filters added inside the context manager will be discarded again
        when leaving it. Upon entering all filters defined outside a
        context will be applied automatically.

        When a recording filter is added, matching warnings are stored in the
        ``log`` attribute as well as in the list returned by ``record``.

        If filters are added and the ``module`` keyword is given, the
        warning registry of this module will additionally be cleared when
        applying it, entering the context, or exiting it. This could cause
        warnings to appear a second time after leaving the context if they
        were configured to be printed once (default) and were already
        printed before the context was entered.

        Nesting this context manager will work as expected when the
        forwarding rule is "always" (default). Unfiltered and unrecorded
        warnings will be passed out and be matched by the outer level.
        On the outmost level they will be printed (or caught by another
        warnings context). The forwarding rule argument can modify this
        behaviour.

        Like ``catch_warnings`` this context manager is not threadsafe.

        Examples
        --------
        >>> with suppress_warnings() as sup:
        ...     sup.filter(DeprecationWarning, "Some text")
        ...     sup.filter(module=np.ma.core)
        ...     log = sup.record(FutureWarning, "Does this occur?")
        ...     command_giving_warnings()
        ...     # The FutureWarning was given once, the filtered warnings were
        ...     # ignored. All other warnings abide outside settings (may be
        ...     # printed/error)
        ...     assert_(len(log) == 1)
        ...     assert_(len(sup.log) == 1)  # also stored in log attribute

        Or as a decorator:

        >>> sup = suppress_warnings()
        >>> sup.filter(module=np.ma.core)  # module must match exact
        >>> @sup
        >>> def some_function():
        ...     # do something which causes a warning in np.ma.core
        ...     pass
        """
        def __init__(self, forwarding_rule="always"):
            self._entered = False

            # Suppressions are either instance or defined inside one with block:
            self._suppressions = []

            if forwarding_rule not in {"always", "module", "once", "location"}:
                raise ValueError("unsupported forwarding rule.")
            self._forwarding_rule = forwarding_rule

        def _clear_registries(self):
            if hasattr(warnings, "_filters_mutated"):
                # clearing the registry should not be necessary on new pythons,
                # instead the filters should be mutated.
                warnings._filters_mutated()
                return
            # Simply clear the registry, this should normally be harmless,
            # note that on new pythons it would be invalidated anyway.
            for module in self._tmp_modules:
                if hasattr(module, "__warningregistry__"):
                    module.__warningregistry__.clear()

        def _filter(self, category=Warning, message="", module=None, record=False):
            if record:
                record = []  # The log where to store warnings
            else:
                record = None
            if self._entered:
                if module is None:
                    warnings.filterwarnings(
                        "always", category=category, message=message)
                else:
                    module_regex = module.__name__.replace('.', r'\.') + '$'
                    warnings.filterwarnings(
                        "always", category=category, message=message,
                        module=module_regex)
                    self._tmp_modules.add(module)
                    self._clear_registries()

                self._tmp_suppressions.append(
                    (category, message, re.compile(message, re.I), module, record))
            else:
                self._suppressions.append(
                    (category, message, re.compile(message, re.I), module, record))

            return record

        def filter(self, category=Warning, message="", module=None):
            """
            Add a new suppressing filter or apply it if the state is entered.

            Parameters
            ----------
            category : class, optional
                Warning class to filter
            message : string, optional
                Regular expression matching the warning message.
            module : module, optional
                Module to filter for. Note that the module (and its file)
                must match exactly and cannot be a submodule. This may make
                it unreliable for external modules.

            Notes
            -----
            When added within a context, filters are only added inside
            the context and will be forgotten when the context is exited.
            """
            self._filter(category=category, message=message, module=module,
                         record=False)

        def record(self, category=Warning, message="", module=None):
            """
            Append a new recording filter or apply it if the state is entered.

            All warnings matching will be appended to the ``log`` attribute.

            Parameters
            ----------
            category : class, optional
                Warning class to filter
            message : string, optional
                Regular expression matching the warning message.
            module : module, optional
                Module to filter for. Note that the module (and its file)
                must match exactly and cannot be a submodule. This may make
                it unreliable for external modules.

            Returns
            -------
            log : list
                A list which will be filled with all matched warnings.

            Notes
            -----
            When added within a context, filters are only added inside
            the context and will be forgotten when the context is exited.
            """
            return self._filter(category=category, message=message, module=module,
                                record=True)

        def __enter__(self):
            if self._entered:
                raise RuntimeError("cannot enter suppress_warnings twice.")

            self._orig_show = warnings.showwarning
            self._filters = warnings.filters
            warnings.filters = self._filters[:]

            self._entered = True
            self._tmp_suppressions = []
            self._tmp_modules = set()
            self._forwarded = set()

            self.log = []  # reset global log (no need to keep same list)

            for cat, mess, _, mod, log in self._suppressions:
                if log is not None:
                    del log[:]  # clear the log
                if mod is None:
                    warnings.filterwarnings(
                        "always", category=cat, message=mess)
                else:
                    module_regex = mod.__name__.replace('.', r'\.') + '$'
                    warnings.filterwarnings(
                        "always", category=cat, message=mess,
                        module=module_regex)
                    self._tmp_modules.add(mod)
            warnings.showwarning = self._showwarning
            self._clear_registries()

            return self

        def __exit__(self, *exc_info):
            warnings.showwarning = self._orig_show
            warnings.filters = self._filters
            self._clear_registries()
            self._entered = False
            del self._orig_show
            del self._filters

        def _showwarning(self, message, category, filename, lineno,
                         *args, **kwargs):
            use_warnmsg = kwargs.pop("use_warnmsg", None)
            for cat, _, pattern, mod, rec in (
                    self._suppressions + self._tmp_suppressions)[::-1]:
                if (issubclass(category, cat) and
                        pattern.match(message.args[0]) is not None):
                    if mod is None:
                        # Message and category match, either recorded or ignored
                        if rec is not None:
                            msg = WarningMessage(message, category, filename,
                                                 lineno, **kwargs)
                            self.log.append(msg)
                            rec.append(msg)
                        return
                    # Use startswith, because warnings strips the c or o from
                    # .pyc/.pyo files.
                    elif mod.__file__.startswith(filename):
                        # The message and module (filename) match
                        if rec is not None:
                            msg = WarningMessage(message, category, filename,
                                                 lineno, **kwargs)
                            self.log.append(msg)
                            rec.append(msg)
                        return

            # There is no filter in place, so pass to the outside handler
            # unless we should only pass it once
            if self._forwarding_rule == "always":
                if use_warnmsg is None:
                    self._orig_show(message, category, filename, lineno,
                                    *args, **kwargs)
                else:
                    self._orig_showmsg(use_warnmsg)
                return

            if self._forwarding_rule == "once":
                signature = (message.args, category)
            elif self._forwarding_rule == "module":
                signature = (message.args, category, filename)
            elif self._forwarding_rule == "location":
                signature = (message.args, category, filename, lineno)

            if signature in self._forwarded:
                return
            self._forwarded.add(signature)
            if use_warnmsg is None:
                self._orig_show(message, category, filename, lineno, *args,
                                **kwargs)
            else:
                self._orig_showmsg(use_warnmsg)

        def __call__(self, func):
            """
            Function decorator to apply certain suppressions to a whole
            function.
            """
            @wraps(func)
            def new_func(*args, **kwargs):
                with self:
                    return func(*args, **kwargs)

            return new_func


text:
var StripeNode = Npm.require('stripe');
var util = Npm.require('util');
var stripeClientConfig = __meteor_runtime_config__.stripe = {};
var Future = Npm.require('fibers/future');

StripeKonnect = function(namespace) {
  this._namespace = namespace;
  this.api = null;
  this.options = null;
};

StripeKonnect.prototype.configure = function(options) {
  this.api = new StripeNode();
  this.api.setApiKey(options.apiKey);
  this.options = options;

  this._setOnClient('appName', options.appName);
  this._setOnClient('appLogo', options.appLogo);
  this._setOnClient('publishableKey', options.publishableKey);
  this._syncWrapMethods();
};

StripeKonnect.prototype._setOnClient = function(key, value) {
  if(!stripeClientConfig[this._namespace]) {
    stripeClientConfig[this._namespace] = {};
  }
  stripeClientConfig[this._namespace][key] = value;
};

StripeKonnect.prototype._syncWrapMethods = function () {
  var self = this;

  _.each(StripeResources, function (methods, resource) {
    self[resource] = {};
    _.each(methods, function (name) {
      var context = self.api[resource];
      var method = self.api[resource][name];
      self[resource][name] = function() {
        var args = _.toArray(arguments);
        var f = new Future();

        args.push(function(err, res) {
          if(err) {
            // stripe uses some custom error type
            // and it's doesn't play well with
            // Meteor's error reporting
            // and that's why we are using this
            var error = new Error(err.message);
            error.raw = err.raw;
            f.throw(error);
          } else {
            f.return(res);
          }
        });

        method.apply(context, args);
        return f.wait();
      };
    });
  });
}


text:
shared_examples 'a notification center' do
  it 'receives notification after subscribing' do
    res = false
    subject.on :ping_received, :test do
      res = true
    end

    subject.post(:ping_received).sync
    expect(res).to be(true)
  end

  it 'does not receive notification after unsubscribing' do
    res = false
    subject.on :ping_received, :test do
      res = true
    end

    subject.remove :ping_received, :test

    subject.post(:ping_received).sync
    expect(res).to be(false)
  end
end

describe Nanoc::Core::NotificationCenter do
  describe 'class' do
    subject { described_class }

    it_behaves_like 'a notification center'
  end

  describe 'instance' do
    subject { described_class.instance }

    it_behaves_like 'a notification center'
  end
end


text:
<Javascript name='JS-Basic' timeLimit='1200' >
  <ResourceURL>jsc://basic-script.js</ResourceURL>
</Javascript>


text:
package ar.com.larreta.stepper.impl;

import java.io.Serializable;

import org.springframework.stereotype.Component;

import ar.com.larreta.mystic.exceptions.PersistenceException;
import ar.com.larreta.mystic.query.Select;
import ar.com.larreta.stepper.LoadBusiness;
import ar.com.larreta.stepper.exceptions.BusinessException;
import ar.com.larreta.stepper.messages.Body;

@Component(FirstResultBusinessListener.BUSINESS_LISTENER_NAME)
public class FirstResultBusinessListener extends StepImpl {

	public static final String FIRST_RESULT = "firstResult";
	public static final String BUSINESS_LISTENER_NAME = "LoadArgsFirstResultBusinessListener";

	@Override
	public Serializable execute(Serializable source, Serializable target, Object... args) throws BusinessException, PersistenceException{
		LoadBusiness loadBusiness = (LoadBusiness) source;
		Body loadBody = (Body) args[0];
		Select select = loadBusiness.getSelect();
		if ((loadBody!=null) && (select!=null)){
			Integer firstResult = (Integer) beanUtils.read(loadBody, FIRST_RESULT);
			if (firstResult!=null){
				select.setFirstResult(firstResult);
			}
		}
		return null;
	}

}


text: Java Like HashMaps for PHP


text:
using System.Runtime.InteropServices;
#if NUNITY
using Vector3 = org.critterai.Vector3;
#else
using Vector3 = UnityEngine.Vector3;
#endif

namespace org.critterai.nav
{
    /// <summary>
    /// Provides high level information related to a <see cref="NavmeshTile"/> object.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    public struct NavmeshTileHeader
    {
        /// <summary>
        /// The tile magic number. (Undocumented.)
        /// </summary>
        public int magic;

        /// <summary>
        /// The tile version. (Undocumented.)
        /// </summary>
        public int version;

        /// <summary>
        /// The x-index of the tile within the tile grid. (x, z)
        /// </summary>
        public int tileX;

        /// <summary>
        /// The z-index of the tile within the tile grid. (x, z)
        /// </summary>
        public int tileZ;

        /// <summary>
        /// The layer of the tile.
        /// </summary>
        /// <remarks>
        /// Layering occurs on the y-axis. (Height)
        /// </remarks>
        public int layer;

        /// <summary>
        /// The user-defined id of the tile.
        /// </summary>
        public uint userId;

        /// <summary>
        /// The number of polygons in the tile.
        /// </summary>
        public int polyCount;

        /// <summary>
        /// The number of polygon vertices in the tile.
        /// </summary>
        public int vertCount;

        /// <summary>
        /// The number of links allocated.
        /// </summary>
        public int maxLinkCount;

        /// <summary>
        /// The number of sub-meshes in the detail mesh.
        /// </summary>
        public int detailMeshCount;

        /// <summary>
        /// The number of unique vertices in the detail mesh. (In addition to the polygon vertices.)
        /// </summary>
        public int detailVertCount;

        /// <summary>
        /// The number of triangles in the detail mesh.
        /// </summary>
        public int detailTriCount;

        /// <summary>
        /// The number of bounding volume nodes. (Zero if bounding volumes are disabled.)
        /// </summary>
        public int bvNodeCount;

        /// <summary>
        /// The number of off-mesh connections.
        /// </summary>
        public int connCount;

        /// <summary>
        /// The index of the first polygon which is an off-mesh connection.
        /// </summary>
        public int connBase;

        /// <summary>
        /// The minimum floor to 'ceiling' height that will still  \allow the floor area to be
        /// considered traversable.
        /// </summary>
        public float walkableHeight;

        /// <summary>
        /// The amount the polygon walls have been eroded away from
        /// obstructions.
        /// </summary>
        public float walkableRadius;

        /// <summary>
        /// The maximum ledge height that is considered to still be
        /// traversable.
        /// </summary>
        public float walkableStep;

        /// <summary>
        /// The minimum bounds of the tile's AABB.
        /// </summary>
        public Vector3 boundsMin;

        /// <summary>
        /// The maximum bounds of the tile's AABB.
        /// </summary>
        public Vector3 boundsMax;

        /// <summary>
        /// The bounding volumn quantization factor. (For converting from world to bounding volumn
        /// coordinates.)
        /// </summary>
        public float bvQuantFactor;

        /// <summary>
        /// Privides human readable text for the header. (Multi-line.)
        /// </summary>
        /// <returns>Text describing the header.</returns>
        public override string ToString()
        {
            return string.Format("Tile: X: {2}, Z: {3}, Layer: {4}\n"
                + "Version: {1}, UserId: {5}\n"
                + "Polys: {6}, Verts: {7}\n"
                + "Detail: Meshes: {9}, Tris: {11}, Verts: {10}\n"
                + "Conns: {13}, ConnBase: {14}\n"
                + "Walkable: Height: {15}, Radius: {16}, Step: {17}\n"
                + "Bounds: Min: {18}, Max: {19}\n"
                + "MaxLinks: {8}, BVQuantFactor: {20}, BVNodes: {12}\n"
                + "Magic: {0}\n"
                , magic, version
                , tileX, tileZ, layer
                , userId
                , polyCount, vertCount
                , maxLinkCount
                , detailMeshCount
                , detailVertCount
                , detailTriCount
                , bvNodeCount
                , connCount, connBase
                , walkableHeight
                , walkableRadius
                , walkableStep
                , Vector3Util.ToString(boundsMin)
                , Vector3Util.ToString(boundsMax)
                , bvQuantFactor);
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace LizardsAndPumpkins\DataPool\SearchEngine\SearchDocument;

interface SearchDocumentBuilder
{
    /**
     * @param mixed $projectionSourceDataData
     * @return SearchDocument
     */
    public function aggregate($projectionSourceDataData) : SearchDocument;
}


text:
import scala.language.dynamics
object Test extends App {
  object stubUpdate {
    def update(as: Any*) = println(".update"+as.toList.mkString("(",", ", ")"))
  }

  object stub {
    def apply = {println(".apply"); stubUpdate}
    def apply(as: Any*) = println(".apply"+as.toList.mkString("(",", ", ")"))
    def update(as: Any*) = println(".update"+as.toList.mkString("(",", ", ")"))
  }
  class MyDynamic extends Dynamic {
    def applyDynamic[T](n: String)(as: Any*) = {println("qual.applyDynamic("+ n +")"+ as.toList.mkString("(",", ", ")")); stub}
    def applyDynamicNamed[T](n: String)(as: (String, Any)*) = {println("qual.applyDynamicNamed("+ n +")"+ as.toList.mkString("(",", ", ")")); stub}
    def selectDynamic[T](n: String) = {println("qual.selectDynamic("+ n +")"); stub}
    def updateDynamic(n: String)(x: Any): Unit = {println("qual.updateDynamic("+ n +")("+ x +")")}
  }
  val qual = new MyDynamic
  val expr = "expr"
  val a = "a"
  val a2 = "a2"
  type T = String

  // If qual.sel is followed by a potential type argument list [Ts] and an argument list (arg1, …, argn) where none of the arguments argi are named:
  //  qual.applyDynamic("sel")(arg1, …, argn)
  qual.sel()
  qual.sel(a)
  // qual.sel(a, a2*) -- should not accept varargs?
  qual.sel(a)(a2)
  qual.sel[T](a)
  qual.sel[T](a)(a2)

  // If qual.sel is followed by a potential type argument list [Ts]
  // and a non-empty named argument list (x1 = arg1, …, xn = argn) where some name prefixes xi = might be missing:
  //  qual.applyDynamicNamed("sel")(xs1 -> arg1, …, xsn -> argn)
  qual.sel(arg = a)
  qual.sel[T](arg = a)
  qual.sel(a, arg2 = "a2")
  // qual.sel(a)(a2, arg2 = "a2")
  // qual.sel[T](a)(a2, arg2 = "a2")
  // qual.sel(arg = a, a2*)
  // qual.sel(arg, arg2 = "a2", a2*)

  // If qual.sel appears immediately on the left-hand side of an assigment
  // qual.updateDynamic("sel")(expr)
  qual.sel = expr

  // If qual.sel, possibly applied to type arguments, but is
  // not applied to explicit value arguments,
  // nor immediately followed by an assignment operator:
  // qual.selectDynamic[Ts]("sel")
  qual.sel
  qual.sel[T]

  qual.sel(1) = expr // parser turns this into qual.sel.update(1, expr)
  qual.sel() = expr  // parser turns this into qual.sel.update(expr)
  qual.sel.apply(1)
  qual.sel.apply(1) = 1

  qual.apply(a)
  qual.apply[String](a)
  qual(a)
  qual[String](a)
  qual[T](arg = a)
  qual(a, arg2 = "a2")
  qual(a) = a2
}


text:
<?php

/** @phpstub */
class OAuthProvider
{
    /**
     * Constructs a new OAuthProvider object
     *
     * @param array $params_array
     */
    public function __construct($params_array = array())
    {
    }

    /**
     * Add required parameters
     *
     * @param string $req_params
     *
     * @return bool
     */
    public function addRequiredParameter($req_params)
    {
    }

    /**
     * Calls the timestampNonceHandler callback
     *
     * @return void
     */
    public function callTimestampNonceHandler()
    {
    }

    /**
     * Calls the consumerNonceHandler callback
     *
     * @return void
     */
    public function callconsumerHandler()
    {
    }

    /**
     * Calls the tokenNonceHandler callback
     *
     * @return void
     */
    public function calltokenHandler()
    {
    }

    /**
     * Check an oauth request
     *
     * @param string $uri
     * @param string $method
     *
     * @return void
     */
    public function checkOAuthRequest($uri = NULL, $method = NULL)
    {
    }

    /**
     * Set the consumerHandler handler callback
     *
     * @param callable $callback_function
     *
     * @return void
     */
    public function consumerHandler($callback_function)
    {
    }

    /**
     * Generate a random token
     *
     * @param int $size
     * @param bool $strong
     *
     * @return string The generated token, as a ``string`` of bytes.
     */
    public function generateToken($size, $strong = false)
    {
    }

    /**
     * is2LeggedEndpoint
     *
     * @param mixed $params_array
     *
     * @return void An ``OAuthProvider`` .
     */
    public function is2LeggedEndpoint($params_array)
    {
    }

    /**
     * Sets isRequestTokenEndpoint
     *
     * @param bool $will_issue_request_token
     *
     * @return void
     */
    public function isRequestTokenEndpoint($will_issue_request_token)
    {
    }

    /**
     * Remove a required parameter
     *
     * @param string $req_params
     *
     * @return bool
     */
    public function removeRequiredParameter($req_params)
    {
    }

    /**
     * Report a problem
     *
     * @param string $oauthexception
     * @param bool $send_headers
     *
     * @return string
     */
    public function reportProblem($oauthexception, $send_headers = true)
    {
    }

    /**
     * Set a parameter
     *
     * @param string $param_key
     * @param mixed $param_val
     *
     * @return bool
     */
    public function setParam($param_key, $param_val = NULL)
    {
    }

    /**
     * Set request token path
     *
     * @param string $path
     *
     * @return bool true
     */
    public function setRequestTokenPath($path)
    {
    }

    /**
     * Set the timestampNonceHandler handler callback
     *
     * @param callable $callback_function
     *
     * @return void
     */
    public function timestampNonceHandler($callback_function)
    {
    }

    /**
     * Set the tokenHandler handler callback
     *
     * @param callable $callback_function
     *
     * @return void
     */
    public function tokenHandler($callback_function)
    {
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/cards_content_layout"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <GridView
        android:id="@+id/cards_grid_view"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:numColumns="2"
        android:verticalSpacing="10dp"
        android:horizontalSpacing="10dp"
        android:stretchMode="columnWidth">
    </GridView>

    <ImageView
        android:id="@+id/add_new_card"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/ic_action_new_dark"
        android:layout_margin="10dp"
        android:onClick="startAddBarcodeActivity" />
</LinearLayout>


text:
import {inject} from 'aurelia-framework';

import {I18N} from 'aurelia-i18n';
import {AuthService} from 'aurelia-auth';

@inject(I18N, AuthService)
export class Welcome {
  constructor(i18n, authService) {
    this.i18n = i18n;
    this.authService = authService;
    this.user = {};

    this.message = this.i18n.tr('welcome_message');

    if (this.authService.isAuthenticated()) {
      let token = JSON.parse(window.localStorage.token_data);  // TODO: Don't hardcode me
      this.innerMessage = this.i18n.tr('signed_in_message');
      this.user = token.user;
    } else {
      this.innerMessage = this.i18n.tr('sign_in_message');
      this.user.username = 'Anonymous';
    }
  }

  get isAuthenticated() {
    return this.authService.isAuthenticated();
  }
}


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

package net.adoptopenjdk.bumblebench.examples;

import net.adoptopenjdk.bumblebench.core.MicroBench;
import sarong.TangleRNG;

/**
 * TangleBench score: 1201761280.000000 (1.202G 2090.7%)
 *         uncertainty:   0.2%
 *

 * OpenJ9 OpenJDK 13 on linux:
 *

 * TangleBench score: 3837962240.000000 (3.838G 2206.8%)
 *         uncertainty:   1.3%
 */
public final class TangleBench extends MicroBench {

	protected long doBatch(long numIterations) throws InterruptedException {
		TangleRNG rng = new TangleRNG(0x1234L, 5678L);
		long sum = 0L;
		for (long i = 0; i < numIterations; i++)
			sum += rng.nextLong();
		return numIterations;
	}
}


text:
from typing import Callable, Iterable, List, Optional, Sequence, Union

from prompt_toolkit.application.current import get_app
from prompt_toolkit.filters import Condition
from prompt_toolkit.formatted_text.base import OneStyleAndTextTuple, StyleAndTextTuples
from prompt_toolkit.key_binding.key_bindings import KeyBindings, KeyBindingsBase
from prompt_toolkit.key_binding.key_processor import KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.containers import (
    AnyContainer,
    ConditionalContainer,
    Container,
    Float,
    FloatContainer,
    HSplit,
    Window,
)
from prompt_toolkit.layout.controls import FormattedTextControl
from prompt_toolkit.mouse_events import MouseEvent, MouseEventType
from prompt_toolkit.utils import get_cwidth
from prompt_toolkit.widgets import Shadow

from .base import Border

__all__ = [
    "MenuContainer",
    "MenuItem",
]

E = KeyPressEvent

class MenuContainer:
    """
    :param floats: List of extra Float objects to display.
    :param menu_items: List of `MenuItem` objects.
    """

    def __init__(
        self,
        body: AnyContainer,
        menu_items: List["MenuItem"],
        floats: Optional[List[Float]] = None,
        key_bindings: Optional[KeyBindingsBase] = None,
    ) -> None:

        self.body = body
        self.menu_items = menu_items
        self.selected_menu = [0]

        # Key bindings.
        kb = KeyBindings()

        @Condition
        def in_main_menu() -> bool:
            return len(self.selected_menu) == 1

        @Condition
        def in_sub_menu() -> bool:
            return len(self.selected_menu) > 1

        # Navigation through the main menu.

        @kb.add("left", filter=in_main_menu)
        def _left(event: E) -> None:
            self.selected_menu[0] = max(0, self.selected_menu[0] - 1)

        @kb.add("right", filter=in_main_menu)
        def _right(event: E) -> None:
            self.selected_menu[0] = min(
                len(self.menu_items) - 1, self.selected_menu[0] + 1
            )

        @kb.add("down", filter=in_main_menu)
        def _down(event: E) -> None:
            self.selected_menu.append(0)

        @kb.add("c-c", filter=in_main_menu)
        @kb.add("c-g", filter=in_main_menu)
        def _cancel(event: E) -> None:
            " Leave menu. "
            event.app.layout.focus_last()

        # Sub menu navigation.

        @kb.add("left", filter=in_sub_menu)
        @kb.add("c-g", filter=in_sub_menu)
        @kb.add("c-c", filter=in_sub_menu)
        def _back(event: E) -> None:
            " Go back to parent menu. "
            if len(self.selected_menu) > 1:
                self.selected_menu.pop()

        @kb.add("right", filter=in_sub_menu)
        def _submenu(event: E) -> None:
            " go into sub menu. "
            if self._get_menu(len(self.selected_menu) - 1).children:
                self.selected_menu.append(0)

            # If This item does not have a sub menu. Go up in the parent menu.
            elif (
                len(self.selected_menu) == 2
                and self.selected_menu[0] < len(self.menu_items) - 1
            ):
                self.selected_menu = [
                    min(len(self.menu_items) - 1, self.selected_menu[0] + 1)
                ]
                if self.menu_items[self.selected_menu[0]].children:
                    self.selected_menu.append(0)

        @kb.add("up", filter=in_sub_menu)
        def _up_in_submenu(event: E) -> None:
            " Select previous (enabled) menu item or return to main menu. "
            # Look for previous enabled items in this sub menu.
            menu = self._get_menu(len(self.selected_menu) - 2)
            index = self.selected_menu[-1]

            previous_indexes = [
                i
                for i, item in enumerate(menu.children)
                if i < index and not item.disabled
            ]

            if previous_indexes:
                self.selected_menu[-1] = previous_indexes[-1]
            elif len(self.selected_menu) == 2:
                # Return to main menu.
                self.selected_menu.pop()

        @kb.add("down", filter=in_sub_menu)
        def _down_in_submenu(event: E) -> None:
            " Select next (enabled) menu item. "
            menu = self._get_menu(len(self.selected_menu) - 2)
            index = self.selected_menu[-1]

            next_indexes = [
                i
                for i, item in enumerate(menu.children)
                if i > index and not item.disabled
            ]

            if next_indexes:
                self.selected_menu[-1] = next_indexes[0]

        @kb.add("enter")
        def _click(event: E) -> None:
            " Click the selected menu item. "
            item = self._get_menu(len(self.selected_menu) - 1)
            if item.handler:
                event.app.layout.focus_last()
                item.handler()

        # Controls.
        self.control = FormattedTextControl(
            self._get_menu_fragments, key_bindings=kb, focusable=True, show_cursor=False
        )

        self.window = Window(height=1, content=self.control, style="class:menu-bar")

        submenu = self._submenu(0)
        submenu2 = self._submenu(1)
        submenu3 = self._submenu(2)

        @Condition
        def has_focus() -> bool:
            return get_app().layout.current_window == self.window

        self.container = FloatContainer(
            content=HSplit(
                [
                    # The titlebar.
                    self.window,
                    # The 'body', like defined above.
                    body,
                ]
            ),
            floats=[
                Float(
                    xcursor=True,
                    ycursor=True,
                    content=ConditionalContainer(
                        content=Shadow(body=submenu), filter=has_focus
                    ),
                ),
                Float(
                    attach_to_window=submenu,
                    xcursor=True,
                    ycursor=True,
                    allow_cover_cursor=True,
                    content=ConditionalContainer(
                        content=Shadow(body=submenu2),
                        filter=has_focus
                        & Condition(lambda: len(self.selected_menu) >= 1),
                    ),
                ),
                Float(
                    attach_to_window=submenu2,
                    xcursor=True,
                    ycursor=True,
                    allow_cover_cursor=True,
                    content=ConditionalContainer(
                        content=Shadow(body=submenu3),
                        filter=has_focus
                        & Condition(lambda: len(self.selected_menu) >= 2),
                    ),
                ),
                # --
            ]
            + (floats or []),
            key_bindings=key_bindings,
        )

    def _get_menu(self, level: int) -> "MenuItem":
        menu = self.menu_items[self.selected_menu[0]]

        for i, index in enumerate(self.selected_menu[1:]):
            if i < level:
                try:
                    menu = menu.children[index]
                except IndexError:
                    return MenuItem("debug")

        return menu

    def _get_menu_fragments(self) -> StyleAndTextTuples:
        focused = get_app().layout.has_focus(self.window)

        # This is called during the rendering. When we discover that this
        # widget doesn't have the focus anymore. Reset menu state.
        if not focused:
            self.selected_menu = [0]

        # Generate text fragments for the main menu.
        def one_item(i: int, item: MenuItem) -> Iterable[OneStyleAndTextTuple]:
            def mouse_handler(mouse_event: MouseEvent) -> None:
                if mouse_event.event_type == MouseEventType.MOUSE_UP:
                    # Toggle focus.
                    app = get_app()
                    if app.layout.has_focus(self.window):
                        if self.selected_menu == [i]:
                            app.layout.focus_last()
                    else:
                        app.layout.focus(self.window)
                    self.selected_menu = [i]

            yield ("class:menu-bar", " ", mouse_handler)
            if i == self.selected_menu[0] and focused:
                yield ("[SetMenuPosition]", "", mouse_handler)
                style = "class:menu-bar.selected-item"
            else:
                style = "class:menu-bar"
            yield style, item.text, mouse_handler

        result: StyleAndTextTuples = []
        for i, item in enumerate(self.menu_items):
            result.extend(one_item(i, item))

        return result

    def _submenu(self, level: int = 0) -> Window:
        def get_text_fragments() -> StyleAndTextTuples:
            result: StyleAndTextTuples = []
            if level < len(self.selected_menu):
                menu = self._get_menu(level)
                if menu.children:
                    result.append(("class:menu", Border.TOP_LEFT))
                    result.append(("class:menu", Border.HORIZONTAL * (menu.width + 4)))
                    result.append(("class:menu", Border.TOP_RIGHT))
                    result.append(("", "\n"))
                    try:
                        selected_item = self.selected_menu[level + 1]
                    except IndexError:
                        selected_item = -1

                    def one_item(
                        i: int, item: MenuItem
                    ) -> Iterable[OneStyleAndTextTuple]:
                        def mouse_handler(mouse_event: MouseEvent) -> None:
                            if mouse_event.event_type == MouseEventType.MOUSE_UP:
                                app = get_app()
                                if item.handler:
                                    app.layout.focus_last()
                                    item.handler()
                                else:
                                    self.selected_menu = self.selected_menu[
                                        : level + 1
                                    ] + [i]

                        if i == selected_item:
                            yield ("[SetCursorPosition]", "")
                            style = "class:menu-bar.selected-item"
                        else:
                            style = ""

                        yield ("class:menu", Border.VERTICAL)
                        if item.text == "-":
                            yield (
                                style + "class:menu-border",
                                "{}".format(Border.HORIZONTAL * (menu.width + 3)),
                                mouse_handler,
                            )
                        else:
                            yield (
                                style,
                                " {}".format(item.text).ljust(menu.width + 3),
                                mouse_handler,
                            )

                        if item.children:
                            yield (style, ">", mouse_handler)
                        else:
                            yield (style, " ", mouse_handler)

                        if i == selected_item:
                            yield ("[SetMenuPosition]", "")
                        yield ("class:menu", Border.VERTICAL)

                        yield ("", "\n")

                    for i, item in enumerate(menu.children):
                        result.extend(one_item(i, item))

                    result.append(("class:menu", Border.BOTTOM_LEFT))
                    result.append(("class:menu", Border.HORIZONTAL * (menu.width + 4)))
                    result.append(("class:menu", Border.BOTTOM_RIGHT))
            return result

        return Window(FormattedTextControl(get_text_fragments), style="class:menu")

    @property
    def floats(self) -> Optional[List[Float]]:
        return self.container.floats

    def __pt_container__(self) -> Container:
        return self.container

class MenuItem:
    def __init__(
        self,
        text: str = "",
        handler: Optional[Callable[[], None]] = None,
        children: Optional[List["MenuItem"]] = None,
        shortcut: Optional[Sequence[Union[Keys, str]]] = None,
        disabled: bool = False,
    ) -> None:

        self.text = text
        self.handler = handler
        self.children = children or []
        self.shortcut = shortcut
        self.disabled = disabled
        self.selected_item = 0

    @property
    def width(self) -> int:
        if self.children:
            return max(get_cwidth(c.text) for c in self.children)
        else:
            return 0


text:
package org.apache.flink.optimizer.java;

import org.apache.flink.api.common.Plan;
import org.apache.flink.api.common.operators.GenericDataSourceBase;
import org.apache.flink.api.common.operators.Operator;
import org.apache.flink.api.common.operators.base.JoinOperatorBase.JoinHint;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.io.DiscardingOutputFormat;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.optimizer.plan.DualInputPlanNode;
import org.apache.flink.optimizer.plan.OptimizedPlan;
import org.apache.flink.optimizer.plan.SinkPlanNode;
import org.apache.flink.optimizer.util.CompilerTestBase;
import org.apache.flink.runtime.operators.DriverStrategy;
import org.apache.flink.runtime.operators.shipping.ShipStrategyType;
import org.apache.flink.util.Visitor;

import org.junit.Test;

import static org.junit.Assert.*;

@SuppressWarnings("serial")
public class JoinTranslationTest extends CompilerTestBase {

    @Test
    public void testBroadcastHashFirstTest() {
        try {
            DualInputPlanNode node = createPlanAndGetJoinNode(JoinHint.BROADCAST_HASH_FIRST);
            assertEquals(ShipStrategyType.BROADCAST, node.getInput1().getShipStrategy());
            assertEquals(ShipStrategyType.FORWARD, node.getInput2().getShipStrategy());
            assertEquals(DriverStrategy.HYBRIDHASH_BUILD_FIRST, node.getDriverStrategy());
        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getClass().getSimpleName() + ": " + e.getMessage());
        }
    }

    @Test
    public void testBroadcastHashSecondTest() {
        try {
            DualInputPlanNode node = createPlanAndGetJoinNode(JoinHint.BROADCAST_HASH_SECOND);
            assertEquals(ShipStrategyType.FORWARD, node.getInput1().getShipStrategy());
            assertEquals(ShipStrategyType.BROADCAST, node.getInput2().getShipStrategy());
            assertEquals(DriverStrategy.HYBRIDHASH_BUILD_SECOND, node.getDriverStrategy());
        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getClass().getSimpleName() + ": " + e.getMessage());
        }
    }

    @Test
    public void testPartitionHashFirstTest() {
        try {
            DualInputPlanNode node = createPlanAndGetJoinNode(JoinHint.REPARTITION_HASH_FIRST);
            assertEquals(ShipStrategyType.PARTITION_HASH, node.getInput1().getShipStrategy());
            assertEquals(ShipStrategyType.PARTITION_HASH, node.getInput2().getShipStrategy());
            assertEquals(DriverStrategy.HYBRIDHASH_BUILD_FIRST, node.getDriverStrategy());
        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getClass().getSimpleName() + ": " + e.getMessage());
        }
    }

    @Test
    public void testPartitionHashSecondTest() {
        try {
            DualInputPlanNode node = createPlanAndGetJoinNode(JoinHint.REPARTITION_HASH_SECOND);
            assertEquals(ShipStrategyType.PARTITION_HASH, node.getInput1().getShipStrategy());
            assertEquals(ShipStrategyType.PARTITION_HASH, node.getInput2().getShipStrategy());
            assertEquals(DriverStrategy.HYBRIDHASH_BUILD_SECOND, node.getDriverStrategy());
        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getClass().getSimpleName() + ": " + e.getMessage());
        }
    }

    @Test
    public void testPartitionSortMergeTest() {
        try {
            DualInputPlanNode node = createPlanAndGetJoinNode(JoinHint.REPARTITION_SORT_MERGE);
            assertEquals(ShipStrategyType.PARTITION_HASH, node.getInput1().getShipStrategy());
            assertEquals(ShipStrategyType.PARTITION_HASH, node.getInput2().getShipStrategy());
            assertEquals(DriverStrategy.INNER_MERGE, node.getDriverStrategy());
        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getClass().getSimpleName() + ": " + e.getMessage());
        }
    }

    @Test
    public void testOptimizerChoosesTest() {
        try {
            DualInputPlanNode node = createPlanAndGetJoinNode(JoinHint.OPTIMIZER_CHOOSES);
            assertEquals(ShipStrategyType.PARTITION_HASH, node.getInput1().getShipStrategy());
            assertEquals(ShipStrategyType.PARTITION_HASH, node.getInput2().getShipStrategy());
            assertTrue(
                    DriverStrategy.HYBRIDHASH_BUILD_FIRST == node.getDriverStrategy()
                            || DriverStrategy.HYBRIDHASH_BUILD_SECOND == node.getDriverStrategy());
        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getClass().getSimpleName() + ": " + e.getMessage());
        }
    }

    private DualInputPlanNode createPlanAndGetJoinNode(JoinHint hint) {
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        DataSet<Long> i1 = env.generateSequence(1, 1000);
        DataSet<Long> i2 = env.generateSequence(1, 1000);

        i1.join(i2, hint)
                .where(new IdentityKeySelector<Long>())
                .equalTo(new IdentityKeySelector<Long>())
                .output(new DiscardingOutputFormat<Tuple2<Long, Long>>());

        Plan plan = env.createProgramPlan();

        // set statistics to the sources
        plan.accept(
                new Visitor<Operator<?>>() {
                    @Override
                    public boolean preVisit(Operator<?> visitable) {
                        if (visitable instanceof GenericDataSourceBase) {
                            GenericDataSourceBase<?, ?> source =
                                    (GenericDataSourceBase<?, ?>) visitable;
                            setSourceStatistics(source, 10000000, 1000);
                        }

                        return true;
                    }

                    @Override
                    public void postVisit(Operator<?> visitable) {}
                });

        OptimizedPlan op = compileWithStats(plan);

        return (DualInputPlanNode)
                ((SinkPlanNode) op.getDataSinks().iterator().next()).getInput().getSource();
    }

    private static final class IdentityKeySelector<T> implements KeySelector<T, T> {

        @Override
        public T getKey(T value) {
            return value;
        }
    }
}


text:
package org.sindice.siren.analysis;

import java.io.Reader;
import java.util.Map.Entry;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.util.CharArrayMap;
import org.apache.lucene.util.Version;
import org.sindice.siren.analysis.filter.DatatypeAnalyzerFilter;
import org.sindice.siren.analysis.filter.PositionAttributeFilter;
import org.sindice.siren.analysis.filter.SirenPayloadFilter;
import org.sindice.siren.util.JSONDatatype;
import org.sindice.siren.util.XSDDatatype;

/**
 * The JsonAnalyzer is especially designed to process JSON data.
 */
public class JsonAnalyzer extends Analyzer {

  private Analyzer                     valueAnalyzer;
  private Analyzer                     fieldAnalyzer;

  private final Version                matchVersion;

  private final CharArrayMap<Analyzer> regAnalyzers;

  /**
   * Create a {@link JsonAnalyzer} with the specified {@link Analyzer}s for
   * field names and values.
   * <p>
   * The default analyzer for field names will be associated with the datatype
   * {@link JSONDatatype#JSON_FIELD}. The default analyzer for values will be
   * associated with the datatype {@link XSDDatatype#XSD_STRING}.
   *
   * @param fieldAnalyzer Default {@link Analyzer} for the field names
   * @param valueAnalyzer Default {@link Analyzer} for the values
   */
  public JsonAnalyzer(final Version version, final Analyzer fieldAnalyzer,
                      final Analyzer valueAnalyzer) {
    matchVersion = version;
    this.valueAnalyzer = valueAnalyzer;
    this.fieldAnalyzer = fieldAnalyzer;
    regAnalyzers = new CharArrayMap<Analyzer>(version, 64, false);

  }

  public void setValueAnalyzer(final Analyzer analyzer) {
    valueAnalyzer = analyzer;
  }

  public void setFieldAnalyzer(final Analyzer analyzer) {
    fieldAnalyzer = analyzer;
  }

  /**
   * Assign an {@link Analyzer} to be used with that key. That analyzer is used
   * to process tokens generated by the {@link JsonTokenizer}.
   *
   * @param datatype The datatype key
   * @param a the associated {@link Analyzer}
   */
  public void registerDatatype(final char[] datatype, final Analyzer a) {
    if (!regAnalyzers.containsKey(datatype)) {
      regAnalyzers.put(datatype, a);
    }
  }

  /**
   * Remove all registered Datatype {@link Analyzer}s.
   */
  public void clearDatatypes() {
    regAnalyzers.clear();
  }

  @Override
  protected TokenStreamComponents createComponents(final String fieldName, final Reader reader) {
    final JsonTokenizer source = new JsonTokenizer(reader);

    final DatatypeAnalyzerFilter tt = new DatatypeAnalyzerFilter(matchVersion, source, fieldAnalyzer, valueAnalyzer);
    for (final Entry<Object, Analyzer> e : regAnalyzers.entrySet()) {
      tt.register((char[]) e.getKey(), e.getValue());
    }
    TokenStream sink = new PositionAttributeFilter(tt);
    sink = new SirenPayloadFilter(sink);
    return new TokenStreamComponents(source, sink);
  }

}


text:
from pyrates.ir import CircuitIR
import matplotlib.pyplot as plt
import os

# parameters
dt = 1e-2
T = 5000.0
dts = 1.0

eic = CircuitIR.from_yaml("config/stn_gpe/stn_pop").compile(backend='fortran', step_size=dt, solver='scipy',
                                                            auto_compat=True)
results, t = eic.run(simulation_time=T, sampling_step_size=dts, profile=True, outputs={'r_e': 'stn/stn_simple/R_e'})
eic.generate_auto_def(f"{os.getcwd()}/config")
results.plot()
plt.show()