text:
/*
 * transcriptome.h
 *
 *  Created on: Feb 6, 2017
 *      Author: isovic
 */

#ifndef SRC_GRAPHMAP_TRANSCRIPTOME_H_
#define SRC_GRAPHMAP_TRANSCRIPTOME_H_

#include <stdint.h>
#include <map>
#include <memory>
#include <string>
#include <vector>

#include "sequences/sequence_file.h"

namespace is {

class Transcriptome;

std::shared_ptr<Transcriptome> createTranscriptome();

class Transcriptome {
 public:
  friend std::shared_ptr<Transcriptome> createTranscriptome();
  ~Transcriptome();

  /* Parses exons and extracts regions from the given GTF file.
   */
  int LoadGTF(const std::string &gtf_path);

  /* Constructs transcriptome sequences from the preloaded GTF file.
   */
  std::shared_ptr<SequenceFile> GenerateTranscriptomeSeqs(const std::shared_ptr<SequenceFile> sequences);

  /* Generates a header for a SAM file. The header is composed of
   * genomic sequence names.
   */
  std::string GenerateSAMHeaders();

  const std::map<std::string, std::vector<std::pair<std::string, char> > >& get_genome_id_to_trans_id() const {
    return genome_id_to_trans_id_;
  }

  const std::map<std::string, std::vector<std::pair<int64_t, int64_t> > >& get_trans_id_to_exons() const {
    return trans_id_to_exons_;
  }

  const std::map<std::string, std::vector<std::pair<int64_t, int64_t> > >& get_trans_id_to_regions() const {
    return trans_id_to_regions_;
  }

  const std::map<std::string, std::pair<std::string, char>>& get_trans_id_to_genome_id() const {
    return trans_id_to_genome_id_;
  }

  const std::map<std::string, int64_t>& get_genome_id_to_len() const {
    return genome_id_to_len_;
  }

 private:
  std::string gtf_path_;

  // A map from genome (chromosome) name (e.g. header split to first space) to a vector containing all transcriptomes which can be generated from that chromosome.
  // Each pair is a (transcript_id, strand), where strand is either '+' or '-';
  std::map<std::string, std::vector<std::pair<std::string, char>>> genome_id_to_trans_id_;
  // Reverse map, to obtain the chromosome name when converting from transcriptome space back to genome space.
  // Second parameter of the pair is the orientation on the genome.
  std::map<std::string, std::pair<std::string, char>> trans_id_to_genome_id_;
  // A map from transcript_id to a vector containing pairs of coordinates. Each pair of coordinates presents one exon which makes the transcriptome.
  std::map<std::string, std::vector<std::pair<int64_t, int64_t>>> trans_id_to_exons_;
  // A list of exons in such way that it combines overlapping exons into regions.
  std::map<std::string, std::vector<std::pair<int64_t, int64_t>>> trans_id_to_regions_;
  // Length of each chromosome in genome space. Needed for reversing the mapping if transcriptome was reverse complemented.
  std::map<std::string, int64_t> genome_id_to_len_;

  Transcriptome();      // Private constructor, prevent memory leaks;
  Transcriptome(const Transcriptome&) = delete;
  const Transcriptome& operator=(const Transcriptome&) = delete;

  // Creates a transcriptome from a given reference sequence and a path to a file with gene annotations.
  // Parameters:
  // @param annotations_path Path to a GFF file (or another supported format) which contains the annotations of exonic regions.
  // @param references A SequenceFile object which contains reference sequences already loaded from disk.
  // @param transcripts A SequenceFile which will contain the generated transcriptomes.
  // @return 0 if everything went fine (C-style).
  int MakeTranscript_(const std::map<std::string, std::vector<std::pair<std::string, char>>> &genome_id_to_trans_id,
                      const std::map<std::string, std::vector<std::pair<int64_t, int64_t>>> &trans_id_to_exons,
                      const std::shared_ptr<SequenceFile> references, std::shared_ptr<SequenceFile> transcripts) const;
  /** Resolves lists of exons in such way that it combines overlapping exons into regions.
   * Returns dict that maps transcript id to list of regions.
   * @param trans_id_to_exons A map from transcriptome ID (name) to a vector of exons which make this transcriptome.
   * @param trans_id_to_regions Generated return map from transcriptome ID (name) to a vector containing regions.
   * @return 0 if everything went fine (C-style).
   */
  int MakeRegions_(const std::map<std::string, std::vector<std::pair<int64_t, int64_t>>> &trans_id_to_exons,
                   std::map<std::string, std::vector<std::pair<int64_t, int64_t>>> &trans_id_to_regions) const;
  int ParseExons_(const std::string &annotations_path,
                  std::map<std::string, std::vector<std::pair<std::string, char>>> &genomeToTrans,
                  std::map<std::string, std::pair<std::string, char>> &transIdToGenomeId,
                  std::map<std::string, std::vector<std::pair<int64_t, int64_t>>> &transToExons) const;
  void HashGenomeLengths_(const std::shared_ptr<SequenceFile> sequences, std::map<std::string, int64_t> &rlens) const;
  std::string trim_(std::string s) const;
  std::vector<std::string> split_(std::string s, char c) const;
  std::string getSequenceName_(const SingleSequence &seq) const;
  std::string getTID_(const std::string &chr_name, const std::string &attributes) const;
//  void outputSeq_(char *header, size_t headerLen, const int8_t *seq, size_t seqLen) const;

};

} /* namespace is */

#endif /* SRC_GRAPHMAP_TRANSCRIPTOME_H_ */


text:
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Sample</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="manifest" href="manifest.webmanifest">
  <meta name="theme-color" content="#1976d2">
  <link rel="manifest" href="manifest.webmanifest">
  <meta name="theme-color" content="#1976d2">
  <link rel="manifest" href="manifest.webmanifest">
  <meta name="theme-color" content="#1976d2">
</head>
<body>
  <app-root></app-root>
  <noscript>Please enable JavaScript to continue using this application.</noscript>
</body>
</html>

redpajama_set_name: RedPajamaGithub


text:
package com.actian.services.knime.core.operators;

import java.util.Arrays;
import java.util.List;

import org.knime.core.node.InvalidSettingsException;
import org.knime.core.node.defaultnodesettings.SettingsModel;
import org.knime.core.node.defaultnodesettings.SettingsModelInteger;
import org.knime.core.node.defaultnodesettings.SettingsModelString;

import com.actian.services.dataflow.operators.Sessionize;
import com.pervasive.datarush.knime.core.framework.AbstractDRSettingsModel;
import com.pervasive.datarush.ports.PortMetadata;

public class SessionizeNodeSettings extends AbstractDRSettingsModel<Sessionize> {

	public final SettingsModelString keyColumn = new SettingsModelString("keyColumn", "");
	public final SettingsModelString timeColumn = new SettingsModelString("timeColumn", "");
	public final SettingsModelInteger interval = new SettingsModelInteger("interval", 60);
	public final SettingsModelString uot = new SettingsModelString("uot", "Secs");

	@Override
	public void configure(PortMetadata[] inputTypes, Sessionize operator)
			throws InvalidSettingsException {
		operator.setKeyColumn(keyColumn.getStringValue());
		operator.setTimeColumn(timeColumn.getStringValue());
		long i = interval.getIntValue()*1000;
		switch(uot.getStringValue()) {
			case "Secs": i = i * 1; break;
			case "Mins": i = i * 60; break;
			case "Hrs" : i = i * 60 * 60; break;
			case "Days": i = i * 60 * 60 * 24; break;
		}
		operator.setInterval(i);
	}

	@Override
	protected List<SettingsModel> getComponentSettings() {
		return Arrays.<SettingsModel>asList(keyColumn,timeColumn,interval,uot);
	}

}


text:
"""
A joystick controller for the drone.

"""
from __future__ import division
import sys

import rospy
from sensor_msgs.msg import Joy

from controller_interface import DroneController

class Button(object):
    """
    Button mapping.

    By default, the PS3 controller is used with the following mapping:

    - Landing: L2
    - Arrived at Destination: R2
    - Takeoff: L1
    - Emergency: R1

    """
    land = 8
    arrived = 9
    takeoff = 10
    emergency = 11

class Axis(object):
    """
    Axis mapping.

    By default, the PS3 controller is used with the following mapping:

    - Roll: Left analog, left-right
    - Pitch: Left analog, up-down
    - Yaw: Right analog, left-right
    - Height: Right analog, up-down

    """
    roll = 0
    pitch = 1
    yaw = 2
    height = 3

class Scale(object):
    """
    Scale mapping.

    """
    roll = pitch = yaw = height = 1

def handle_joystick(data):
    """
    Receive and handle joystick message data.

    Parameters
    ----------
    data : Joy
        Joystick data.

    """
    if data.buttons[Button.emergency]:
        rospy.loginfo("Emergency Button Pressed")
        controller.emergency()
    elif data.buttons[Button.land]:
        rospy.loginfo("Land Button Pressed")
        controller.land()
    elif data.buttons[Button.takeoff]:
        rospy.loginfo("Takeoff Button Pressed")
        controller.take_off()
    else:
        controller.set_command(data.axes[Axis.roll] * Scale.roll,
                               data.axes[Axis.pitch] * Scale.pitch,
                               data.axes[Axis.yaw] * Scale.yaw,
                               data.axes[Axis.height] * Scale.height)

    if data.buttons[Button.arrived]:
        rospy.loginfo("Arrival Button Pressed")
        controller.arrived = True
    else:
        controller.arrived = False

def update_mappings():
    """
    Update the button, axis, and scale mappings from the launch file.

    """
    Button.emergency = int(rospy.get_param("~ButtonEmergency",
                                           Button.emergency))
    Button.land = int(rospy.get_param("~ButtonLand", Button.land))
    Button.takeoff = int(rospy.get_param("~ButtonTakeoff", Button.takeoff))
    Button.arrived = int(rospy.get_param("~ButtonArrived", Button.arrived))
    Axis.roll = int(rospy.get_param("~AxisRoll", Axis.roll))
    Axis.pitch = int(rospy.get_param("~AxisPitch", Axis.pitch))
    Axis.yaw = int(rospy.get_param("~AxisYaw", Axis.yaw))
    Axis.height = int(rospy.get_param("~AxisZ", Axis.height))
    Scale.roll = float(rospy.get_param("~ScaleRoll", Scale.roll))
    Scale.pitch = float(rospy.get_param("~ScalePitch", Scale.pitch))
    Scale.yaw = float(rospy.get_param("~ScaleYaw", Scale.yaw))
    Scale.height = float(rospy.get_param("~ScaleZ", Scale.height))

if __name__ == "__main__":
    rospy.init_node("ardrone_joystick_controller")
    controller = DroneController()
    update_mappings()
    rospy.Subscriber("/joy", Joy, handle_joystick)
    rospy.spin()


text:
"""
Entries are containers for calculated information, which is used in
many analyses. This module contains entry related tools and implements
the base Entry class, which is the basic entity that can be used to
store calculated information. Other Entry classes such as ComputedEntry
and PDEntry inherit from this class.
"""

from numbers import Number
from abc import ABCMeta, abstractmethod
from typing import Union, Dict

import numpy as np

from monty.json import MSONable

from pymatgen.core.composition import Composition

__author__ = "Shyue Ping Ong, Anubhav Jain, Ayush Gupta"
__copyright__ = "Copyright 2020, The Materials Project"
__version__ = "1.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "shyuep@gmail.com"
__status__ = "Production"
__date__ = "Mar 03, 2020"

class Entry(MSONable, metaclass=ABCMeta):
    """
    A lightweight object containing the energy associated with
    a specific chemical composition. This base class is not
    intended to be instantiated directly. Note that classes
    which inherit from Entry must define a .energy property.

    """

    def __init__(
        self,
        composition: Union[Composition, str, Dict[str, float]],
        energy: float,
    ):
        """
        Initializes an Entry.

        Args:
            composition (Composition): Composition of the entry. For
                flexibility, this can take the form of all the typical input
                taken by a Composition, including a {symbol: amt} dict,
                a string formula, and others.
            energy (float): Energy of the entry.
        """
        self._composition = Composition(composition)
        self._energy = energy

    @property
    def is_element(self) -> bool:
        """
        :return: Whether composition of entry is an element.
        """
        # NOTE _composition rather than composition as GrandPDEntry
        # edge case exists if we have a compound where chempots are
        # given for all bar one element type
        return self._composition.is_element

    @property
    def composition(self) -> Composition:
        """
        :return: the composition of the entry.
        """
        return self._composition

    @property
    @abstractmethod
    def energy(self) -> float:
        """
        :return: the energy of the entry.
        """

    @property
    def energy_per_atom(self) -> float:
        """
        :return: the energy per atom of the entry.
        """
        return self.energy / self.composition.num_atoms

    def __repr__(self):
        return "{} : {} with energy = {:.4f}".format(self.__class__.__name__, self.composition, self.energy)

    def __str__(self):
        return self.__repr__()

    def normalize(self, mode: str = "formula_unit") -> "Entry":
        """
        Normalize the entry's composition and energy.

        Args:
            mode: "formula_unit" is the default, which normalizes to
                composition.reduced_formula. The other option is "atom", which
                normalizes such that the composition amounts sum to 1.
        """

        factor = self._normalization_factor(mode)
        new_composition = self._composition / factor
        new_energy = self._energy / factor

        new_entry_dict = self.as_dict()
        new_entry_dict["composition"] = new_composition.as_dict()
        new_entry_dict["energy"] = new_energy

        return self.from_dict(new_entry_dict)

    def _normalization_factor(self, mode: str = "formula_unit") -> float:
        # NOTE here we use composition rather than _composition in order to ensure
        # that we have the expected behaviour downstream in cases where composition
        # is overwritten (GrandPotPDEntry, TransformedPDEntry)
        if mode == "atom":
            factor = self.composition.num_atoms
        elif mode == "formula_unit":
            factor = self.composition.get_reduced_composition_and_factor()[1]
        else:
            raise ValueError("`{}` is not an allowed option for normalization".format(mode))

        return factor

    def as_dict(self) -> dict:
        """
        :return: MSONable dict.
        """
        return {
            "@module": self.__class__.__module__,
            "@class": self.__class__.__name__,
            "energy": self._energy,
            "composition": self._composition.as_dict(),
        }

    def __eq__(self, other):
        # NOTE: Scaled duplicates i.e. physically equivalent materials
        # are not equal unless normalized separately.
        if self is other:
            return True

        # Equality is defined based on composition and energy
        # If structures are involved, it is assumed that a {composition, energy} is
        # vanishingly unlikely to be the same if the structures are different

        if not np.allclose(self.energy, other.energy):
            return False

        return self.composition == other.composition

    def _is_dict_eq(self, other):
        """
        Check if entry dicts are equal using a robust check for
        numerical values.
        """
        self_dict = self.as_dict()
        other_dict = other.as_dict()

        # NOTE use implicit generator to allow all() to short-circuit
        return all(_is_robust_eq(other_dict[k], v) for k, v in self_dict.items())

    def __hash__(self):
        # NOTE truncate _energy to 8 dp to ensure same robustness
        # as np.allclose
        return hash(f"{self.__class__.__name__}" f"{self._composition.formula}" f"{self._energy:.8f}")

def _is_robust_eq(v_self, v_other):
    """
    Use np.allclose for numerical values for robustness
    otherwise use default __eq__.

    NOTE robustness doesn't reach to nested structures i.e. For a
    ComputedStructureEntry where parameters stores the Incar this would
    not be robust to fp changes in that Incar dictionary. For a
    GrandPotPDEntry it will not be robust to fp changes in the chempots
    """
    if isinstance(v_self, Number) and isinstance(v_other, Number):
        return np.allclose(v_self, v_other, atol=1e-8)

    return v_self == v_other


text:
from collections import defaultdict
import logging
import json
from typing import Dict, Generator, List, NamedTuple, Optional, Text, Tuple

from rasa.core.featurizers.tracker_featurizers import MaxHistoryTrackerFeaturizer
from rasa.shared.core.constants import (
    ACTION_LISTEN_NAME,
    PREVIOUS_ACTION,
    ACTION_UNLIKELY_INTENT_NAME,
    USER,
)
from rasa.shared.core.domain import Domain, State
from rasa.shared.core.events import ActionExecuted, Event
from rasa.shared.core.generator import TrackerWithCachedStates

from rasa.nlu.tokenizers.tokenizer import Tokenizer
from rasa.shared.nlu.constants import TEXT
from rasa.shared.nlu.training_data.message import Message

logger = logging.getLogger(__name__)

class StoryConflict:
    """Represents a conflict between two or more stories.

    Here, a conflict means that different actions are supposed to follow from
    the same dialogue state, which most policies cannot learn.
    """

    def __init__(self, sliced_states: List[State]) -> None:
        """
        Creates a `StoryConflict` from a given state.

        Args:
            sliced_states: The (sliced) dialogue state at which the conflict occurs.
        """

        self._sliced_states = sliced_states
        # A list of actions that all follow from the same state.
        self._conflicting_actions = defaultdict(
            list
        )  # {"action": ["story_1", ...], ...}

    def __hash__(self) -> int:
        return hash(str(list(self._sliced_states)))

    def add_conflicting_action(self, action: Text, story_name: Text) -> None:
        """Adds another action that follows from the same state.

        Args:
            action: Name of the action.
            story_name: Name of the story where this action is chosen.
        """
        self._conflicting_actions[action] += [story_name]

    @property
    def conflicting_actions(self) -> List[Text]:
        """List of conflicting actions.

        Returns:
            List of conflicting actions.

        """
        return list(self._conflicting_actions.keys())

    @property
    def conflict_has_prior_events(self) -> bool:
        """Checks if prior events exist.

        Returns:
            `True` if anything has happened before this conflict, otherwise `False`.
        """
        return _get_previous_event(self._sliced_states[-1])[0] is not None

    def __str__(self) -> Text:
        # Describe where the conflict occurs in the stories
        last_event_type, last_event_name = _get_previous_event(self._sliced_states[-1])
        if last_event_type:
            conflict_message = (
                f"Story structure conflict after {last_event_type} "
                f"'{last_event_name}':\n"
            )
        else:
            conflict_message = "Story structure conflict at the beginning of stories:\n"

        # List which stories are in conflict with one another
        for action, stories in self._conflicting_actions.items():
            conflict_message += (
                f"  {self._summarize_conflicting_actions(action, stories)}"
            )

        return conflict_message

    @staticmethod
    def _summarize_conflicting_actions(action: Text, stories: List[Text]) -> Text:
        """Gives a summarized textual description of where one action occurs.

        Args:
            action: The name of the action.
            stories: The stories in which the action occurs.

        Returns:
            A textural summary.
        """
        if len(stories) > 3:
            # Four or more stories are present
            conflict_description = (
                f"'{stories[0]}', '{stories[1]}', and {len(stories) - 2} other trackers"
            )
        elif len(stories) == 3:
            conflict_description = f"'{stories[0]}', '{stories[1]}', and '{stories[2]}'"
        elif len(stories) == 2:
            conflict_description = f"'{stories[0]}' and '{stories[1]}'"
        elif len(stories) == 1:
            conflict_description = f"'{stories[0]}'"
        else:
            raise ValueError(
                "An internal error occurred while trying to summarise a conflict "
                "without stories. Please file a bug report at "
                "https://github.com/RasaHQ/rasa."
            )

        return f"{action} predicted in {conflict_description}\n"

class TrackerEventStateTuple(NamedTuple):
    """Holds a tracker, an event, and sliced states associated with those."""

    tracker: TrackerWithCachedStates
    event: Event
    sliced_states: List[State]

    @property
    def sliced_states_hash(self) -> int:
        """Returns the hash of the sliced states."""
        return hash(json.dumps(self.sliced_states, sort_keys=True))

def find_story_conflicts(
    trackers: List[TrackerWithCachedStates],
    domain: Domain,
    max_history: Optional[int] = None,
) -> List[StoryConflict]:
    """Generates `StoryConflict` objects, describing conflicts in the given trackers.

    Args:
        trackers: Trackers in which to search for conflicts.
        domain: The domain.
        max_history: The maximum history length to be taken into account.

    Returns:
        StoryConflict objects.
    """
    if max_history:
        logger.info(
            f"Considering the preceding {max_history} turns for conflict analysis."
        )
    else:
        logger.info("Considering all preceding turns for conflict analysis.")

    # We do this in two steps, to reduce memory consumption:

    # Create a 'state -> list of actions' dict, where the state is
    # represented by its hash
    conflicting_state_action_mapping = _find_conflicting_states(
        trackers, domain, max_history
    )

    # Iterate once more over all states and note the (unhashed) state,
    # for which a conflict occurs
    conflicts = _build_conflicts_from_states(
        trackers, domain, max_history, conflicting_state_action_mapping,
    )

    return conflicts

def _find_conflicting_states(
    trackers: List[TrackerWithCachedStates],
    domain: Domain,
    max_history: Optional[int],
    tokenizer: Optional[Tokenizer] = None,
) -> Dict[int, Optional[List[Text]]]:
    """Identifies all states from which different actions follow.

    Args:
        trackers: Trackers that contain the states.
        domain: The domain object.
        max_history: Number of turns to take into account for the state descriptions.
        tokenizer: A tokenizer to tokenize the user messages.

    Returns:
        A dictionary mapping state-hashes to a list of actions that follow from each
        state.
    """
    # Create a 'state -> list of actions' dict, where the state is
    # represented by its hash
    state_action_mapping = defaultdict(list)

    for element in _sliced_states_iterator(trackers, domain, max_history, tokenizer):
        hashed_state = element.sliced_states_hash
        current_hash = hash(element.event)

        if current_hash not in state_action_mapping[
            hashed_state
        ] or _unlearnable_action(element.event):
            state_action_mapping[hashed_state] += [current_hash]

    # Keep only conflicting `state_action_mapping`s
    # or those mappings that contain `action_unlikely_intent`
    action_unlikely_intent_hash = hash(
        ActionExecuted(action_name=ACTION_UNLIKELY_INTENT_NAME)
    )
    return {
        state_hash: actions
        for (state_hash, actions) in state_action_mapping.items()
        if len(actions) > 1 or action_unlikely_intent_hash in actions
    }

def _unlearnable_action(event: Event) -> bool:
    """Identifies if the action cannot be learned by policies that use story data.

    Args:
        event: An event to be checked.

    Returns:
        `True` if the event can be learned, `False` otherwise.
    """
    return (
        isinstance(event, ActionExecuted)
        and event.action_name == ACTION_UNLIKELY_INTENT_NAME
    )

def _build_conflicts_from_states(
    trackers: List[TrackerWithCachedStates],
    domain: Domain,
    max_history: Optional[int],
    conflicting_state_action_mapping: Dict[int, Optional[List[Text]]],
    tokenizer: Optional[Tokenizer] = None,
) -> List["StoryConflict"]:
    """Builds a list of `StoryConflict` objects for each given conflict.

    Args:
        trackers: Trackers that contain the states.
        domain: The domain object.
        max_history: Number of turns to take into account for the state descriptions.
        conflicting_state_action_mapping: A dictionary mapping state-hashes to a list
            of actions that follow from each state.
        tokenizer: A tokenizer to tokenize the user messages.

    Returns:
        A list of `StoryConflict` objects that describe inconsistencies in the story
        structure. These objects also contain the history that leads up to the conflict.
    """
    # Iterate once more over all states and note the (unhashed) state,
    # for which a conflict occurs
    conflicts = {}
    for element in _sliced_states_iterator(trackers, domain, max_history, tokenizer):
        hashed_state = element.sliced_states_hash

        if hashed_state in conflicting_state_action_mapping:
            if hashed_state not in conflicts:
                conflicts[hashed_state] = StoryConflict(element.sliced_states)

            conflicts[hashed_state].add_conflicting_action(
                action=str(element.event), story_name=element.tracker.sender_id,
            )

    # Return list of conflicts that arise from unpredictable actions
    # (actions that start the conversation)
    return [
        conflict
        for (hashed_state, conflict) in conflicts.items()
        if conflict.conflict_has_prior_events
    ]

def _sliced_states_iterator(
    trackers: List[TrackerWithCachedStates],
    domain: Domain,
    max_history: Optional[int],
    tokenizer: Optional[Tokenizer],
) -> Generator[TrackerEventStateTuple, None, None]:
    """Creates an iterator over sliced states.

    Iterate over all given trackers and all sliced states within each tracker,
    where the slicing is based on `max_history`.

    Args:
        trackers: List of trackers.
        domain: Domain (used for tracker.past_states).
        max_history: Assumed `max_history` value for slicing.
        tokenizer: A tokenizer to tokenize the user messages.

    Yields:
        A (tracker, event, sliced_states) triplet.
    """
    for tracker in trackers:
        states = tracker.past_states(domain)

        idx = 0
        for event in tracker.events:
            if isinstance(event, ActionExecuted):
                sliced_states = MaxHistoryTrackerFeaturizer.slice_state_history(
                    states[: idx + 1], max_history
                )
                if tokenizer:
                    _apply_tokenizer_to_states(tokenizer, sliced_states)
                # TODO: deal with oov (different tokens can lead to identical features
                # if some of those tokens are out of vocabulary for all featurizers)
                yield TrackerEventStateTuple(tracker, event, sliced_states)
                idx += 1

def _apply_tokenizer_to_states(tokenizer: Tokenizer, states: List[State]) -> None:
    """Split each user text into tokens and concatenate them again.

    Args:
        tokenizer: A tokenizer to tokenize the user messages.
        states: The states to be tokenized.
    """
    for state in states:
        if USER in state and TEXT in state[USER]:
            state[USER][TEXT] = " ".join(
                token.text
                for token in tokenizer.tokenize(
                    Message({TEXT: state[USER][TEXT]}), TEXT
                )
            )

def _get_previous_event(
    state: Optional[State],
) -> Tuple[Optional[Text], Optional[Text]]:
    """Returns previous event type and name.

    Returns the type and name of the event (action or intent) previous to the
    given state (excluding action_listen).

    Args:
        state: Element of sliced states.

    Returns:
        Tuple of (type, name) strings of the prior event.
    """

    previous_event_type = None
    previous_event_name = None

    # A typical state might be
    # `{'user': {'intent': 'greet'}, 'prev_action': {'action_name': 'action_listen'}}`.
    if not state:
        previous_event_type = None
        previous_event_name = None
    elif (
        PREVIOUS_ACTION in state.keys()
        and "action_name" in state[PREVIOUS_ACTION]
        and state[PREVIOUS_ACTION]["action_name"] != ACTION_LISTEN_NAME
    ):
        previous_event_type = "action"
        previous_event_name = state[PREVIOUS_ACTION]["action_name"]
    elif PREVIOUS_ACTION in state.keys() and "action_text" in state[PREVIOUS_ACTION]:
        previous_event_type = "bot utterance"
        previous_event_name = state[PREVIOUS_ACTION]["action_text"]
    elif USER in state.keys():
        if "intent" in state[USER]:
            previous_event_type = "intent"
            previous_event_name = state[USER]["intent"]
        elif "text" in state[USER]:
            previous_event_type = "user utterance"
            previous_event_name = state[USER]["text"]

    if not isinstance(previous_event_name, (str, type(None))):
        # While the Substate type doesn't restrict the value of `action_text` /
        # `intent`, etc. to be a string, it always should be
        raise TypeError(
            f"The value '{previous_event_name}' in the substate should be a string or "
            f"None, not {type(previous_event_name)}. Did you modify Rasa source code?"
        )

    return previous_event_type, previous_event_name


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="description" content="Metro, a sleek, intuitive, and powerful framework for faster and easier web development for Windows Metro Style.">
    <meta name="keywords" content="HTML, CSS, JS, JavaScript, framework, metro, front-end, frontend, web development">
    <meta name="author" content="Sergey Pimenov and Metro UI CSS contributors">

    <link rel='shortcut icon' type='image/x-icon' href='favicon.ico' />
    <title>RTL Supprot :: Metro UI CSS - The front-end framework for developing projects on the web in Windows Metro Style</title>

    <link href="css/metro.css" rel="stylesheet">
    <link href="css/metro-icons.css" rel="stylesheet">
    <link href="css/metro-rtl.css" rel="stylesheet">
    <link href="css/metro-responsive.css" rel="stylesheet">
    <link href="css/metro-schemes.css" rel="stylesheet">

    <link href="css/docs.css" rel="stylesheet">

 RTL Support

        @@adsense

            To use rtl support you must include metro-rtl.css in head of you page and set attribute dir to rtl for parent element or same element.

Typography

                <link href="css/metro-rtl.css" rel="stylesheet">

                <div dir="rtl">
                    <h1>...</h1>
                    <p>...</p>
                </div>

                <p dir="rtl">...</p>

                <article dir="rtl">...</article>

Paragraph

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean luctus lectus sit amet odio ullamcorper malesuada dignissim justo gravida. Pellentesque sagittis, tellus id sagittis accumsan, augue velit pretium urna, ac interdum dui nibh et orci. Quisque dapibus elit ut metus varius ac bibendum sem luctus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed quis sagittis lorem. Praesent ac eros quam.

Heading

h1. Metro RTL Heading

h2. Metro RTL Heading

h3. Metro RTL Heading

h4. Metro RTL Heading

h5. Metro RTL Heading

h6. Metro RTL Heading

Lists

Lorem ipsum dolor sit amet

Consectetur adipiscing elit

Integer molestie lorem at massa

Facilisis in pretium nisl aliquet

Nulla volutpat aliquam velit

Phasellus iaculis neque

Purus sodales ultricies

Vestibulum laoreet porttitor sem

Ac tristique libero volutpat at

Phasellus iaculis neque

Purus sodales ultricies

Vestibulum laoreet porttitor sem

Ac tristique libero volutpat at

Faucibus porta lacus fringilla vel

Aenean sit amet erat nunc

Eget porttitor lorem

Description

default

Description lists

A description list is perfect for defining terms.

Euismod

Vestibulum id ligula porta felis euismod semper eget lacinia odio sem nec elit.

Donec id elit non mi porta gravida at eget metus.

Malesuada porta

Etiam porta sem malesuada magna mollis euismod.

horizontal

Description lists

A description list is perfect for defining terms.

Euismod

Vestibulum id ligula porta felis euismod semper eget lacinia odio sem nec elit.

Donec id elit non mi porta gravida at eget metus.

Malesuada porta

Etiam porta sem malesuada magna mollis euismod.

Blockquote

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.

                Someone famous Source Title

Input controls

                <div dir="rtl">
                    <div class="input-control text" data-role="input">
                        <input type="text" value="This is a text">
                    </div>
                </div>

                <div class="input-control text" data-role="input"  dir="rtl">
                    <input type="text" value="This is a text">
                </div>

Simple input

                            <input type="text" value="This is a text">

Input with button

                            <input type="text" value="This is a text">
                            <button class="button"></button>

Input with buttons group

                            <input type="text">

                                <button class="button"></button>
                                <button class="button"></button>

Prepend icon

                            <input type="text" value="This is a text">

Helper clear

                            <input type="text" value="This is a text">
                            <button class="button helper-button clear"></button>

Helper reveal

                            <input type="password" value="This is a text">
                            <button class="button helper-button reveal"></button>

Input file

                            <input type="file">
                            <button class="button"></button>

Select

                            <select>
                                <option>1</option>
                                <option>2</option>
                                <option>3</option>
                            </select>

    @@hit


text:
import os
from ConfigManager import *

c = config = ConfigManager()

#
# General
#
general = c.add_section('general')

general['renderer'] = StringOption(
    """ Renderer to use for conversion """,
    options = '--renderer',
    default = 'XHTML',
)

general['theme'] = StringOption(
    """ Theme for the renderer to use """,
    options = '--theme',
    default = 'default',
)

general['copy-theme-extras'] = BooleanOption(
    """  Copy files associated with the theme to the output directory """,
    options = '--copy-theme-extras !--no-theme-extras',
    default = True,
)

general['kpsewhich'] = StringOption(
    """ Program which locates LaTeX files and packages """,
    options = '--kpsewhich',
    default = 'kpsewhich',
)

def readconfig(file):
    """ Read a configuration file """
    if not os.path.isfile(file):
        print >>sys.stderr, "WARNING: Could not load config file '%s'" % file
        return
    config.read(file)

general['config'] = StringOption(
    """
    Load additional configuration file

    This configuration file will be loaded during the processing of
    command-line options.  However, configuration files cannot override
    command-line options.  So no matter what is in the configuration file,
    if an option is specified on the command-line, it will always win.
    To eliminate any confusion, this should generally be the first
    argument.

    """,
    options = '--config -c',
    callback = readconfig,
)

general['paux-dirs'] = MultiOption(
    """
    Directories where *.paux files should be loaded from.

    """,
    options = '--paux-dirs',
)

#
# Links
#

links = c.add_section('links')

def getstring(data):
    """ Return a string which may or may not be quoted """
    data = list(data.lstrip())

    if not data:
        return ''

    s = []
    for quote in '\'"':
        if data[0] == quote:
            data.pop(0)
            while data:
                if data[0] == quote:
                    data.pop(0)
                    break
                s.append(data.pop(0))
            return ''.join(s), ''.join(data)

    while data:
        if data[0] != ' ':
            s.append(data.pop(0))
            continue
        break
    return ''.join(s), ''.join(data)

def setlinks(data):
    """ Set links in the configuration """
    data = data[1:-1].strip()
    key, data = getstring(data)
    url, data = getstring(data)
    title, data = getstring(data)
    if not title:
        title = url
        url = ''
    if title:
        links['%s-title' % key] = StringOption(default=title)
    if url:
        links['%s-url' % key] = StringOption(default=url)

links[';links'] = CompoundOption(
    """ Set links for use in navigation """,
    options = '--link',
    category = 'document',
    callback = setlinks,
)

#
# Counters
#

counters = c.add_section('counters')

def setcounter(data):
    """ Set counters in the configuration """
    value = [x for x in data[1:-1].split() if x]
    if len(value) == 2:
        counters[value[0]] = IntegerOption(default=int(value[1]))

counters[';counters'] = CompoundOption(
    """ Set initial counter values """,
    options = '--counter',
    category = 'document',
    callback = setcounter,
)

#
# Files
#

files = c.add_section('files')
c.add_category('files', 'File Handling Options')

files['input-encoding'] = StringOption(
    """ Input file encoding """,
    options = '--input-encoding',
    default = 'utf-8',
    category = 'files',
)

files['output-encoding'] = StringOption(
    """ Output file encoding """,
    options = '--output-encoding',
    default = 'utf-8',
    category = 'files',
)

files['escape-high-chars'] = BooleanOption(
    """ Escape characters that are higher than 7-bit """,
    options = '--escape-high-chars',
    default = False,
    category = 'files',
)

files['split-level'] = IntegerOption(
    """ Highest section level that generates a new file """,
    options = '--split-level',
    default = 2,
    category = 'files',
)

def setFilename(data):
    """ If there is only one filename specified, turn off splitting """
    data = data.strip()
    if ' ' in data:
        return data
    if '[' in data:
        return data
    files['split-level'] = -10
    return data

files['filename'] = StringOption(
    """ Template for output filenames """,
    options = '--filename',
    default = 'index [$id, sect$num(4)]',
    category = 'files',
    callback = setFilename,
)

files['bad-chars'] = StringOption(
    """ Characters that should not be allowed in a filename """,
    options = '--bad-filename-chars',
    default = ': #$%^&*!~`"\'=?/{}[]()|<>;\\,.',
    category = 'files',
)

files['bad-chars-sub'] = StringOption(
    """ Character that should be used instead of an illegal character """,
    options = '--bad-filename-chars-sub',
    default = '-',
    category = 'files',
)

files['directory'] = StringOption(
    """ Directory to put output files into """,
    options = '--dir -d',
    category = 'files',
    default = '$jobname',
)

#
# Images
#

images = c.add_section('images')
c.add_category('images', 'Image Generation Options')

images['base-url'] = StringOption(
    """ Base URL for all images """,
    options = '--image-base-url',
    category = 'images',
)

images['enabled'] = BooleanOption(
    """ Enable image generation """,
    options = '--enable-images !--disable-images',
    default = True,
    category = 'images',
)

images['imager'] = StringOption(
    """ LaTeX to image program """,
    options = '--imager',
    default = 'dvipng dvi2bitmap gspdfpng gsdvipng OSXCoreGraphics',
    category = 'images',
)

images['vector-imager'] = StringOption(
    """ LaTeX to vector image program """,
    options = '--vector-imager',
    default = 'none dvisvgm',
    category = 'images',
)

images['filenames'] = StringOption(
    """ Template for image filenames """,
    options = '--image-filenames',
    default = 'images/img-$num(4)',
    category = 'images',
)

images['baseline-padding'] = IntegerOption(
    """ Amount to pad the image below the baseline """,
    options = '--image-baseline-padding',
    default = 0,
    category = 'images',
)

images['scale-factor'] = FloatOption(
    """ Factor to scale externally included images by """,
    options = '--image-scale-factor',
    default = 1.0,
    category = 'images',
)

images['compiler'] = StringOption(
    """ LaTeX command to use when compiling image document """,
    options = '--image-compiler',
    category = 'images',
)

images['cache'] = BooleanOption(
    """  Enable image caching between runs """,
    options = '--enable-image-cache !--disable-image-cache',
    default = False,
    category = 'images',
)

images['save-file'] = BooleanOption(
    """ Should the temporary images.tex file be saved for debugging? """,
    options = '--save-image-file !--delete-image-file',
    default = False,
    category = 'images',
)

images['transparent'] = BooleanOption(
    """ Specifies whether the image backgrounds should be transparent or not """,
    options = '--transparent-images !--opaque-images',
    default = False,
    category = 'images',
)

images['resolution'] = IntegerOption(
    """ Resolution of images document """,
    options = '--image-resolution',
    default = 0,
    category = 'images',
)

#
# Document
#

doc = c.add_section('document')
c.add_category('document', 'Document Options')

doc['base-url'] = StringOption(
    """ Base URL for inter-node links """,
    options = '--base-url',
    category = 'document',
)

doc['title'] = StringOption(
    """
    Title for the document

    This option specifies a title to use instead of the title
    specified in the LaTeX document.

    """,
    options = '--title',
    category = 'document',
)

doc['toc-depth'] = IntegerOption(
    """ Number of levels to display in the table of contents """,
    options = '--toc-depth',
    category = 'document',
    default = 3,
)

doc['toc-non-files'] = BooleanOption(
    """ Display sections that do not create files in the table of contents """,
    options = '--toc-non-files',
    category = 'document',
    default = False,
)

doc['sec-num-depth'] = IntegerOption(
    """ Maximum section depth to display section numbers """,
    options = '--sec-num-depth',
    category = 'document',
    default = 2,
)

doc['index-columns'] = IntegerOption(
    """ Number of columns to split the index entries into """,
    options = '--index-columns',
    category = 'document',
    default = 2,
)

doc['lang-terms'] = StringOption(
    """ Specifies a '%s' delimited list of files that contain language terms """ % os.pathsep,
    options = '--lang-terms',
    category = 'document',
    default = '',
)

config.read('~/.plasTeXrc')
config.read('/usr/local/etc/plasTeXrc')
config.read(os.path.join(os.path.dirname(__file__), 'plasTeXrc'))

del c


text:
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;

#[test]
fn verr_1() {
    run_test(&Instruction { mnemonic: Mnemonic::VERR, operand1: Some(Direct(BP)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 0, 229], OperandSize::Word)
}

#[test]
fn verr_2() {
    run_test(&Instruction { mnemonic: Mnemonic::VERR, operand1: Some(Indirect(SI, Some(OperandSize::Word), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 0, 36], OperandSize::Word)
}

#[test]
fn verr_3() {
    run_test(&Instruction { mnemonic: Mnemonic::VERR, operand1: Some(Direct(BX)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 0, 227], OperandSize::Dword)
}

#[test]
fn verr_4() {
    run_test(&Instruction { mnemonic: Mnemonic::VERR, operand1: Some(IndirectScaledDisplaced(ESI, Two, 1168269032, Some(OperandSize::Word), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 0, 36, 117, 232, 94, 162, 69], OperandSize::Dword)
}

#[test]
fn verr_5() {
    run_test(&Instruction { mnemonic: Mnemonic::VERR, operand1: Some(Direct(DI)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 0, 231], OperandSize::Qword)
}

#[test]
fn verr_6() {
    run_test(&Instruction { mnemonic: Mnemonic::VERR, operand1: Some(IndirectScaledIndexedDisplaced(RDI, RSI, Eight, 1833539953, Some(OperandSize::Word), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 0, 164, 247, 113, 153, 73, 109], OperandSize::Qword)
}


text:
/**
 * @tag controllers, home
 */
jQuery.Controller.extend('single_app_view.Controllers.Main',
/* @Static */
{
	onDocument: true
},
/* @Prototype */
{

 "{window} load": function(params) {

    ACCOUNT = new Account({email: ACCOUNT_ID,
			    account_id: ACCOUNT_ID});

    RecordController = new smart_common.Controllers.Record($("#app_content"));

      var proxied_record = new Record({
          record_id: PROXIED_RECORD_ID,
          label: PROXIED_RECORD_NAME,
          demographics: {}
      });

     RecordController.RECENT_RECORDS[PROXIED_RECORD_ID] = proxied_record;
     OpenAjax.hub.publish("patient_record.selected", PROXIED_RECORD_ID);
     OpenAjax.hub.publish("maincontroller.initialized");
     SMART.launch_app(MANIFEST, get_context(MANIFEST));

}

});


text:
namespace Google.Analytics.Admin.V1Beta.Snippets
{
    // [START analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateProperty_async_flattened]
    using Google.Analytics.Admin.V1Beta;
    using System.Threading.Tasks;

    public sealed partial class GeneratedAnalyticsAdminServiceClientSnippets
    {
        /// <summary>Snippet for CreatePropertyAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public async Task CreatePropertyAsync()
        {
            // Create client
            AnalyticsAdminServiceClient analyticsAdminServiceClient = await AnalyticsAdminServiceClient.CreateAsync();
            // Initialize request argument(s)
            Property property = new Property();
            // Make the request
            Property response = await analyticsAdminServiceClient.CreatePropertyAsync(property);
        }
    }
    // [END analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateProperty_async_flattened]
}


text:
const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const APP = __dirname

module.exports = {
  context: APP,
  entry: {
    ngapp: './ngapp/app.js'
  },
  output: {
    path: './public',
    filename: '[name].js'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract('style-loader', 'css-loader')
      },
      {
        test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/,
        loader: 'file'
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin('style.css')
  ]
}


text:
  Animation duration:
  <input id="duration" value="2000" type="number" min="0" step="100" #duration>

<mat-vertical-stepper [linear]="false" #stepper [animationDuration]="duration.value">
  <mat-step [stepControl]="firstFormGroup">
    <form [formGroup]="firstFormGroup">
      <ng-template matStepLabel>Fill out your name</ng-template>
      <mat-form-field>
        <input matInput placeholder="Last name, First name" formControlName="firstCtrl" required>
      </mat-form-field>

        <button mat-button matStepperNext>Next</button>

    </form>
  </mat-step>
  <mat-step [stepControl]="secondFormGroup">
    <form [formGroup]="secondFormGroup">
      <ng-template matStepLabel>Fill out your address</ng-template>
      <mat-form-field>
        <input matInput placeholder="Address" formControlName="secondCtrl" required>
      </mat-form-field>

        <button mat-button matStepperPrevious>Back</button>
        <button mat-button matStepperNext>Next</button>

    </form>
  </mat-step>
  <mat-step>
    <ng-template matStepLabel>Done</ng-template>
    You are now done.

      <button mat-button matStepperPrevious>Back</button>
      <button mat-button (click)="stepper.reset()">Reset</button>

  </mat-step>
</mat-vertical-stepper>


text:
import random

from axelrod import Player

class MetaPlayer(Player):
    """A generic player that has its own team of players."""

    team = []

    def __init__(self):

        Player.__init__(self)

        # Make sure we don't use any meta players to avoid infinite recursion.
        self.team = [t for t in self.team if not issubclass(t, MetaPlayer)]
        self.nteam = len(self.team)

        # Initiate all the player in out team.
        self.team = [t() for t in self.team]

        # If the team will have stochastic players, this meta is also stochastic.
        self.stochastic = any([t.stochastic for t in self.team])

    def strategy(self, opponent):

        # Make sure the history of all hunters is current.
        for ih in range(len(self.team)):
            self.team[ih].history = self.history

        # Get the results of all our players.
        results = [player.strategy(opponent) for player in self.team]

        # A subclass should just define a way to choose the result based on team results.
        return self.meta_strategy(results)

    def meta_strategy(self, results):
        """Determine the meta result based on results of all players."""
        pass

class MetaMajority(MetaPlayer):
    """A player who goes by the majority vote of all other non-meta players."""

    name = "Meta Majority"

    def __init__(self):

        # We need to import the list of strategies at runtime, since
        # _strategies import also _this_ module before defining the list.
        from _strategies import ordinary_strategies
        self.team = ordinary_strategies

        MetaPlayer.__init__(self)

    def meta_strategy(self, results):
        if results.count('D') > results.count('C'):
            return 'D'
        return 'C'

class MetaMinority(MetaPlayer):
    """A player who goes by the minority vote of all other non-meta players."""

    name = "Meta Minority"

    def __init__(self):

        # We need to import the list of strategies at runtime, since
        # _strategies import also _this_ module before defining the list.
        from _strategies import ordinary_strategies
        self.team = ordinary_strategies

        MetaPlayer.__init__(self)

    def meta_strategy(self, results):
        if results.count('D') < results.count('C'):
            return 'D'
        return 'C'

class MetaWinner(MetaPlayer):
    """A player who goes by the strategy of the current winner."""

    name = "Meta Winner"

    def __init__(self, team=None):

        # The default is to used all strategies available, but we need to import the list
        # at runtime, since _strategies import also _this_ module before defining the list.
        if team:
            self.team = team
        else:
            from _strategies import ordinary_strategies
            self.team = ordinary_strategies

        MetaPlayer.__init__(self)

        # For each player, we will keep the history of proposed moves and
        # a running score since the beginning of the game.
        for t in self.team:
            t.proposed_history = []
            t.score = 0

    def strategy(self, opponent):

        # Update the running score for each player, before determining the next move.
        if len(self.history):
            for player in self.team:
                pl_C = player.proposed_history[-1] == "C"
                opp_C = opponent.history[-1] == "C"
                s = 2 * (pl_C and opp_C) or 5 * (pl_C and not opp_C) or 4 * (not pl_C and not opp_C) or 0
                player.score += s

        return MetaPlayer.strategy(self, opponent)

    def meta_strategy(self, results):

        scores = [pl.score for pl in self.team]
        bestscore = min(scores)
        beststrategies = [i for i, pl in enumerate(self.team) if pl.score == bestscore]
        bestproposals = [results[i] for i in beststrategies]
        bestresult = "C" if "C" in bestproposals else "D"

        # Update each player's proposed history with his proposed result, but always after
        # the new result has been settled based on scores accumulated until now.
        for r, t in zip(results, self.team):
            t.proposed_history.append(r)

        return bestresult


text:
package com.lanyotech.pps.domain;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import com.easyjf.beans.BeanUtils;
import com.easyjf.container.annonation.POLoad;
import com.easyjf.util.CommUtil;
import com.easyjf.web.ajax.IJsonObject;
@Entity
@Table(name = "stockoutcome")
public class StockOutcome implements IJsonObject {
	@Id
	@GeneratedValue(strategy = GenerationType.TABLE)
	private Long id;
	@Column(unique = true)
	private String sn;
	/**
	 * 0-销售出库单,1-生产领料单,2-其它出库单
	 */
	private Integer types;
	@ManyToOne(fetch=FetchType.LAZY)
	@POLoad
	private Client client;
	@ManyToOne(fetch=FetchType.LAZY)
	@POLoad
	private Depot depot;
	@ManyToOne(fetch=FetchType.LAZY)
	@POLoad
	private Employee keeper;
	private Date vdate;
	private Date inputTime=new Date();
	@ManyToOne(fetch = FetchType.LAZY)
	private Employee inputUser;
	private String remark;
	private BigDecimal saleAmount;
	private BigDecimal amount;
	private Boolean auditing;
	@ManyToOne(fetch=FetchType.LAZY)
	@POLoad
	private Employee auditor;
	private Date auditTime;
	@OneToMany(cascade = CascadeType.ALL, mappedBy = "bill")
	private List<StockOutcomeItem> items = new java.util.ArrayList<StockOutcomeItem>();
	private Integer status;

	public Object toJSonObject() {
		Map map=CommUtil.obj2mapExcept(this, new String[]{"client","keeper","depot","auditor","inputUser","items"});
		if(client!=null){
			map.put("client", CommUtil.obj2map(client, new String[]{"id","name"}));
		}
		if(keeper!=null){
			map.put("keeper", CommUtil.obj2map(keeper, new String[]{"id","name","trueName"}));
		}
		if(auditor!=null){
			map.put("auditor", CommUtil.obj2map(auditor, new String[]{"id","name","trueName"}));
		}
		if(inputUser!=null){
			map.put("inputUser", CommUtil.obj2map(inputUser, new String[]{"id","name","trueName"}));
		}
		if(depot!=null){
			map.put("depot", CommUtil.obj2map(depot, new String[]{"id","name"}));
		}
		return map;
	}
	public Object toJSonObjectWithItems() {
		Map map=(Map)this.toJSonObject();
		if(items!=null && !items.isEmpty()){
			List list=new ArrayList();
			for(StockOutcomeItem item:items){
				list.add(item.toJSonObject());
			}
			map.put("items", list);
		}
		return map;
	}
	public Long getId() {
		return id;
	}
	public String getSn() {
		return sn;
	}
	public Client getClient() {
		return client;
	}
	public Depot getDepot() {
		return depot;
	}
	public Date getVdate() {
		return vdate;
	}
	public String getRemark() {
		return remark;
	}

	public Boolean getAuditing() {
		return auditing;
	}
	public Employee getAuditor() {
		return auditor;
	}
	public Date getAuditTime() {
		return auditTime;
	}
	public List<StockOutcomeItem> getItems() {
		return items;
	}
	public Integer getStatus() {
		return status;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public void setSn(String sn) {
		this.sn = sn;
	}
	public void setClient(Client client) {
		this.client = client;
	}
	public void setDepot(Depot depot) {
		this.depot = depot;
	}
	public void setVdate(Date vdate) {
		this.vdate = vdate;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}

	public void setAuditing(Boolean auditing) {
		this.auditing = auditing;
	}
	public void setAuditor(Employee auditor) {
		this.auditor = auditor;
	}
	public void setAuditTime(Date auditTime) {
		this.auditTime = auditTime;
	}
	public void setItems(List<StockOutcomeItem> items) {
		this.items = items;
	}
	public void setStatus(Integer status) {
		this.status = status;
	}
	public BigDecimal getAmount() {
		return amount;
	}
	public void setAmount(BigDecimal amount) {
		this.amount = amount;
	}
	public Integer getTypes() {
		return types;
	}
	public Employee getKeeper() {
		return keeper;
	}
	public void setTypes(Integer types) {
		this.types = types;
	}
	public void setKeeper(Employee keeper) {
		this.keeper = keeper;
	}
	public BigDecimal getSaleAmount() {
		return saleAmount;
	}
	public void setSaleAmount(BigDecimal saleAmount) {
		this.saleAmount = saleAmount;
	}

	public Date getInputTime() {
		return inputTime;
	}
	public Employee getInputUser() {
		return inputUser;
	}
	public void setInputTime(Date inputTime) {
		this.inputTime = inputTime;
	}
	public void setInputUser(Employee inputUser) {
		this.inputUser = inputUser;
	}
	public void countAmount(){
		java.math.BigDecimal s=new BigDecimal(0);
		if(items!=null&&items.size()>0){
			for(StockOutcomeItem it:this.getItems()){
				if(it.getAmount()!=null)s=s.add(it.getAmount());
			}
		}
		this.amount=s;
	}
	public List<Long> updateItems(List<StockOutcomeItem> newItems) {
		List<Long> deletes = new java.util.ArrayList<Long>();
		for (StockOutcomeItem flow : this.items) {
			boolean exist = false;
			for (StockOutcomeItem f : newItems) {
				if (f.getId() != null) {
					if (f.getId().equals(flow.getId())) {
						exist = true;
						break;
					}
				}
			}
			if (!exist)
				deletes.add(flow.getId());
		}
		for (int i = 0; i < deletes.size(); i++) {
			this.removeItem((Long) deletes.get(i));
		}

		for (StockOutcomeItem flow : newItems) {
			StockOutcomeItem item = null;
			if (flow.getId() != null) {
				item = getItem(flow.getId());
			}
			if (item != null) {
				Long id = item.getId();
				BeanUtils.copyProperties(flow, item);
				item.setId(id);
				item.setBill(this);
			} else
				addItem(flow);
		}
		return deletes;
	}

	public StockOutcomeItem getItem(Long itemId) {
		StockOutcomeItem item = null;
		for (StockOutcomeItem i : items) {
			if (i != null && itemId.equals(i.getId())) {
				item = i;
				break;
			}
		}
		return item;
	}

	public void addItem(StockOutcomeItem item) {
		item.setBill(this);
		this.items.add(item);
	}

	public void removeItem(Long itemId) {
		StockOutcomeItem p = getItem(itemId);
		if (p != null) {
			p.setBill(null);
			this.items.remove(p);
		}
	}
}


text:
$computer = read-host 'Enter server name'
$database = read-host 'Enter database name'
$backupName = read-host 'Enter backup name'
$backupFolder = read-host 'Enter remote folder for backup'
$timestamp = (Get-Date).ToString("yyyyMMddHHmm")
$fullBackupName = "$backupFolder\" + $backupName + "_$timestamp.bak"
$credential = read-host 'Enter user name'
$params = $database,$computer,$fullBackupName

$backupScript = {
    param([string[]]$params)
    $database = $params[0]
    $computer = $params[1]
    $fullBackupName = $params[2]
    Write-Host "Logged in to server $computer"
    Write-Host "Server: $computer"
    Write-Host "Database: $database"
    Write-Host "Backup location: $fullBackupName"
    import-Module SQLPS
    Backup-SqlDatabase -ServerInstance $computer -Database $database -BackupFile $fullBackupName
}

invoke-command -computername $computer -scriptblock $backupScript -ArgumentList (,$params) -Credential $credential


text:
'''
Created on 08.02.2016.

@author: Lazar
'''

class Sidebar(object):
    '''
    classdocs
    '''

    def __init__(self, links, parent, color, name):
        self.links = links
        self.parent = parent
        self.color = color
        self.name = name


text:
<?php

namespace Illarra\CoreBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;

class IllarraCoreExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');

        // Set parameters
        $container->setParameter('illarra_core.locales', $config['locales']);
        $container->setParameter('illarra_core.default_locale', $config['default_locale']);
        $container->setParameter('illarra_core.available_locales', $config['available_locales']);
        $container->setParameter('illarra_core.active_locales', $config['active_locales']);
        $container->setParameter('illarra_core.admin.entities_per_page', $config['admin']['entities_per_page']);
        $container->setParameter('illarra_core.admin.locale', $config['admin']['locale']);
    }
}


text:
define([
    'jquery',
    'backbone',
    'find/app/page/search/related-concepts/related-concepts-view',
    'find/app/model/entity-collection',
    'underscore',
    'jasmine-jquery'
], function($, Backbone, RelatedConceptsView, EntityCollection, _) {
    'use strict';

    describe('Related concepts view', function() {
        function createView() {
            this.clickHandler = jasmine.createSpy('clickHandler');

            this.view = new RelatedConceptsView({
                entityCollection: this.entityCollection,
                indexesCollection: this.indexesCollection,
                queryModel: this.queryModel,
                clickHandler: this.clickHandler,
                queryState: {
                    conceptGroups: this.conceptGroups
                }
            });

            this.view.render();
        }

        beforeEach(function() {
            this.indexesCollection = new Backbone.Collection();
            this.queryModel = new Backbone.Model();

            this.conceptGroups = new Backbone.Collection([
                {concepts: ['orange']},
                {concepts: ['blood']}
            ]);

            this.entityCollection = new EntityCollection([], {
                getSelectedRelatedConcepts: _.constant([])
            });
        });

        describe('created before the indexes collection has fetched', function() {
            beforeEach(createView);

            it('displays the "not loading" text', function() {
                expect(this.view.$('.related-concepts-not-loading')).not.toHaveClass('hide');
            });

            it('does not display the related concepts list', function() {
                expect(this.view.$('.related-concepts-list')).toHaveClass('hide');
            });

            it('does not show the loading indicator', function() {
                expect(this.view.$('.related-concepts-processing')).toHaveClass('hide');
            });

            it('does not show the error message', function() {
                expect(this.view.$('.related-concepts-error')).toHaveClass('hide');
            });

            it('does not show the empty message', function() {
                expect(this.view.$('.related-concepts-none')).toHaveClass('hide');
            });
        });

        describe('created after the indexes collection and the related concept have fetched', function() {
            beforeEach(function() {
                this.indexesCollection.set([{name: 'Wikipedia'}]);

                this.entityCollection.set([
                    {cluster: 0, text: 'fruit'},
                    {cluster: 0, text: 'juice'},
                    {cluster: 1, text: 'red'},
                    {cluster: 1, text: 'blood'},
                    {cluster: 2, text: 'orange'}
                ], {parse: true});

                createView.call(this);
            });

            it('displays the related concepts list', function() {
                expect(this.view.$('.related-concepts-list')).not.toHaveClass('hide');
            });

            it('does not show the loading indicator', function() {
                expect(this.view.$('.related-concepts-processing')).toHaveClass('hide');
            });

            it('does not show the "not loading" text', function() {
                expect(this.view.$('.related-concepts-not-loading')).toHaveClass('hide');
            });

            it('does not show the error message', function() {
                expect(this.view.$('.related-concepts-error')).toHaveClass('hide');
            });

            it('does not show the empty message', function() {
                expect(this.view.$('.related-concepts-none')).toHaveClass('hide');
            });

            it('only renders one loading spinner when multiple request events are triggered', function() {
                this.entityCollection.trigger('request');
                this.entityCollection.trigger('request');

                expect(this.view.$('.loading-spinner')).toHaveLength(1);
            });
        });

        describe('created after the indexes collection has fetched but before the related concepts have fetched', function() {
            beforeEach(function() {
                this.indexesCollection.set([{name: 'Wikipedia'}]);

                createView.call(this);
            });

            it('displays the loading indicator', function() {
                expect(this.view.$('.related-concepts-processing')).not.toHaveClass('hide');
            });

            it('does not display the related concepts list', function() {
                expect(this.view.$('.related-concepts-list')).toHaveClass('hide');
            });

            it('does not show the "not loading" text', function() {
                expect(this.view.$('.related-concepts-not-loading')).toHaveClass('hide');
            });

            it('does not show the error message', function() {
                expect(this.view.$('.related-concepts-error')).toHaveClass('hide');
            });

            it('does not show the empty message', function() {
                expect(this.view.$('.related-concepts-none')).toHaveClass('hide');
            });

            describe('after the related concepts have fetched', function() {
                beforeEach(function() {
                    this.entityCollection.reset([
                        {cluster: 0, text: 'fruit'},
                        {cluster: -1, text: 'bromine'},
                        {cluster: 0, text: 'juice'},
                        {cluster: 1, text: 'red'},
                        {cluster: 0, text: 'squeeze'}
                    ], {parse: true});
                });

                it('displays the related concepts list', function() {
                    expect(this.view.$('.related-concepts-list')).not.toHaveClass('hide');
                });

                it('hides the loading indicator', function() {
                    expect(this.view.$('.related-concepts-processing')).toHaveClass('hide');
                });

                it('does not show the "not loading" text', function() {
                    expect(this.view.$('.related-concepts-not-loading')).toHaveClass('hide');
                });

                it('does not show the error message', function() {
                    expect(this.view.$('.related-concepts-error')).toHaveClass('hide');
                });

                it('does not show the empty message', function() {
                    expect(this.view.$('.related-concepts-none')).toHaveClass('hide');
                });

                it('does not render items with a negative cluster', function() {
                    expect(this.view.$('.related-concepts-list')).not.toContainText('bromine');
                });

                it('does not contain selected related concept', function() {
                    expect(this.view.$('.related-concepts-list')).not.toContainText('blood');
                });

                it('does not contain query text', function() {
                    expect(this.view.$('.related-concepts-list')).not.toContainText('orange');
                });

                it('renders each item in a non-negative cluster with other members of the cluster, taking the first member as the heading', function() {
                    var $clusterLis = this.view.$('.related-concepts-list > li');
                    expect($clusterLis).toHaveLength(2);

                    var $fruitCluster = $clusterLis.eq(0);
                    expect($fruitCluster.find('h4')).toHaveText('fruit');
                    expect($fruitCluster.find('li')).toHaveLength(3);
                    expect($fruitCluster.find('li:nth-child(1)')).toHaveText('fruit');
                    expect($fruitCluster.find('li:nth-child(2)')).toHaveText('juice');
                    expect($fruitCluster.find('li:nth-child(3)')).toHaveText('squeeze');

                    var $colourCluster = $clusterLis.eq(1);
                    expect($colourCluster.find('h4')).toHaveText('red');
                    expect($colourCluster.find('li')).toHaveLength(0);
                });

                describe('when a cluster heading is clicked', function() {
                    beforeEach(function() {
                        // Click a child of the heading to check that click events propagate correctly (a previous bug)
                        this.view.$('.related-concepts-list > li:nth-child(1) h4 > a *').click();
                    });

                    it('calls the clickHandler with every item in the cluster', function() {
                        expect(this.clickHandler).toHaveBeenCalledWith([
                            'fruit',
                            'juice',
                            'squeeze'
                        ]);
                    });
                });

                describe('when a cluster child is clicked', function() {
                    beforeEach(function() {
                        this.view.$('.related-concepts-list > li:nth-child(1) li:nth-child(1) .entity-text').click();
                    });

                    it('calls the click handler with an array containing the clicked item', function() {
                        expect(this.clickHandler).toHaveBeenCalledWith([
                            'fruit'
                        ]);
                    });
                });
            });
        });
    });
});


text:
import reducer from '.'

const initialState = {
  attentionBoxVisible: true,
}

describe('ui', () => {
  it('should return the initial state', () => {
    const next = reducer(initialState, {})
    expect(next).toEqual(initialState)
  })

  it('should return the initial state', () => {
    expect(
      reducer(initialState, { type: 'UI_ATTENTIONBOX_TOGGLE' })
    ).toEqual(
      {
        attentionBoxVisible: false,
      },
    )
  })

  it('UI_ATTENTIONBOX_TOGGLE', () => {
    const next = reducer(initialState, { type: 'UI_ATTENTIONBOX_TOGGLE' })
    expect(next).toMatchSnapshot()
  })
})


text:
package io.webfolder.cdp.type.constant;

import com.google.gson.annotations.SerializedName;

public enum PortraitType {
    @SerializedName("portraitPrimary")
    PortraitPrimary("portraitPrimary"),

    @SerializedName("portraitSecondary")
    PortraitSecondary("portraitSecondary"),

    @SerializedName("landscapePrimary")
    LandscapePrimary("landscapePrimary"),

    @SerializedName("landscapeSecondary")
    LandscapeSecondary("landscapeSecondary");

    public final String value;

    PortraitType(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return value;
    }
}


text:
<?php

namespace Acquia\Hmac\Test\Symfony;

use Acquia\Hmac\KeyInterface;
use Acquia\Hmac\Symfony\HmacToken;
use Symfony\Component\HttpFoundation\Request;
use PHPUnit\Framework\TestCase;

/**
 * Tests the Symfony authentication token.
 */
class HmacTokenTest extends TestCase
{
    /**
     * Ensures the getters work as expected.
     */
    public function testGetters()
    {
        $request = $this->createMock(Request::class);
        $key = $this->createMock(KeyInterface::class);

        $token = new HmacToken($request, $key);

        $this->assertEquals($request, $token->getRequest());
        $this->assertEquals($key, $token->getCredentials());
    }
}


text:
'use strict'

var expect = require('expect.js')
  , Query = require('./query')

describe('Query', function() {
  describe('.aggregation()', function() {
    it('should create spec', function() {
      var spec = Query.aggregation('count', 'output')

      expect(spec.type).to.be('count')
      expect(spec.name).to.be('output')
    })

    it('should create spec using raw object', function() {
      var spec = Query.aggregation({type: 'count', name: 'output'})

      expect(spec.type).to.be('count')
      expect(spec.name).to.be('output')
    })

    it('should throw error for missing type', function() {
      expect(function() {
        Query.aggregation('missing', 'aggregation')
      }).to.throwException()
    })

    it('should throw error for missing name', function() {
      expect(function() {
        Query.aggregation('count')
      }).to.throwException()
    })
  })

  describe('#aggregation()', function() {
    var query

    beforeEach(function() {
      query = new Query()
    })

    it('should add spec to aggregations', function() {
      query.aggregation('count', 'output')
      var raw = query.toJSON()

      expect(raw.aggregations).to.have.length(1)
      expect(raw.aggregations[0].type).to.be('count')
      expect(raw.aggregations[0].name).to.be('output')
    })

    it('should add raw spec to aggregations', function() {
      query.aggregation({type: 'count', name: 'output'})
      var raw = query.toJSON()

      expect(raw.aggregations).to.be.an(Array)
      expect(raw.aggregations).to.have.length(1)
      expect(raw.aggregations[0].type).to.be('count')
      expect(raw.aggregations[0].name).to.be('output')
    })
  })
})


text:
from numpy import array
from math import sqrt
import numpy as np
import csv

import pyvision as pv

class Point:
    def __init__(self,x=0.0,y=0.0,z=0.0,w=1.0,scale=1.0,rotation=0.0):
        '''
        Create a point.

        Arguments:
        x: x coordinate
        y: y coordinate
        z: z coordinate
        w: homoginious coordinate
        scale: scale selection
        rotation: rotation selection
        '''
        if isinstance(x,tuple):
            # Initialize from a tuple
            self.x = float(x[0])
            self.y = float(x[1])
            self.z = 0.0
            self.w = 1.0
            if len(x) > 2:
                self.z = x[3]
            if len(x) > 3:
                self.w = x[4]
        else:
            # Initialize from coordinates.
            self.x = float(x)
            self.y = float(y)
            self.z = float(z)
            self.w = float(w)
            self.scale = scale
            self.rotation = rotation

    def X(self):
        '''Return the x coordiante.'''
        return float(self.x)/self.w

    def Y(self):
        '''Return the y coordinate.'''
        return float(self.y)/self.w

    def Z(self):
        '''Return the z coordinate.'''
        return float(self.z)/self.w

    def asArray(self,homogenious=False):
        '''
        returns the point data as a 4 element numpy array.

        if 'homogenious' == True: returns x,y,z,w
        else: return x,y,z,1.0
        '''
        if homogenious:
            return array([self.X(),self.Y(),self.Z(),1.0])
        else:
            return array([self.X(),self.Y(),self.Z(),1.0])

    def asVector2H(self):
        ''' Return a 2D homogenious vector [x,y,w] '''
        return array([[self.x],[self.y],[self.w]])

    def asVector3H(self):
        ''' Return a 3D homogenious vector [x,y,z,w] '''
        return array([[self.x],[self.y],[self.z],[self.w]])

    def asOpenCV(self):
        '''Return as a point compatible with OpenCV'''
        return (self.X(), self.Y()) #cv.cvPoint(int(round(self.X())),int(round(self.Y())))

    def asTuple(self):
        '''Return as a 2 tuple.'''
        return (self.X(),self.Y())

    def asArray3D(self):
        '''Return as an array of three elements.'''
        return np.array((self.X(),self.Y(),self.Z()))

    def asSpherical(self):
        '''
        Computes and returns a representation of this point in spherical coordinates: (r,phi,theta).

        r = radius or distance of the point from the origin.
        phi = is the angle of the projection on the xy plain and the x axis
        theta = is the angle with the z axis.

        x = r*cos(phi)*sin(theta)
        y = r*sin(phi)*sin(theta)
        z = r*cos(theta)
        '''
        x,y,z,_ = self.asArray()

        r = np.sqrt(x**2+y**2+z**2)
        phi = np.arctan2(y,x)
        theta = np.arctan2(np.sqrt(x**2+y**2),z)

        return r,phi,theta

    def l2(self,point):
        ''' Compute the Euclidian distance between two points. '''
        dx = self.X()-point.X()
        dy = self.Y()-point.Y()
        dz = self.Z()-point.Z()

        return sqrt(dx*dx + dy*dy + dz*dz)

    def unit(self):
        '''
        Returns a vector in the same direction but of unit length.
        '''
        x = self.X()
        y = self.Y()
        z = self.Z()
        l = np.sqrt(x*x+y*y+z*z)
        if l < 0.000001:
            # Point is at 0,0,0
            return pv.Point(0,0,0)

        return (1.0/l)*self

    def magnitude(self):
        ''' Compute the magnitude of the point (distance from origin). '''
        x = self.X()
        y = self.Y()
        z = self.Z()

        return np.sqrt(x**2+y**2+z**2)

    def __sub__(self,point):
        ''' Subtract two points '''
        return Point(self.X()-point.X(),self.Y()-point.Y(),self.Z()-point.Z())

    def __add__(self,point):
        ''' Add two points. '''
        return Point(self.X()+point.X(),self.Y()+point.Y(),self.Z()+point.Z())

    def __mul__(self,val):
        ''' Multiply the point by a value. '''
        if isinstance(val,float) or isinstance(val,int):
            return Point(self.X()*val,self.Y()*val,self.Z()*val)

    def __rmul__(self,val):
        ''' Multiply the point by a value. '''
        if isinstance(val,float) or isinstance(val,int):
            return Point(self.X()*val,self.Y()*val,self.Z()*val)

    def __str__(self):
        ''' Return a string representing the point. '''
        return "pv.Point(%f,%f,%f)"%(self.X(),self.Y(),self.Z())

    def __repr__(self):
        ''' Return a string representing the point. '''
        return "pv.Point(%f,%f,%f)"%(self.X(),self.Y(),self.Z())

def readPointsFile(filename):
    '''
    This function reads a points file that was created by the EyePicker
    application. EyePicker produces a csv file where each line corresponds
    to a file and can contain a number of points.

    This function returns a dictionary where the key is the filename and
    each entry contains a list of points.
    '''
    f = csv.reader(open(filename,'rb'))

    result = {}

    for row in f:
        fname = row[0]

        row = row[1:]

        # Make sure the number of values is even
        assert len(row) % 2 == 0

        points = []
        for i in range(0,len(row),2):
            x = float(row[i])
            y = float(row[i+1])
            points.append(Point(x,y))

        result[fname] = points

    return result


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

using Rotativa.NetCore.Options;

namespace Rotativa.NetCore
{
    public abstract class AsResultBase : ActionResult
    {
        protected AsResultBase()
        {
            this.WkhtmlPath = string.Empty;
            this.FormsAuthenticationCookieName = ".ASPXAUTH";
        }

        /// <summary>
        /// This will be send to the browser as a name of the generated PDF file.
        /// </summary>
        public string FileName { get; set; }

        /// <summary>
        /// Path to wkhtmltopdf\wkhtmltoimage binary.
        /// </summary>
        public string WkhtmlPath { get; set; }

        /// <summary>
        /// Custom name of authentication cookie used by forms authentication.
        /// </summary>
        [Obsolete("Use FormsAuthenticationCookieName instead of CookieName.")]
        public string CookieName
        {
            get => this.FormsAuthenticationCookieName;
            set => this.FormsAuthenticationCookieName = value;
        }

        /// <summary>
        /// Custom name of authentication cookie used by forms authentication.
        /// </summary>
        public string FormsAuthenticationCookieName { get; set; }

        /// <summary>
        /// Sets custom headers.
        /// </summary>
        [OptionFlag("--custom-header")]
        public Dictionary<string, string> CustomHeaders { get; set; }

        /// <summary>
        /// Sets cookies.
        /// </summary>
        [OptionFlag("--cookie")]
        public Dictionary<string, string> Cookies { get; set; }

        /// <summary>
        /// Sets post values.
        /// </summary>
        [OptionFlag("--post")]
        public Dictionary<string, string> Post { get; set; }

        /// <summary>
        /// Indicates whether the page can run JavaScript.
        /// </summary>
        [OptionFlag("-n")]
        public bool IsJavaScriptDisabled { get; set; }

        /// <summary>
        /// Minimum font size.
        /// </summary>
        [OptionFlag("--minimum-font-size")]
        public int? MinimumFontSize { get; set; }

        /// <summary>
        /// Sets proxy server.
        /// </summary>
        [OptionFlag("-p")]
        public string Proxy { get; set; }

        /// <summary>
        /// HTTP Authentication username.
        /// </summary>
        [OptionFlag("--username")]
        public string UserName { get; set; }

        /// <summary>
        /// HTTP Authentication password.
        /// </summary>
        [OptionFlag("--password")]
        public string Password { get; set; }

        /// <summary>
        /// Use this if you need another switches that are not currently supported by Rotativa.
        /// </summary>
        [OptionFlag("")]
        public string CustomSwitches { get; set; }

        public string SaveOnServerPath { get; set; }

        protected abstract string GetUrl(ActionContext context);

        /// <summary>
        /// Returns properties with OptionFlag attribute as one line that can be passed to wkhtmltopdf binary.
        /// </summary>
        /// <returns>Command line parameter that can be directly passed to wkhtmltopdf binary.</returns>
        protected virtual string GetConvertOptions()
        {
            var result = new StringBuilder();

            var fields = this.GetType().GetProperties();
            foreach (var fi in fields)
            {
                var of = fi.GetCustomAttributes(typeof(OptionFlag), true).FirstOrDefault() as OptionFlag;
                if (of == null)
                    continue;

                object value = fi.GetValue(this, null);
                if (value == null)
                    continue;

                if (fi.PropertyType == typeof(Dictionary<string, string>))
                {
                    var dictionary = (Dictionary<string, string>)value;
                    foreach (var d in dictionary)
                    {
                        result.AppendFormat(" {0} {1} {2}", of.Name, d.Key, d.Value);
                    }
                }
                else if (fi.PropertyType == typeof(bool))
                {
                    if ((bool)value)
                        result.AppendFormat(CultureInfo.InvariantCulture, " {0}", of.Name);
                }
                else
                {
                    result.AppendFormat(CultureInfo.InvariantCulture, " {0} {1}", of.Name, value);
                }
            }

            return result.ToString().Trim();
        }

        private string GetWkParams(ActionContext context)
        {
            var switches = string.Empty;

            var cookieOptions = context.HttpContext.RequestServices.GetService<IOptions<CookieAuthenticationOptions>>();

            if (cookieOptions.Value != null && !String.IsNullOrEmpty(cookieOptions.Value.CookieName))
            {
                var cookieName = cookieOptions.Value.CookieName;

                string authenticationCookie = null;
                if (context.HttpContext.Request.Cookies != null && context.HttpContext.Request.Cookies.ContainsKey(cookieName))
                {
                    authenticationCookie = context.HttpContext.Request.Cookies[cookieName];
                }
                if (authenticationCookie != null)
                {
                    var authCookieValue = authenticationCookie;
                    switches += " --cookie " + this.FormsAuthenticationCookieName + " " + authCookieValue;
                }
            }

            switches += " " + this.GetConvertOptions();

            var url = this.GetUrl(context);
            switches += " " + url;

            return switches;
        }

        protected virtual byte[] CallTheDriver(ActionContext context)
        {
            var switches = this.GetWkParams(context);
            var fileContent = this.WkhtmlConvert(switches);
            return fileContent;
        }

        protected abstract byte[] WkhtmlConvert(string switches);

        public byte[] BuildFile(ActionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (this.WkhtmlPath == string.Empty)
            {
                var location = Assembly.GetEntryAssembly().Location;
                var directory = Path.GetDirectoryName(location);
                this.WkhtmlPath = Path.Combine(directory, "Rotativa");
            }

            var fileContent = this.CallTheDriver(context);

            if (string.IsNullOrEmpty(this.SaveOnServerPath) == false)
            {
                File.WriteAllBytes(this.SaveOnServerPath, fileContent);
            }

            return fileContent;
        }

        public override void ExecuteResult(ActionContext context)
        {
            var fileContent = this.BuildFile(context);

            var response = this.PrepareResponse(context.HttpContext.Response);

            response.Body.Write(fileContent, 0, fileContent.Length);
        }

        private static string SanitizeFileName(string name)
        {
            string invalidChars = Regex.Escape(new string(Path.GetInvalidPathChars()) + new string(Path.GetInvalidFileNameChars()));
            string invalidCharsPattern = string.Format(@"[{0}]+", invalidChars);

            string result = Regex.Replace(name, invalidCharsPattern, "_");
            return result;
        }

        protected HttpResponse PrepareResponse(HttpResponse response)
        {
            response.ContentType = this.GetContentType();

            if (!string.IsNullOrEmpty(this.FileName))
            {
                response.Headers.Add("Content-Disposition", string.Format("attachment; filename=\"{0}\"", SanitizeFileName(this.FileName)));
            }

            return response;
        }

        protected abstract string GetContentType();
    }
}


text:
require 'rails_helper'

RSpec.describe ArticleStaleWorker, type: :worker do
  it "sends an ArticleMailer" do
    article = create(:article, :stale)

    mailer = class_double(ArticleMailer, deliver: true)

    expect(ArticleMailer).to receive(:send_staleness_notification_for)
      .with([article]).and_return(mailer)

    described_class.perform_async([article.id])
  end
end


text:
<resources>
    <declare-styleable name="AspectRatioLayout">
        <attr name="ratio_width" format="float"/>
        <attr name="ratio_height" format="float"/>
    </declare-styleable>
    <attr name="detail_even_row_color" format="reference"/>
    <attr name="detail_odd_row_color" format="reference"/>
    <attr name="entity_view_header_background_color" format="reference"/>
    <attr name="entity_view_header_text_color" format="reference"/>
    <attr name="searchbox_action_bar_color" format="reference"/>
    <attr name="drawer_pulldown_text_color" format="reference"/>
    <attr name="drawer_pulldown_even_row_color" format="reference"/>
    <attr name="drawer_pulldown_odd_row_color" format="reference"/>
    <attr name="menu_tile_title_text_color" format="reference"/>
    <attr name="entity_select_title_text_color" format="reference"/>

    <attr name="backgroundColor" format="reference|color"/>
    <attr name="subtitle" format="string"/>
    <attr name="img" format="reference"/>
    <attr name="textColor" format="reference|color"/>

    <declare-styleable name="ShrinkingLinearLayout">
        <attr name="shrinkable_view" format="reference"/>
    </declare-styleable>

    <declare-styleable name="CustomButtonWithText">
        <attr name="backgroundColor"/>
        <attr name="subtitle"/>
        <attr name="img"/>
        <attr name="textColor"/>
    </declare-styleable>

    <declare-styleable name="ResizingTextView">
        <attr name="text_size_small" format="reference|dimension"/>
    </declare-styleable>

    <attr name="filter_select_background_color" format="reference"/>
    <attr name="filter_select_text_color" format="reference"/>

    <declare-styleable name="TabbedDetailView">
        <attr name="even_row_color" format="reference|color"/>
        <attr name="odd_row_color" format="reference|color"/>
    </declare-styleable>

    <declare-styleable name="ClippingView">
        <attr name="clip_start_x" format="reference|float"/>
        <attr name="clip_start_y" format="reference|float"/>
        <attr name="clip_width" format="reference|float"/>
        <attr name="clip_height" format="reference|float"/>
    </declare-styleable>

    <declare-styleable name="FilePreference">
        <attr name="file_type" format="string"/>
    </declare-styleable>

</resources>


text:
using System.Reflection;

namespace ArguMint.TestCommon.Helpers
{
   public static class ObjectExtensions
   {
      public static object Property( this object obj, string propertyName )
      {
         var propertyInfo = obj.GetType().GetProperty( propertyName, BindingFlags.Public | BindingFlags.Instance );
         return propertyInfo.GetValue( obj );
      }
   }
}


text:
// Copyright 2020 Google LLC
// 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.

/*! THIS FILE IS AUTO-GENERATED */

import {AuthPlus, getAPI, GoogleConfigurable} from 'googleapis-common';
import {gmailpostmastertools_v1} from './v1';
import {gmailpostmastertools_v1beta1} from './v1beta1';

export const VERSIONS = {
  v1: gmailpostmastertools_v1.Gmailpostmastertools,
  v1beta1: gmailpostmastertools_v1beta1.Gmailpostmastertools,
};

export function gmailpostmastertools(
  version: 'v1'
): gmailpostmastertools_v1.Gmailpostmastertools;
export function gmailpostmastertools(
  options: gmailpostmastertools_v1.Options
): gmailpostmastertools_v1.Gmailpostmastertools;
export function gmailpostmastertools(
  version: 'v1beta1'
): gmailpostmastertools_v1beta1.Gmailpostmastertools;
export function gmailpostmastertools(
  options: gmailpostmastertools_v1beta1.Options
): gmailpostmastertools_v1beta1.Gmailpostmastertools;
export function gmailpostmastertools<
  T =
    | gmailpostmastertools_v1.Gmailpostmastertools
    | gmailpostmastertools_v1beta1.Gmailpostmastertools
>(
  this: GoogleConfigurable,
  versionOrOptions:
    | 'v1'
    | gmailpostmastertools_v1.Options
    | 'v1beta1'
    | gmailpostmastertools_v1beta1.Options
) {
  return getAPI<T>('gmailpostmastertools', versionOrOptions, VERSIONS, this);
}

const auth = new AuthPlus();
export {auth};
export {gmailpostmastertools_v1};
export {gmailpostmastertools_v1beta1};
export {
  AuthPlus,
  GlobalOptions,
  APIRequestContext,
  GoogleConfigurable,
  StreamMethodOptions,
  GaxiosPromise,
  MethodOptions,
  BodyResponseCallback,
} from 'googleapis-common';


text:
Supports multiple modes, you can keep main configuration on one mode but for testing(or environment dependent features) have another mode with limited number of dependencies which will override the ones from first mode.

DI container will search for a requested dependency in configured mode and will look in other mod's configurations in case if requested dependency will not be found.

## Usage example:
```
node sample.js
```

## Installation
```
npm install -s simple-mdi
```

## Running tests
```
npm test
```