text:
import logging
import math
import functools

"""A coordinate of a station precision of which we must take into account
is calculated as an average of somewhat 10 elements.
Taking machine epsilon 1e-15, averaging 10 numbers with close magnitudes
ensures relative precision of 1e-14."""
coord_isclose = functools.partial(math.isclose, rel_tol=1e-14)

def coords_eq(lon1, lat1, lon2, lat2):
    return coord_isclose(lon1, lon2) and coord_isclose(lat1, lat2)

def osm_id_comparator(el):
    """This function is used as key for sorting lists of
       OSM-originated objects
    """
    return (el['osm_type'], el['osm_id'])

def itinerary_comparator(itinerary):
    "This function is used as key for sorting itineraries in a route"""
    return (itinerary['stops'], itinerary['interval'])

def compare_stops(stop0, stop1):
    """Compares json of two stops in route"""
    stop_keys = ('name', 'int_name', 'id', 'osm_id', 'osm_type')
    stop0_props = tuple(stop0[k] for k in stop_keys)
    stop1_props = tuple(stop1[k] for k in stop_keys)

    if stop0_props != stop1_props:
        logging.debug("Different stops properties: %s, %s",
                      stop0_props, stop1_props)
        return False

    if not coords_eq(stop0['lon'], stop0['lat'],
                     stop1['lon'], stop1['lat']):
        logging.debug("Different stops coordinates: %s (%f, %f), %s (%f, %f)",
                      stop0_props, stop0['lon'], stop0['lat'],
                      stop1_props, stop1['lon'], stop1['lat'])
        return False

    entrances0 = sorted(stop0['entrances'], key=osm_id_comparator)
    entrances1 = sorted(stop1['entrances'], key=osm_id_comparator)
    if entrances0 != entrances1:
        logging.debug("Different stop entrances")
        return False

    exits0 = sorted(stop0['exits'], key=osm_id_comparator)
    exits1 = sorted(stop1['exits'], key=osm_id_comparator)
    if exits0 != exits1:
        logging.debug("Different stop exits")
        return False

    return True

def compare_transfers(transfers0, transfers1):
    """Compares two arrays of transfers of the form
       [(stop1_uid, stop2_uid, time), ...]
    """
    if len(transfers0) != len(transfers1):
        logging.debug("Different len(transfers): %d != %d",
                      len(transfers0), len(transfers1))
        return False

    transfers0 = [tuple([t[0], t[1], t[2]])
                      if t[0] < t[1] else
                  tuple([t[1], t[0], t[2]])
                      for t in transfers0]
    transfers1 = [tuple([t[0], t[1], t[2]])
                      if t[0] < t[1] else
                  tuple([t[1], t[0], t[2]])
                      for t in transfers1]

    transfers0.sort()
    transfers1.sort()

    diff_cnt = 0
    for tr0, tr1 in zip(transfers0, transfers1):
        if tr0 != tr1:
            if diff_cnt == 0:
                logging.debug("First pair of different transfers: %s, %s",
                              tr0, tr1)
            diff_cnt += 1
    if diff_cnt:
        logging.debug("Different transfers number = %d", diff_cnt)
        return False

    return True

def compare_networks(network0, network1):
    if network0['agency_id'] != network1['agency_id']:
        logging.debug("Different agency_id at route '%s'",
                      network0['network'])
        return False

    route_ids0 = sorted(x['route_id'] for x in network0['routes'])
    route_ids1 = sorted(x['route_id'] for x in network1['routes'])

    if route_ids0 != route_ids1:
        logging.debug("Different route_ids: %s != %s",
                      route_ids0, route_ids1)
        return False

    routes0 = sorted(network0['routes'], key=lambda x: x['route_id'])
    routes1 = sorted(network1['routes'], key=lambda x: x['route_id'])

    # Keys to compare routes. 'name' key is omitted since RouteMaster
    # can get its name from one of its Routes unpredictably.
    route_keys = ('type', 'ref', 'colour', 'route_id')

    for route0, route1 in zip(routes0, routes1):
        route0_props = tuple(route0[k] for k in route_keys)
        route1_props = tuple(route1[k] for k in route_keys)
        if route0_props != route1_props:
            logging.debug("Route props of '%s' are different: %s, %s",
                          route0['route_id'], route0_props, route1_props)
            return False

        itineraries0 = sorted(route0['itineraries'], key=itinerary_comparator)
        itineraries1 = sorted(route1['itineraries'], key=itinerary_comparator)

        for itin0, itin1 in zip(itineraries0, itineraries1):
            if itin0['interval'] != itin1['interval']:
                logging.debug("Different interval: %d != %d at route %s '%s'",
                              itin0['interval'], itin1['interval'],
                              route0['route_id'], route0['name'])
                return False
            if itin0['stops'] != itin1['stops']:
                logging.debug("Different stops at route %s '%s'",
                              route0['route_id'], route0['name'])
                return False

    return True


text:
[![Version](https://img.shields.io/cocoapods/v/PieCharts.svg?style=flat)](http://cocoadocs.org/docsets/PieCharts)
[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
[![License](https://img.shields.io/cocoapods/l/PieCharts.svg?style=flat)](http://cocoadocs.org/docsets/PieCharts)

Easy to use and highly customizable pie charts library for iOS

Swift 4.2, iOS 8+

[Video](https://youtu.be/LPFTPMDKDAE)

![ScreenShot](Screenshots/IMG_1279.PNG)![ScreenShot](Screenshots/IMG_1278.PNG)

## Features:
- Customizable slices
- Add overlays using simple UIViews
- Interactive
- Animated
- Dynamic slice insertion
- Reusable components via extensible layer system
- Configurable in interface builder
- [Legends](https://github.com/i-schuetz/ChartLegends). This is in a separate project to keep things focused and reusable.

## Installation

### CocoaPods

Add to your Podfile:

```ruby
use_frameworks!
pod 'PieCharts'
```

### Carthage

Add to your Cartfile:

```
github "i-schuetz/PieCharts"
```

## Usage

### Basic chart:

```swift
@IBOutlet weak var chartView: PieChart!

chartView.models = [
    PieSliceModel(value: 2.1, color: UIColor.yellow),
    PieSliceModel(value: 3, color: UIColor.blue),
    PieSliceModel(value: 1, color: UIColor.green)
]
```

Configurable in interface builder, with live update of the view:

![ScreenShot](Screenshots/IB.PNG)

### Overlays:

Overlays are implemented using layers. There are several built in layers and you also can implement your own ones.

To add text e.g. text labels inside the slices + text with lines outside, simply:
```swift
chartView.layers = [PiePlainTextLayer(), PieLineTextLayer()]

```

Each layer has its own customization options. For example, here we customize the plain labels layer:

```swift
let textLayerSettings = PiePlainTextLayerSettings()
textLayerSettings.viewRadius = 55
textLayerSettings.hideOnOverflow = true
textLayerSettings.label.font = UIFont.systemFont(ofSize: 8)

let formatter = NumberFormatter()
formatter.maximumFractionDigits = 1
textLayerSettings.label.textGenerator = {slice in
    return formatter.string(from: slice.data.percentage * 100 as NSNumber).map{"\($0)%"} ?? ""
}

let textLayer = PiePlainTextLayer()
textLayer.animator = AlphaPieViewLayerAnimator()
textLayer.settings = textLayerSettings

```

This is the custom views layer, which makes possible to create custom views:
```swift
let viewLayer = PieCustomViewsLayer()

let settings = PieCustomViewsLayerSettings()
settings.viewRadius = 135
settings.hideOnOverflow = false
viewLayer.settings = settings

viewLayer.viewGenerator = {slice, center in
    let myView = UIView()
    // add images, animations, etc.
    return myView
}

```

### Interactivity, events:

Conform to `PieChartDelegate` to react to interaction and other events:

```swift
func onGenerateSlice(slice: PieSlice)
func onStartAnimation(slice: PieSlice)
func onEndAnimation(slice: PieSlice)
func onSelected(slice: PieSlice, selected: Bool)
```

### Dynamic slice insertion:

```swift
chartView.insertSlice(index: 1, model: PieSliceModel(value: 5, color: UIColor.blue))
```

## Contributing

1. Fork
2. Commit changes to a branch in your fork
3. Push your code and make a pull request

## Outlook

The layer system can be abstracted a step further in order to make the slices themselves be in a layer. This way we can combine multiple slice-layers to create more complex types of pie charts.

## Credits

The food images used in the demo are from freepik.com, and flaticon.com/authors/madebyoliver

## Created By:

Ivan Schütz

## License

SwiftCharts is Copyright (c) 2017 Ivan Schütz and released as open source under the attached [Apache 2.0 license](LICENSE).

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

redpajama_set_name: RedPajamaGithub


text:
<?php

class FormalTheory_RegularExpression_Token_Set extends FormalTheory_RegularExpression_Token
{

	private $_char_array;
	private $_is_positive;

	static function getGroups()
	{
		static $groups = NULL;
		if( is_null( $groups ) ) {
			$number_range = array( "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" );
			$word_range = array_merge(
				range( "A", "Z" ), range( "a", "z" ),
				$number_range, array( "_" )
			);
			$space_range = array( " ", "\t", "\n", "\r", "\f" );
			$groups = array(
				"w" => $word_range,
				"d" => $number_range,
				"s" => $space_range,
			);
		}
		return $groups;
	}

	static function getInverseGroups()
	{
		static $inverse_groups = NULL;
		if( is_null( $inverse_groups ) ) {
			$full_range = array_map( "chr", range( 0, 127 ) );
			$inverse_groups = array();
			foreach( self::getGroups() as $group_char => $group_symbols ) {
				$inverse_groups[strtoupper( $group_char )] = array_diff( $full_range, $group_symbols );
			}
			$inverse_groups = array_reverse( $inverse_groups, TRUE );
		}
		return $inverse_groups;
	}

	static function newFromGroupChar( $group_char )
	{
		$groups = self::getGroups();
		if( array_key_exists( $group_char, $groups ) ) {
			return new self( $groups[$group_char], TRUE );
		}
		if( array_key_exists( strtolower( $group_char ), $groups ) ) {
			return new self( $groups[strtolower( $group_char )], FALSE );
		}
		throw new RuntimeException( "bad \$group_char" );
	}

	function __construct( array $char_array, $is_positive )
	{
		foreach( $char_array as $char ) {
			if( ! is_string( $char ) || strlen( $char ) !== 1 ) {
				throw new Exception( "non-char found in char array" );
			}
		}
		sort( $char_array );
		$this->_char_array = array_unique( $char_array );
		$this->_is_positive = (bool)$is_positive;
	}

	function _toString()
	{
		$char_array = $this->charArray();
		if( count( $char_array ) === 127 && ! in_array( "\n", $char_array ) ) return ".";

		$normal_set = $this->___toString( $char_array, FALSE );
		$inverse_set = $this->___toString( $char_array, TRUE );
		return strlen( $normal_set ) <= strlen( $inverse_set ) ? $normal_set : $inverse_set;
	}

	private function ___toString( array $char_array, $should_inverse )
	{
		$string = "";
		if( $should_inverse ) {
			$char_array = array_diff( array_map( "chr", range( 0, 127 ) ), $char_array );
		}
		$all_groups = self::getInverseGroups() + self::getGroups();
		foreach( $all_groups as $group_char => $group_symbols ) {
			if( count( array_intersect( $char_array, $group_symbols ) ) === count( $group_symbols ) ) {
				$char_array = array_diff( $char_array, $group_symbols );
				$string .= "\\{$group_char}";
			}
		}

		$offset_array = array_map( "ord", $char_array );
		$current_run = array();
		$last_offset = NULL;
		foreach( $offset_array as $offset ) {
			if( $offset-1 !== $last_offset ) {
				if( count( $current_run ) > 2 ) {
					$first_offset = array_shift( $current_run );
					$string .=
						FormalTheory_RegularExpression_Token_Constant::escapeChar( chr( $first_offset ) ).
						"-".
						FormalTheory_RegularExpression_Token_Constant::escapeChar( chr( $last_offset ) );
				} else {
					$string .= implode( "", array_map( array( "FormalTheory_RegularExpression_Token_Constant", "escapeChar" ), array_map( "chr", $current_run ) ) );
				}
				$current_run = array();
			}
			$current_run[] = $offset;
			$last_offset = $offset;
		}
		if( count( $current_run ) > 2 ) {
			$first_offset = array_shift( $current_run );
			$string .=
				FormalTheory_RegularExpression_Token_Constant::escapeChar( chr( $first_offset ) ).
				"-".
				FormalTheory_RegularExpression_Token_Constant::escapeChar( chr( $last_offset ) );
		} else {
			$string .= implode( "", array_map( array( "FormalTheory_RegularExpression_Token_Constant", "escapeChar" ), array_map( "chr", $current_run ) ) );
		}
		if( $should_inverse ) {
			return "[^{$string}]";
		} else {
			$is_simple = strlen( $string ) === 1 || preg_match( "/^\\\\(".implode( "|", array_keys( $all_groups ) ).")$/", $string );
			return $is_simple ? $string : "[{$string}]";
		}
	}

	function charArray()
	{
		return $this->_is_positive
			? $this->_char_array
			: array_diff( array_map( "chr", range( 0, 127 ) ), $this->_char_array );
	}

	function getMatches()
	{
		return array_map( function( $char ) {
			return FormalTheory_RegularExpression_Match::createFromString( $char );
		}, $this->charArray() );
	}

	function getFiniteAutomataClosure()
	{
		$char_array = $this->charArray();
		return function( $fa, $start_states, $end_states ) use ( $char_array ) {
			foreach( $char_array as $char ) {
				$start_states[1]->addTransition( $char, $end_states[2] );
				$start_states[2]->addTransition( $char, $end_states[2] );
			}
		};
	}

	protected function _compare( $token )
	{
		return $this->charArray() === $token->charArray();
	}

}

?>


text:
<?php

global $ss_framework;

echo get_avatar( $comment, $size = '64' );

echo '
';
	echo '
' . get_comment_author_link() . '
';
	echo '<time datetime="' . get_comment_date( 'c' ) . '">comment_ID ) ) . '">';
		printf( __( '%1$s', 'shoestrap' ), get_comment_date(),  get_comment_time() );
	echo '</time>';

	edit_comment_link( __( '(Edit)', 'shoestrap' ), '', '' );

	if ( $comment->comment_approved == '0' ) {
		echo $ss_framework->alert( 'info', __( 'Your comment is awaiting moderation.', 'shoestrap' ) );
	}

	comment_text();
	comment_reply_link( array_merge( $args, array( 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) );


text:
package tars.ui;

import java.util.logging.Logger;

import com.google.common.eventbus.Subscribe;

import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.SplitPane;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import tars.commons.core.LogsCenter;
import tars.commons.events.ui.RsvTaskAddedEvent;
import tars.model.task.rsv.RsvTask;

// @@author A0121533W
/**
 * UI Controller for panel containing the list of reserved tasks.
 */
public class RsvTaskListPanel extends UiPart {

    private static String LOG_MESSAGE_LAYOUT_UPDATING =
            "Updating layout for %s";
    private static final Logger logger = LogsCenter.getLogger(UiManager.class);
    private static final String FXML = "RsvTaskListPanel.fxml";
    private static final int START_INDEX = 1;

    private VBox panel;
    private AnchorPane placeHolderPane;

    @FXML
    private ListView<RsvTask> rsvTaskListView;

    public RsvTaskListPanel() {
        super();
    }

    @Override
    public void setNode(Node node) {
        panel = (VBox) node;
    }

    @Override
    public String getFxmlPath() {
        return FXML;
    }

    @Override
    public void setPlaceholder(AnchorPane pane) {
        this.placeHolderPane = pane;
    }

    public static RsvTaskListPanel load(Stage primaryStage,
            AnchorPane rsvTaskListPlaceholder,
            ObservableList<RsvTask> rsvTaskList) {
        RsvTaskListPanel rsvTaskListPanel = UiPartLoader.loadUiPart(
                primaryStage, rsvTaskListPlaceholder, new RsvTaskListPanel());
        rsvTaskListPanel.configure(rsvTaskList);
        return rsvTaskListPanel;
    }

    private void configure(ObservableList<RsvTask> rsvTaskList) {
        setConnections(rsvTaskList);
        addToPlaceholder();
    }

    private void setConnections(ObservableList<RsvTask> rsvTaskList) {
        rsvTaskListView.setItems(rsvTaskList);
        rsvTaskListView.setCellFactory(listView -> new RsvTaskListViewCell());
    }

    private void addToPlaceholder() {
        SplitPane.setResizableWithParent(placeHolderPane, false);
        placeHolderPane.getChildren().add(panel);
    }

    public void scrollTo(int index) {
        Platform.runLater(() -> {
            rsvTaskListView.scrollTo(index);
        });
    }

    class RsvTaskListViewCell extends ListCell<RsvTask> {
        private RsvTask newlyAddedRsvTask;

        public RsvTaskListViewCell() {
            registerAsAnEventHandler(this);
        }

        @Override
        protected void updateItem(RsvTask task, boolean empty) {
            super.updateItem(task, empty);

            if (empty || task == null) {
                setGraphic(null);
                setText(null);
            } else {
                RsvTaskCard card =
                        RsvTaskCard.load(task, getIndex() + START_INDEX);
                HBox layout = card.getLayout();
                if (this.newlyAddedRsvTask != null
                        && this.newlyAddedRsvTask.isSameStateAs(task)) {
                    layout.setStyle(UiColor.TASK_CARD_NEWLY_ADDED_BORDER);
                } else {
                    layout.setStyle(UiColor.TASK_CARD_DEFAULT_BORDER);
                }
                setGraphic(layout);
            }
        }

        @Subscribe
        private void handleRsvTaskAddedEvent(RsvTaskAddedEvent event) {
            logger.info(LogsCenter.getEventHandlingLogMessage(event,
                    String.format(LOG_MESSAGE_LAYOUT_UPDATING,
                            event.task.toString())));
            this.newlyAddedRsvTask = event.task;
        }
    }

}


text:
module BombDefuser
  class GameList
    extend ResourceList

    @resource = "games"

    class << self
      attr_accessor :platforms
    end

    def self.include_additional_parameters
      self.platforms ||= []
      params[:platforms] = platforms.join(",") unless platforms.empty?
    end
  end
end


text:
from satoshidicetools.simulator import satoshidice

"""
Bet same amount of money each time.
"""

class Flatbet(satoshidice.Simulator):
    def strategy(selef, previous_bet):
        pass

    def on_strategy_end(self):
        self.plot()

flatbet = Flatbet(balance=0.001, bet_amount=0.0001, less_then=45000)
flatbet.run()


text:
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom;

import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.gef.EditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.AbstractBorderItemEditPart;
import org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.swt.graphics.Color;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.EsbLinkEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.SequenceEditPart;

public abstract class AbstractInputConnector extends AbstractBorderItemEditPart {

    public final boolean isInput = true;

    protected IFigure primaryShapeForward;

    protected IFigure primaryShapeReverse;

    public NodeFigure figure_;

    // abstract public IFigure getPrimaryShapeForward();
    // abstract public IFigure getPrimaryShapeReverse();

    public AbstractInputConnector(View view) {
        super(view);
        // TODO Auto-generated constructor stub
    }

    protected NodeFigure createNodeFigure() {
        // TODO Auto-generated method stub
        return null;
    }

    public NodeFigure getNodeFigureInput() {

        return figure_;
    }

    protected IFigure createNodeShapeForward() {
        return primaryShapeForward = new EastPointerFigure();
    }

    protected IFigure createNodeShapeReverse() {
        return primaryShapeReverse = new WestPointerFigure();
    }

    public EastPointerFigure getPrimaryShapeForward() {
        return (EastPointerFigure) primaryShapeForward;
    }

    public WestPointerFigure getPrimaryShapeReverse() {
        return (WestPointerFigure) primaryShapeReverse;

    }

    public void notifyChanged(Notification notification) {
        int direction = -1;
        super.notifyChanged(notification);
        if (notification.getEventType() == Notification.ADD) {
            /*
             * You can directly call Reverse(EditPart) method here. But it will
             * lead to reduce the performance since it will call
             * Reverse(EditPart) for each and every notifyChange event. So we
             * will filter the request to some extend.
             */
            if (this.getTargetConnections().size() != 0) {
                EditPart link = ((EsbLinkEditPart) this.getTargetConnections().get(0)).getSource();
                if (((link instanceof AbstractOutputConnector)
                        && (((AbstractOutputConnector) link).getParent() instanceof AbstractMediator)
                        && (((AbstractMediator) ((AbstractOutputConnector) link).getParent()).reversed))
                        || (link instanceof AbstractEndpointOutputConnector)) {
                    if (this.getParent() instanceof AbstractMediator) {
                        ((AbstractMediator) this.getParent()).reverse(this.getParent());
                    }
                }

                if (this.getParent() instanceof SequenceEditPart) {
                    if (link instanceof AbstractEndpointOutputConnector) {
                        // ((SequenceEditPart)this.getParent()).moveConnectorsRightSide();
                    }
                }
            }
        }
    }

    @Override
    public boolean isSelectable() {
        // TODO Auto-generated method stub
        return false;
    }

    public class EastPointerFigure extends EastPointerShape {

        public EastPointerFigure() {

            this.setBackgroundColor(THIS_BACK);
            this.setPreferredSize(new Dimension(getMapMode().DPtoLP(12), getMapMode().DPtoLP(10)));
        }

    }

    public class WestPointerFigure extends WestPointerShape {

        public WestPointerFigure() {

            this.setBackgroundColor(THIS_BACK);
            this.setPreferredSize(new Dimension(getMapMode().DPtoLP(12), getMapMode().DPtoLP(10)));
        }

    }

    static final Color THIS_BACK = new Color(null, 50, 50, 50);

}


text:
/**
 * @file
 * @brief Declarates external variable gDebug.
 */
#ifndef PZDEBUG
#define PZDEBUG

/**
 * @ingroup common
 * @brief Extern variable to debug. Values used: 0, 1 and 2. (Jorge)
 */

extern int gDebug;

#endif


text:
package org.gbif.api.vocabulary;

import org.gbif.api.util.VocabularyUtils;

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

import javax.annotation.Nullable;

import org.apache.commons.lang3.StringUtils;

/**
 * Enumeration for all possible identifier types.
 */
public enum IdentifierType {

  URL,

  /**
   * Reference controlled by a separate system, used for example by DOI.
   * {http://en.wikipedia.org/wiki/Handle_(computing)}
   */
  LSID,

  HANDLER,

  DOI,

  UUID,

  FTP,

  URI,

  UNKNOWN,

  /**
   * Indicates the identifier originated from an auto_increment column in the portal.data_provider or
   * portal.data_resource table respectively.
   */
  GBIF_PORTAL,

  /**
   * Identifies the node (e.g: 'DK' for Denmark, 'sp2000' for Species 2000).
   */
  GBIF_NODE,

  /**
   * Participant identifier from the GBIF Directory.
   */
  GBIF_PARTICIPANT,

  /**
   * ID migrated from GrSciColl.
   */
  GRSCICOLL_ID,

  /**
   * Cool URI migrated from GrSciColl.
   */
  GRSCICOLL_URI,

  /**
   * IRN of an IH record.
   */
  IH_IRN,

  /**
   * Research Organization Registry.
   * https://ror.org
   */
  ROR,

  /**
   * https://www.grid.ac/institutes/
   */
  GRID,

  /**
   * https://cites.org/
   */
  CITES,

  /**
   * Symbiota IDs to help linking GrSciColl occurrences.
   */
  SYMBIOTA_UUID;

  // TODO: Check if this is used, it didn't exist in the new Registry2 API, but I preserved it from the old vocabulary
  public static final List<IdentifierType> TYPES;

  static {
    TYPES = Collections.unmodifiableList(Arrays.asList(IdentifierType.values()));
  }

  /**
   * @return the matching IdentifierType or null
   */
  public static IdentifierType fromString(String identifierType) {
    return VocabularyUtils.lookupEnum(identifierType, IdentifierType.class);
  }

  /**
   * Tries to infer the identifier type from a given identifier.
   * Most identifiers have a URI protocol prefix or a specific structure that
   * allows the guess.
   *
   * @return the inferred identifier type or Unknown if identifier is null or cant be inferred.
   */
  public static IdentifierType inferFrom(@Nullable String identifier) {
    String lcIdentifier = StringUtils.trimToEmpty(identifier).toLowerCase();

    if (lcIdentifier.isEmpty()) {
      return UNKNOWN;
    }

    if (lcIdentifier.startsWith(org.gbif.api.model.common.DOI.GBIF_PREFIX)
        || lcIdentifier.startsWith(org.gbif.api.model.common.DOI.TEST_PREFIX)) {
      return DOI;
    }
    if (lcIdentifier.startsWith("10.")
        || lcIdentifier.startsWith("doi:10.")
        || lcIdentifier.startsWith("urn:doi:10.")
        || lcIdentifier.startsWith("http://dx.doi.org/10.")
        || lcIdentifier.startsWith("https://dx.doi.org/10.")
        || lcIdentifier.startsWith("http://doi.org/10.")
        || lcIdentifier.startsWith("https://doi.org/10.")) {
      return DOI;
    }

    if (lcIdentifier.startsWith("https://ror.org")) {
      return ROR;
    }

    if (lcIdentifier.startsWith("http:")
        || lcIdentifier.startsWith("https:")
        || lcIdentifier.startsWith("www.")) {
      return URL;
    }
    if (lcIdentifier.startsWith("ftp:")) {
      return FTP;
    }
    if (lcIdentifier.startsWith("urn:lsid:") || lcIdentifier.startsWith("lsid:")) {
      return LSID;
    }

    if (lcIdentifier.startsWith("urn:uuid:") || lcIdentifier.startsWith("uuid:")) {
      return UUID;
    }

    if (lcIdentifier.startsWith("gbif:ih:irn:")) {
      return IH_IRN;
    }

    if (lcIdentifier.startsWith("grid")) {
      return GRID;
    }

    try {
      //noinspection ResultOfMethodCallIgnored
      java.util.UUID.fromString(lcIdentifier);
      return UUID;
    } catch (IllegalArgumentException ignored) {
      // We're just trying to convert a String to anything readable. Apparently the UUID approach failed.
    }

    return UNKNOWN;
  }
}


text:
/*
 * This library is distributed under a modified BSD license.  See the included
 * LICENSE file for details.
 */
package org.fife.ui.rtextarea;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

/**
 * Unit tests for the {@link RTextAreaEditorKit.CutAction} class.
 *
 * @author Robert Futrell
 * @version 1.0
 */
class RTextAreaEditorKitCutActionTest {

	@Test
	void testConstructor_multiArg() {
		RTextAreaEditorKit.CutAction action = new RTextAreaEditorKit.CutAction(
			"cut", null, "Description", 0, null);
		Assertions.assertEquals("cut", action.getName());
		Assertions.assertEquals("Description", action.getDescription());
	}

	@Test
	void testActionPerformedImpl() {

		RTextArea textArea = new RTextArea("Hello world");
		textArea.setSelectionStart(2);
		textArea.setSelectionEnd(9);

		RTextAreaEditorKit.CutAction action = new RTextAreaEditorKit.CutAction();
		action.actionPerformedImpl(null, textArea);

	}

	@Test
	void testGetMacroID() {
		Assertions.assertEquals(RTextAreaEditorKit.cutAction,
			new RTextAreaEditorKit.CutAction().getMacroID());
	}
}


text:
package v1beta1

import kapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api/v1beta3"

// Auth system gets identity name and provider
// POST to UserIdentityMapping, get back error or a filled out UserIdentityMapping object

type User struct {
	kapi.TypeMeta   `json:",inline"`
	kapi.ObjectMeta `json:"metadata,omitempty"`

	FullName string `json:"fullName,omitempty"`

	Identities []string `json:"identities"`

	Groups []string `json:"groups"`
}

type UserList struct {
	kapi.TypeMeta `json:",inline"`
	kapi.ListMeta `json:"metadata,omitempty"`
	Items         []User `json:"items"`
}

type Identity struct {
	kapi.TypeMeta   `json:",inline"`
	kapi.ObjectMeta `json:"metadata,omitempty"`

	// ProviderName is the source of identity information
	ProviderName string `json:"providerName"`

	// ProviderUserName uniquely represents this identity in the scope of the provider
	ProviderUserName string `json:"providerUserName"`

	// User is a reference to the user this identity is associated with
	// Both Name and UID must be set
	User kapi.ObjectReference `json:"user"`

	Extra map[string]string `json:"extra,omitempty"`
}

type IdentityList struct {
	kapi.TypeMeta `json:",inline"`
	kapi.ListMeta `json:"metadata,omitempty"`
	Items         []Identity `json:"items"`
}

type UserIdentityMapping struct {
	kapi.TypeMeta   `json:",inline"`
	kapi.ObjectMeta `json:"metadata,omitempty"`

	Identity kapi.ObjectReference `json:"identity,omitempty"`
	User     kapi.ObjectReference `json:"user,omitempty"`
}

func (*User) IsAnAPIObject()                {}
func (*UserList) IsAnAPIObject()            {}
func (*Identity) IsAnAPIObject()            {}
func (*IdentityList) IsAnAPIObject()        {}
func (*UserIdentityMapping) IsAnAPIObject() {}


text:
package bankfile

import (
	"reflect"
	"testing"

	"github.com/st3sch/whycc/bankfile/converter"
)

func TestFactory_FindBy(t *testing.T) {
	f := factory{}

	c, err := f.FindBy("ingdiba")
	if err != nil {
		t.Errorf("Unexpected error: '%v'", err)
	}
	_, ok := c.(Converter)
	if !ok {
		t.Errorf("Returned converter doesn't implement interface 'converter'")
	}

	_, err = f.FindBy("non existent")
	if err == nil {
		t.Error("Expected invlaid type error not raised")
	}
}

func TestFactory_loadConverterFor(t *testing.T) {
	type testpair struct {
		in       string
		expected reflect.Type
	}

	tests := []testpair{
		{"ingdiba", reflect.TypeOf(converter.IngDiBa{})},
		{"augusta", reflect.TypeOf(converter.Augusta{})},
		{"krspaka", reflect.TypeOf(converter.KrSpaKa{})},
	}

	f := factory{}
	for _, pair := range tests {
		conv, err := f.loadConverterFor(pair.in)
		if err != nil {
			t.Errorf("Unexpected Error: '%v'", err)
			continue
		}

		converterType := reflect.TypeOf(conv)
		if pair.expected != converterType {
			t.Errorf("Expected converter type %q does not match returned converter type %q", pair.expected, converterType)
		}
	}

	_, err := f.loadConverterFor("non existent")
	if err == nil {
		t.Error("Expected invlaid type error not raised")
	}
}

func TestNewConverterLocator(t *testing.T) {
	cl := NewConverterLocator()
	if reflect.TypeOf(cl) != reflect.TypeOf(factory{}) {
		t.Errorf("ConverterLocator does not return factory. It returns: %q", reflect.TypeOf(cl))
	}
}


text:
<!DOCTYPE >

			Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

		<object width="425" height="350">
			<param name="movie" value="//www.youtube.com/embed/B2wpZQRldI4">
			</param>
			<embed src="//www.youtube.com/embed/B2wpZQRldI4" type="application/x-shockwave-flash" width="425" height="350"></embed>
		</object>


text:
require 'app/models/service'
require 'app/models/service_converter'
require 'app/models/service_mediator'
require 'app/models/service_sorter'
require 'fleet'

module FleetAdapter
  module Routes
    class Services < Base

      namespace '/' + API_VERSION do
        post '/services' do
          services = service_mediator.load_and_start_all
          status 201
          json services.map { |service| { id: service.id } }
        end

        get '/services/:id' do
          result = {
            id: params[:id],
            'actualState' => service_mediator.status_for(params[:id])
          }

          json result
        end

        put '/services/:id' do
          case @payload[:desiredState]
          when 'started'
            service_mediator.start(params[:id])
            status 204
          when 'stopped'
            service_mediator.stop(params[:id])
            status 204
          else
            status 400
          end
        end

        delete '/services/:id' do
          service_mediator.destroy(params[:id])
          status 204
        end
      end

      def service_mediator
        ServiceMediator.new(@payload)
      end
    end
  end
end


text:
<!doctype html>
<meta charset="utf-8">
<meta name="timeout" content="long">
<title>IndexedDB: Parallel iteration of cursors in upgradeneeded</title>
<link rel="author" href="pwnall@chromium.org" title="Victor Costan">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="resources/support-promises.js"></script>
<script>
'use strict';

for (let cursorCount of [2, 20, 200, 2000]) {
  promise_test(testCase => {
    return createDatabase(testCase, (database, transaction) => {
      const store = database.createObjectStore('cache', { keyPath: 'key' });
      store.put({ key: '42' });

      const promises = [];

      for (let j = 0; j < 2; j += 1) {
        const promise = new Promise((resolve, reject) => {
          let request = null;
          for (let i = 0; i < cursorCount / 2; i += 1) {
            request = store.openCursor();
          }

          let continued = false;
          request.onsuccess = testCase.step_func(() => {
            const cursor = request.result;

            if (!continued) {
              assert_equals(cursor.key, '42');
              assert_equals(cursor.value.key, '42');
              continued = true;
              cursor.continue();
            } else {
              assert_equals(cursor, null);
              resolve();
            }
          });
          request.onerror = () => reject(request.error);
        });
        promises.push(promise);
      }
      return Promise.all(promises);
    }).then(database => {
      database.close();
    });
  }, `${cursorCount} cursors`);
}

</script>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DotVVM.Framework.Diagnostics;

namespace DotVVM.Framework.Runtime.Tracing
{
    public interface IStartupTracer
    {
        void TraceEvent(string eventName);

        Task NotifyStartupCompleted(IDiagnosticsInformationSender informationSender);

    }

}


text:
<?php namespace Gesar\Feedback;

use Illuminate\Support\ServiceProvider;

class FeedbackServiceProvider extends ServiceProvider {

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        if(! $this->app->routesAreCached()) {
            require __DIR__.'/routes.php';
        }

        $this->publishes([
            __DIR__ . '/migrations/' => base_path('/database/migrations'),
        ], 'migrations');

        $this->publishes([
            __DIR__ . '/views/' => base_path('/resources/views/g_feedback/'),
        ], 'views');

        $this->publishes([
            __DIR__.'/config/config.php' => config_path('g_feedback.php'),
        ]);
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {

//
    }

}


text:
__protobuf__ = proto.module(
    package="google.cloud.gaming.v1",
    manifest={},
)

__all__ = tuple(sorted(__protobuf__.manifest))


text:
<!DOCTYPE html>

		<title>DOM events</title>

DOM events


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Shuhari.Framework.Utils;

namespace Shuhari.Framework.ComponentModel
{
    /// <summary>
    /// Base implementation for INotifyPropertyChanged, normally used in WPF applications
    /// </summary>
    public abstract class Observable : INotifyPropertyChanged
    {
        /// <inheritdoc />
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Notify property changed
        /// </summary>
        /// <param name="propertyName"></param>
        protected virtual void OnPropertyChanged(string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        /// <summary>
        /// Set field value, and raise <see cref="PropertyChanged"/> if value changed
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="propName"></param>
        /// <param name="field"></param>
        /// <param name="value"></param>
        protected void SetProperty<T>(string propName, ref T field, T value)
        {
            Expect.IsNotBlank(propName, nameof(propName));

            if (!Equals(field, value))
            {
                field = value;
                OnPropertyChanged(propName);
            }
        }
    }
}


text:
import time
import unittest

import config
import node

LEADER = 1
ED = 2

class Cert_5_8_1_KeySynchronization(unittest.TestCase):
    def setUp(self):
        self.simulator = config.create_default_simulator()

        self.nodes = {}
        for i in range(1,3):
            self.nodes[i] = node.Node(i, (i == ED), simulator=self.simulator)

        self.nodes[LEADER].set_panid(0xface)
        self.nodes[LEADER].set_mode('rsdn')
        self.nodes[LEADER].add_whitelist(self.nodes[ED].get_addr64())
        self.nodes[LEADER].enable_whitelist()
        self.nodes[LEADER].set_key_switch_guardtime(0)

        self.nodes[ED].set_panid(0xface)
        self.nodes[ED].set_mode('rsn')
        self.nodes[ED].add_whitelist(self.nodes[LEADER].get_addr64())
        self.nodes[ED].enable_whitelist()
        self.nodes[ED].set_key_switch_guardtime(0)

    def tearDown(self):
        for node in list(self.nodes.values()):
            node.stop()
            node.destroy()
        self.simulator.stop()

    def test(self):
        self.nodes[LEADER].start()
        self.simulator.go(4)
        self.assertEqual(self.nodes[LEADER].get_state(), 'leader')

        self.nodes[ED].start()
        self.simulator.go(5)
        self.assertEqual(self.nodes[ED].get_state(), 'child')

        addrs = self.nodes[LEADER].get_addrs()
        for addr in addrs:
            if 'ff:fe00' not in addr:
                self.assertTrue(self.nodes[ED].ping(addr))

        key_sequence_counter = self.nodes[ED].get_key_sequence_counter()
        self.nodes[ED].set_key_sequence_counter(key_sequence_counter + 10)

        addrs = self.nodes[LEADER].get_addrs()
        for addr in addrs:
            if 'ff:fe00' not in addr:
                self.assertFalse(self.nodes[ED].ping(addr))

if __name__ == '__main__':
    unittest.main()


text:
<?php

    error_reporting(0);

    // Abre a base de dados
    require_once("abrir_conexao.php");

    $array_questoes = array();

    /* Realiza a leitura da questão. */

    $table = "enunciado";

    $command = "SELECT enunciado
                FROM $table WHERE idEnunciado='$questao_id';";

    $execution = $connection->query($command);

    $acmSelect = $execution->num_rows;

    if ($acmSelect > 0)
    {
        while($read = $execution->fetch_assoc())
        {
            $array_questoes["enunciado"] = $read["enunciado"];
        }
    }

    /* Faz a leitura da resposta da questao. */

    $table = "questao";

    $command = "SELECT algoritmo,
                       algoritmo_respondido,
                       blocos
                FROM $table WHERE idQuestao='$questao_id';";

    $execution = $connection->query($command);

    $acmSelect = $execution->num_rows;

    if ($acmSelect > 0)
    {
        while($read = $execution->fetch_assoc())
        {
            $array_questoes["algoritmo"] = $read["algoritmo"];
            $array_questoes["algoritmo_respondido"] = $read["algoritmo_respondido"];
            $array_questoes["blocos"] = $read["blocos"];
        }
    }

    //header('Content-Type: application/json');

    // Escreve o array em formato JSON.
    $contents = json_encode($array_questoes, JSON_UNESCAPED_UNICODE);

    // Fecha a base de dados.
    require_once("fechar_conexao.php");

?>


text:
package com.hairywelly.storm;

import backtype.storm.task.ShellBolt;
import backtype.storm.topology.IRichBolt;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.tuple.Fields;

import java.util.Map;

public class SplitSentence extends ShellBolt implements IRichBolt {

    public SplitSentence() {
        super("mono","WordCountTest.exe");
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields("word"));
    }

    @Override
    public Map<String, Object> getComponentConfiguration() {
        return null;
    }
}


text:
    URL, von der das Hilfsprogramm als binäres Archiv heruntergeladen werden kann.
    Es werden ZIP- und GZIP-komprimierte TAR-Archive unterstützt.

    Der Zeitstempel des Archivs auf dem Server wird mit der lokal installierten Version
    (soweit vorhanden) verglichen, so daß Updates einfach veröffentlicht werden können.

    Die URL muß vom Hudson-Master aus erreichbar sein, nicht aber von jedem einzelnen
    Slave-Knoten.