text:
package shike.app.model.dao.track;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.support.annotation.Nullable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import shike.app.model.dao.db.DbUtil;
import shike.app.model.dao.db.VirtualTrackLocationsTable;
import shike.app.model.dao.db.VirtualTracksTable;
import shike.app.model.session.track.VirtualTrack;

/**
 * Implementazione di {@link VirtualTrackDao} specifica per VirtualTrack
 */
public class VirtualTrackDaoImpl implements VirtualTrackDao {

	/**
	 * Riferimento al database dell'applicazione
	 */
	private SQLiteDatabase db;

	/**
	 * Costruttore necessario per ottenere il riferimento al database
	 *
	 * @param context contesto dell'applicazione, necessario per ottenere il database
	 */
	public VirtualTrackDaoImpl(Context context) {
		db = DbUtil.getInstance(context).getWritableDatabase();
	}

	/**
	 * Ritorna tutti i punti che compongono un percorso
	 *
	 * @param virtualTrackId id del percorso per il quale si vogliono trovare i punti
	 * @return sequenza ordinata dei punti del percorso
	 */
	private List<Location> getTrackPoints(int virtualTrackId) {
		Map<Integer, Location> points = new TreeMap<>();

		Cursor cur = db.query(VirtualTrackLocationsTable.TABLE, null,
			VirtualTrackLocationsTable.VIRTUAL_TRACK_ID + " = " + virtualTrackId,
			null, null, null, null);

		while (cur.moveToNext()) {
			int order = cur.getInt(cur.getColumnIndex(
				VirtualTrackLocationsTable.LOCATION_ORDER));

			Location point = new Location(VirtualTrackLocationsTable.TABLE);
			point.setLatitude(cur.getDouble(
				cur.getColumnIndex(VirtualTrackLocationsTable.LATITUDE)));
			point.setLongitude(cur.getDouble(
				cur.getColumnIndex(VirtualTrackLocationsTable.LONGITUDE)));
			point.setAltitude(cur.getDouble(
				cur.getColumnIndex(VirtualTrackLocationsTable.ALTITUDE)));

			points.put(order, point);

		}

		cur.close();

		return new ArrayList<>(points.values());
	}

	/**
	 * Crea un VirtualTrack a partire da una riga della tabella 'virtualtracks'
	 *
	 * @param cur cursore che rappresenta una riga di 'virtualtracks'
	 * @return percorso corrispondente alla riga
	 */
	private VirtualTrack cursorToTrack(Cursor cur) {
		int _id = cur.getInt(cur.getColumnIndex(VirtualTracksTable._ID));

		String name = cur.getString(cur.getColumnIndex(VirtualTracksTable.NAME));

		double length = cur.getDouble(cur.getColumnIndex(
			VirtualTracksTable.LENGTH));

		Date creationDate = new Date(cur.getLong(
			cur.getColumnIndex(VirtualTracksTable.CREATION_DATE)));

		Location barycenter = new Location(VirtualTracksTable.TABLE);
		barycenter.setLatitude(cur.getDouble(
			cur.getColumnIndex(VirtualTracksTable.BARYCENTER_LATITUDE)));
		barycenter.setLongitude(cur.getDouble(
			cur.getColumnIndex(VirtualTracksTable.BARYCENTER_LONGITUDE)));

		List<Location> points = getTrackPoints(_id);

		return new VirtualTrack(_id, name, length, points, creationDate, barycenter);
	}

	@Override
	public List<VirtualTrack> getAll() {

		List<VirtualTrack> tracks = new ArrayList<>();

		Cursor cur = db.query(VirtualTracksTable.TABLE, null, null, null, null, null,
			null);

		while (cur.moveToNext()) {
			tracks.add(cursorToTrack(cur));
		}

		cur.close();

		return tracks;
	}

	@Override
	public List<VirtualTrack> get(final Location location, @Nullable Double radius) {
		List<VirtualTrack> tracks = getAll();

		if (radius != null && radius > 0) {
			for (VirtualTrack track : tracks) {
				if (track.getPoints().get(0).distanceTo(location) > radius) {
					tracks.remove(track);
				}
			}
		}

		// Ordinamento percorsi per distanza da location
		Collections.sort(tracks, new Comparator<VirtualTrack>() {
			@Override
			public int compare(VirtualTrack lhs, VirtualTrack rhs) {
				double lhsDistance = lhs.getPoints().get(0).distanceTo(location);
				double rhsDistance = rhs.getPoints().get(0).distanceTo(location);

				if (lhsDistance < rhsDistance) { // lhs è più vicino a location di rhs
					return -1;
				} else if (lhsDistance > rhsDistance) { // rhs è più vicino a location di lhs
					return 1;
				} else { // lhs e rhs sono alla stessa distanza da location
					return 0;
				}
			}
		});

		return tracks;
	}

	@Override
	public VirtualTrack get(int virtualTrackId) {

		Cursor cur = db.query(VirtualTracksTable.TABLE, null,
			VirtualTracksTable._ID + " = " + virtualTrackId, null, null, null, null);
		VirtualTrack track = null;

		if (cur.getCount() == 1) {
			cur.moveToNext();

			track = cursorToTrack(cur);
		}
		cur.close();

		return track;
	}

	@Override
	public int add(List<VirtualTrack> tracks, boolean truncateFirst) {
		if (truncateFirst) {
			removeAll();
		}
		int rows = 0;
		for (VirtualTrack track : tracks) {
			ContentValues content = new ContentValues();
			content.put(VirtualTracksTable._ID, track.get_id());
			content.put(VirtualTracksTable.NAME, track.getName());
			content.put(VirtualTracksTable.CREATION_DATE, track.getCreationDate().getTime
				());
			content.put(VirtualTracksTable.LENGTH, track.getLength());
			content.put(VirtualTracksTable.BARYCENTER_LATITUDE,
				track.getCenter().getLatitude());
			content.put(VirtualTracksTable.BARYCENTER_LONGITUDE,
				track.getCenter().getLongitude());

			long result = db.replace(VirtualTracksTable.TABLE, null, content);

			db.beginTransaction();
			int index = 0;
			for (Location point : track.getPoints()) {
				ContentValues pointContent = new ContentValues();
				pointContent.put(VirtualTrackLocationsTable.VIRTUAL_TRACK_ID,
					track.get_id());
				pointContent.put(VirtualTrackLocationsTable.LOCATION_ORDER, index++);
				pointContent.put(VirtualTrackLocationsTable.LATITUDE, point.getLatitude());
				pointContent.put(VirtualTrackLocationsTable.LONGITUDE,
					point.getLongitude());
				pointContent.put(VirtualTrackLocationsTable.ALTITUDE, point.getAltitude());
				db.replaceOrThrow(VirtualTrackLocationsTable.TABLE, null, pointContent);
			}

			db.setTransactionSuccessful();
			db.endTransaction();

			if (result > -1) {
				++rows;
			}
		}
		return rows;
	}

	@Override
	public int removeAll() {
		return db.delete(VirtualTracksTable.TABLE, "1", null);
	}
}


text:
namespace tao::json::internal
{
   template< typename T, template< typename... > class Traits, typename... With >
   inline constexpr bool use_first_ptr_as = std::is_constructible_v< T, const basic_value< Traits >&, With&... >;

   template< typename T, template< typename... > class Traits, typename... With >
   inline constexpr bool use_second_ptr_as = !use_first_ptr_as< T, Traits, With... > && std::is_move_constructible_v< T > && has_as< Traits< T >, basic_value< Traits >, With... >;

   template< typename T, template< typename... > class Traits, typename... With >
   inline constexpr bool use_third_ptr_as = !use_first_ptr_as< T, Traits, With... > && !use_second_ptr_as< T, Traits, With... > && std::is_default_constructible_v< T > && has_to< Traits< T >, basic_value< Traits >, T, With... >;

   template< typename T, template< typename... > class Traits, typename... With >
   inline constexpr bool use_fourth_ptr_as = !use_first_ptr_as< T, Traits, With... > && !use_third_ptr_as< T, Traits, With... > && std::is_copy_constructible_v< T > && has_as< Traits< T >, basic_value< Traits >, With... >;

   template< typename T, template< typename... > class Traits, class Producer >
   inline constexpr bool use_first_ptr_consume = std::is_move_constructible_v< T >&& has_consume_one< Traits, Producer, T >;

   template< typename T, template< typename... > class Traits, class Producer >
   inline constexpr bool use_second_ptr_consume = !use_first_ptr_consume< T, Traits, Producer > && std::is_default_constructible_v< T > && has_consume_two< Traits, Producer, T >;

   template< typename T, template< typename... > class Traits, class Producer >
   inline constexpr bool use_third_ptr_consume = !use_second_ptr_consume< T, Traits, Producer > && std::is_copy_constructible_v< T > && has_consume_one< Traits, Producer, T >;

}  // namespace tao::json::internal

#endif

redpajama_set_name: RedPajamaGithub


text:
// -*-Mode: C++;-*- // technically C99

// * BeginRiceCopyright *****************************************************
//
// $HeadURL$
// $Id$
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2002-2022, Rice University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
//
// * Neither the name of Rice University (RICE) nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// This software is provided by RICE and contributors "as is" and any
// express or implied warranties, including, but not limited to, the
// implied warranties of merchantability and fitness for a particular
// purpose are disclaimed. In no event shall RICE or contributors be
// liable for any direct, indirect, incidental, special, exemplary, or
// consequential damages (including, but not limited to, procurement of
// substitute goods or services; loss of use, data, or profits; or
// business interruption) however caused and on any theory of liability,
// whether in contract, strict liability, or tort (including negligence
// or otherwise) arising in any way out of the use of this software, even
// if advised of the possibility of such damage.
//
// ******************************************************* EndRiceCopyright *

/******************************************************************************
 * File: MPI_Init.c
 *
 * Purpose: override MPI initialization to capture rank
 *
 * Modification history:
 *   28 October 2007 - created - John Mellor-Crummey
 *****************************************************************************/

/******************************************************************************
 * standard include files
 *****************************************************************************/
#include <mpi.h>

/******************************************************************************
 * standard include files
 *****************************************************************************/
#include "name.h"

/******************************************************************************
 * forward declarations
 *****************************************************************************/

static void remember_rank();

/******************************************************************************
 * interface functions
 *****************************************************************************/

/*-----------------------------------------------------------------------------
 * Function MPI_Init
 * Purpose: override MPI initialization in C/C++ programs to capture MPI rank
 *---------------------------------------------------------------------------*/
int MPI_Init( int *argc, char ***argv )
{
  int retval = PMPI_Init(argc, argv);

  if (retval == MPI_SUCCESS) remember_rank();

  return retval;
}

/*-----------------------------------------------------------------------------
 * Function mpi_init_
 * Purpose: override MPI initialization in Fortran programs to capture MPI rank
 *---------------------------------------------------------------------------*/
void mpi_init_(int *ierr)
{
  pmpi_init_(ierr);
  if (*ierr == MPI_SUCCESS) remember_rank();
}

/******************************************************************************
 * private operations
 *****************************************************************************/

/*-----------------------------------------------------------------------------
 * Function remember_rank
 * Purpose: record MPI rank for later use by csprof
 *---------------------------------------------------------------------------*/
static void remember_rank()
{
  int rank;

  if (MPI_Comm_rank(MPI_COMM_WORLD, &rank) == MPI_SUCCESS) {
    hpcrun_set_mpirank(rank);
  }
}


text:
$(document).ready(function() {
    $('#user-avatar-image input').on('click', function(e) {
        e.stopPropagation();
    });
});

$('#user-avatar-image').click(function() {
    var $block = $(this);
    var url = Routing.generate('dream_ajax_load_poster');

    $block.find('input').click();
    $('#dream_poster').fileupload({
        url: url,
        dataType: 'json',
        done: function (e, data) {
            var responseArr = JSON.parse(data.jqXHR.responseText);
            $.each(responseArr, function (index, file) {
                if(file.error){
                    $('#errors').append(
                        '
' +
                            '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' +
                            file.src + ' ' +file.error + '' +
                        '
'
                    );

                    return;
                }
                if(file.type == 'image' && file.error == null) {
                    $block.addClass('active').find('img').attr('src', file.srcPreview);
                    $('#newUserForm_avatar').get(0).value = file.src;
                }
            });
        },
        error: function(msg) {
            console.log('error = ' + msg);
            console.dir(msg);
        }
    });
});


text:
<?php

namespace Fsilva\HttpMessage;

use Psr\Http\Message\UriInterface;
use Fsilva\HttpMessage\Exception\InvalidSchemeException;
use Fsilva\HttpMessage\Exception\InvalidArgumentException;
use Fsilva\HttpMessage\Exception\InvalidHostNameException;

/**
 * Value object representing a URI for use in HTTP requests.
 *
 * Instances of this interface are considered immutable; all methods that
 * might change state are implemented such that they retain the internal
 * state of the current instance and return a new instance that contains the
 * changed state.
 *
 * Typically the Host header will also be present in the request message.
 * For server-side requests, the scheme will typically be discoverable in the
 * server parameters.
 *
 * @link http://tools.ietf.org/html/rfc3986 (the URI specification)
 *
 * @package Fsilva\HttpMessage
 * @author  Filipe Silva <silvam.filipe@gmail.com>
 */
class Uri implements UriInterface
{
    /**
     * @var string[] Allowed values for URI scheme
     */
    private $schemes = ['http', 'https', ''];

    /**
     * @var array Default scheme ports
     */
    private $defaultPorts = [
        'http' => '80',
        'https' => '443'
    ];

    /**
     * @var string URI scheme
     */
    private $scheme = '';

    /**
     * @var string User name
     */
    private $user = '';

    /**
     * @var string User password
     */
    private $pass;

    /**
     * @var string URI host name
     */
    private $host = '';

    /**
     * @var string|int Host port
     */
    private $port = '';

    /**
     * @var string Path segment of the URI
     */
    private $path = '';

    /**
     * @var string Query segment of the URI
     */
    private $query = '';

    /**
     * @var string The fragment of the URI
     */
    private $fragment = '';

    public function __construct($url = null)
    {
        $validUrl = Validator::isValid('url', $url);
        if (!is_null($url) && !$validUrl) {
            throw new InvalidArgumentException(
                "The URL '{$url}' is not valid."
            );
        }
        if (!is_null($url)) {
            $parts = parse_url($url);
            if ((bool) $parts && is_array($parts)) {
                foreach ($parts as $property => $value) {
                    $this->$property = $value;
                }
            }
        }
    }

    /**
     * Retrieve the URI scheme.
     *
     * If no scheme is present, this method returns an empty string.
     *
     * The string returned omits the trailing "://" delimiter if present.
     *
     * @return string The scheme of the URI.
     */
    public function getScheme()
    {
        return $this->scheme;
    }

    /**
     * Retrieve the authority portion of the URI.
     *
     * The authority portion of the URI is:
     *
     * <pre>
     * [user-info@]host[:port]
     * </pre>
     *
     * If the port component is not set or is the standard port for the current
     * scheme, it will not be included.
     *
     * This method returns an empty string if no authority information is
     * present.
     *
     * @return string Authority portion of the URI, in "[user-info@]host[:port]"
     *     format.
     */
    public function getAuthority()
    {
        $authority = ($this->user !== '') ? $this->getUserInfo() .'@' : '';
        $port = '';
        if (!is_null($this->getPort())) {
            $port = ':'. $this->getPort();
        }
        return $authority.$this->getHost().$port;
    }

    /**
     * Retrieve the user information portion of the URI, if present.
     *
     * If a user is present in the URI, this will return that value;
     * additionally, if the password is also present, it will be appended to the
     * user value, with a colon (":") separating the values.
     *
     * It will not return the "@" suffix when returning user information.
     *
     * @return string User information portion of the URI, if present, in
     *     "username[:password]" format.
     */
    public function getUserInfo()
    {
        $format = '%s%s';
        if (!is_null($this->pass) && $this->pass !== '') {
            $format = '%s:%s';
        }

        return sprintf($format, $this->user, $this->pass);
    }

    /**
     * Retrieve the host segment of the URI.
     *
     * This method returns a string; if no host segment is present, an
     * empty string in then returned.
     *
     * @return string Host segment of the URI.
     */
    public function getHost()
    {
        return $this->host;
    }

    /**
     * Retrieve the port segment of the URI.
     *
     * If a port is present, and it is non-standard for the current scheme,
     * this method returns it as an integer. If the port is the standard port
     * used with the current scheme, this method returns null.
     *
     * If no port is present this method returns a null value.
     *
     * @return null|int The port for the URI.
     */
    public function getPort()
    {
        $standard = ($this->scheme != '') ?
            $this->defaultPorts[$this->getScheme()] : 0;

        if ($this->port == '') {
            return null;
        }

        $port = intval($this->port);

        if ($this->port == $standard) {
            $port = null;
        }

        return $port;
    }

    /**
     * Retrieve the path segment of the URI.
     *
     * This method always return a string; if no path is present it will return
     * an empty string.
     *
     * @return string The path segment of the URI.
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * Retrieve the query string of the URI.
     *
     * This method will always return a string; if no query string is present,
     * it returns an empty string.
     *
     * The string returned omits the leading "?" character.
     *
     * @return string The URI query string.
     */
    public function getQuery()
    {
        return $this->query;
    }

    /**
     * Retrieve the fragment segment of the URI.
     *
     * This method always returns a string; if no fragment is present, it will
     * return an empty string.
     *
     * The string returned will always omit the leading "#" character.
     *
     * @return string The URI fragment.
     */
    public function getFragment()
    {
        return $this->fragment;
    }

    /**
     * Create a new instance with the specified scheme.
     *
     * This method retains the state of the current instance, and return
     * a new instance that contains the specified scheme. If the scheme
     * provided includes the "://" delimiter, it will be removed.
     *
     * A scheme can only be one of the following values: "http", "https",
     * or an empty string.
     *
     * An empty scheme is equivalent to removing the scheme.
     *
     * @param string $scheme The scheme to use with the new instance.
     *
     * @return self A new instance with the specified scheme.
     * @throws \InvalidArgumentException|InvalidSchemeException for invalid or
     * unsupported schemes.
     */
    public function withScheme($scheme)
    {
        $message = "Invalid or unsupported scheme. Supported schemes are " .
            "http, https or '' (empty string).";
        if (!is_string($scheme)) {
            throw new InvalidSchemeException($message);
        }
        $cleaned = strtolower(str_replace('://', '', $scheme));
        if (!in_array($cleaned, $this->schemes, true)) {
            throw new InvalidSchemeException($message);
        }
        $uri = clone($this);
        $uri->scheme = $cleaned;
        return $uri;
    }

    /**
     * Create a new instance with the specified user information.
     *
     * This method retains the state of the current instance, and return
     * a new instance that contains the specified user information.
     *
     * Password is optional, but the user information includes the
     * user; an empty string for the user is equivalent to removing user
     * information.
     *
     * @param string      $user     User name to use for authority.
     * @param null|string $password Password associated with $user.
     *
     * @return self A new instance with the specified user information.
     */
    public function withUserInfo($user, $password = null)
    {
        $uri = clone($this);
        $uri->user = $user;
        $uri->pass = $password;
        return $uri;
    }

    /**
     * Create a new instance with the specified host.
     *
     * This method retains the state of the current instance, and returns
     * a new instance that contains the specified host.
     *
     * An empty host value is equivalent to removing the host.
     *
     * @param string $host Hostname to use with the new instance.
     *
     * @return self|Uri A new instance with the specified host.
     * @throws \InvalidArgumentException for invalid hostnames.
     */
    public function withHost($host)
    {
        $valid = Validator::isValid('hotsname', $host);
        if (!$valid && $host != '') {
            throw new InvalidHostNameException(
                "The hostname '{$host}' ist not valid."
            );
        }

        $uri = clone($this);
        $uri->host = $host;
        return $uri;
    }

    /**
     * Create a new instance with the specified port.
     *
     * This method retains the state of the current instance, and return
     * a new instance that contains the specified port.
     *
     * An exception is raise for ports outside the
     * established TCP and UDP port ranges.
     *
     * A null value provided for the port is equivalent to removing the port
     * information.
     *
     * @param null|int $port Port to use with the new instance; a null value
     *                       removes the port information.
     *
     * @return self A new instance with the specified port.
     * @throws \InvalidArgumentException for invalid ports.
     */
    public function withPort($port)
    {
        $clearPort = ($port === '');
        $port = intval($port);
        $isDefault = in_array($port, $this->defaultPorts);
        $udpTcp = $port >= 1024 && $port <= 49151;

        if (!$isDefault && !$udpTcp && !$clearPort) {
            throw new InvalidArgumentException(
                "The port {$port} is not valid."
            );
        }

        if ($clearPort) {
            $port = '';
        }

        $uri = clone($this);
        $uri->port = $port;

        return $uri;
    }

    /**
     * Create a new instance with the specified path.
     *
     * This method retains the state of the current instance, and return
     * a new instance that contains the specified path.
     *
     * The path will be prefixed with "/" if not present
     *
     * An empty path value is equivalent to removing the path.
     *
     * @param string $path The path to use with the new instance.
     *
     * @return self A new instance with the specified path.
     * @throws \InvalidArgumentException for invalid paths.
     */
    public function withPath($path)
    {
        if (preg_match('/\s/', $path)) {
            throw new InvalidArgumentException(
                "The path '{$path}' contains invalid characters."
            );
        }

        $path = rtrim(str_replace('//', '/', ('/'. $path)), '/');

        $uri = clone($this);
        $uri->path = $path;
        return $uri;
    }

    /**
     * Create a new instance with the specified query string.
     *
     * This method retains the state of the current instance, and return
     * a new instance that contains the specified query string.
     *
     * If the query string is prefixed by "?", that character will be removed.
     * Additionally, the query string SHOULD be parseable by parse_str() in
     * order to be valid.
     *
     * An empty query string value is equivalent to removing the query string.
     *
     * @param string $query The query string to use with the new instance.
     *
     * @return self A new instance with the specified query string.
     * @throws \InvalidArgumentException for invalid query strings.
     */
    public function withQuery($query)
    {
        if (!is_string($query)) {
            throw new InvalidArgumentException(
                'The query must be an URI formatted string.'
            );
        }
        $query = ltrim($query, '?');
        $uri = clone($this);
        $uri->query = $query;
        return $uri;
    }

    /**
     * Create a new instance with the specified URI fragment.
     *
     * This method retains the state of the current instance, and return
     * a new instance that contains the specified URI fragment.
     *
     * If the fragment is prefixed by "#", that character will be removed.
     *
     * An empty fragment value is equivalent to removing the fragment.
     *
     * @param string $fragment The URI fragment to use with the new instance.
     *
     * @return self A new instance with the specified URI fragment.
     */
    public function withFragment($fragment)
    {
        $fragment = ltrim($fragment, '#');
        $uri = clone($this);
        $uri->fragment = $fragment;
        return $uri;
    }

    /**
     * Return the string representation of the URI.
     *
     * Concatenates the various segments of the URI, using the appropriate
     * delimiters:
     *
     * - If a scheme is present, "://" will append the value.
     * - If the authority information is present, that value will be
     *   concatenated.
     * - If a path is present, it will be prefixed by a "/" character.
     * - If a query string is present, it will be prefixed by a "?" character.
     * - If a URI fragment is present, it will be prefixed by a "#" character.
     *
     * @return string
     */
    public function __toString()
    {
        $schema = $this->getScheme();
        $str = ($schema != '') ? "{$schema}://" : $schema;
        $str .= $this->getAuthority();
        $str .= $this->getPath();
        $query = $this->getQuery();
        $str .= ($query != '') ? "?{$query}" : $query;
        $str .= ($this->fragment != '') ? "#{$this->fragment}" : $this->fragment;
        return $str;
    }
}


text:
id: bd7178d8c242eddfaeb5bd13
title: Visualizzare i dati con un grafico a dispersione
challengeType: 3
forumTopicId: 301467
dashedName: visualize-data-with-a-scatterplot-graph
---

# --description--

**Obiettivo:** Costruisci un'app [CodePen.io](https://codepen.io) funzionalmente simile a questa: <https://codepen.io/freeCodeCamp/full/bgpXyK>.

Soddisfa le seguenti [user story](https://en.wikipedia.org/wiki/User_story) e fai in modo che tutti i test siano superati. Usa il tuo stile personale.

Puoi usare HTML, JavaScript, CSS e la libreria di visualizzazione basata su svg D3. I test richiedono la generazione degli assi con la proprietà axis di D3, che crea automaticamente le tacche sugli assi. Queste tacche sono richieste per superare i test perché la loro posizione è usata per determinare l'allineamento degli elementi del grafico. Puoi trovare informazioni su come generare gli assi su <https://github.com/d3/d3/blob/master/API.md#axes-d3-axis>. Gli elementi del DOM (non-virtuale) richiesti sono selezionati al momento di ogni test. Se usi un framework frontend (come Vue per esempio) i risultati dei test potrebbero essere inaccurati per il contenuto dinamico. Speriamo di supportarli prima o poi, ma al momento non lo sono per i progetti D3.

**User Story #1:** Posso vedere un elemento title con un corrispondente `id="title"`.

**User Story #2:** Posso vedere un asse x con corrispondente `id="x-axis"`.

**User Story #3:** Posso vedere un asse y con corrispondente `id="y-axis"`.

**User Story #4:** Posso vedere dei punti, ognuno con una classe `dot`, che rappresentano i dati da tracciare.

**User Story #5:** Ogni punto dovrebbe avere le proprietà `data-xvalue` e `data-yvalue` che contengono i rispettivi valori `x` e `y`.

**User Story #6:** per ogni punto `data-xvalue` e `data-yvalue` dovrebbero essere nel range dei dati e nel formato corretto. Per superare i test sono accettabili come valori per `data-xvalue` numeri interi (anni scritti per esteso) o oggetti `Date`. Per `data-yvalue` (minuti), usa oggetti `Date`.

**User Story #7:** `data-xvalue` e il suo punto corrispondente dovrebbero allinearsi con il punto/valore corrispondente sull'asse delle x.

**User Story #8:** `data-yvalue` e il suo punto corrispondente dovrebbero allinearsi con il punto/valore corrispondente sull'asse delle y.

**User Story #9:** Posso vedere varie tacche con etichetta in formato di tempo `%M:%S` sull'asse delle y.

**User Story #10:** Posso vedere varie tacche con etichetta che mostrano l'anno sull'asse delle x.

**User Story #11:** Posso vedere che le etichette dell'asse x coprono lo stesso intervallo dei valori dei dati.

**User Story #12:** Posso vedere che le etichette dell'asse y coprono lo stesso intervallo dei valori dei dati.

**User Story #13:** Posso vedere una legenda con una descrizione che ha `id="legend"`.

**User Story #14:** Posso passare con il mouse su un'area e vedere un tooltip con un corrispondente `id="tooltip"` che mostra maggiori informazioni sull'area.

**User Story #15:** Il mio tooltip dovrebbe avere una proprietà `data-year` che corrisponde al `data-xvalue` dell'area attiva.

Ecco i dati che dovrai utilizzare per completare il progetto: `https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/cyclist-data.json`

Puoi costruire il tuo progetto usando questo modello CodePen e facendo click su `Save` per creare il tuo pen. Oppure puoi usare questo link CDN per eseguire i test in qualsiasi ambiente tu voglia: `https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`

Una volta fatto, invia l'URL del tuo progetto di lavoro con tutti i suoi test superati.

# --solutions--

```js
// solution required
```


text:
package DeBugging;

public class DeBugg3 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
	    System.out.println("Over the river");
	      System.out.println("and through the woods");
	      System.out.println("to Grandmother's house we go");
	}

}


text:
 Esky, is again unmaintained.
 I would reccomend trying `pyinstaller` and `pyupdater`
 It seems to be the king.

 There are some useful modules here such as the functions to get admin access. These
 could be made reusable for other projects.

 I would also like to encourage people to collaborate instead of always spin
 off new libraries. Why do we have 4 activley mainited freezers for python????

Esky  - keep frozen apps fresh
==============================

[![Join the chat at https://gitter.im/cloudmatrix/esky](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/cloudmatrix/esky?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Build Status](https://travis-ci.org/cloudmatrix/esky.svg)](https://travis-ci.org/cloudmatrix/esky)
[![Build status](https://ci.appveyor.com/api/projects/status/qsl966pqssff9lpt?svg=true&pendingText=Windows%20Pending&failingText=Windows%20Failing&passingText=Windows%20Passing)](https://ci.appveyor.com/project/tim83455/esky-r8uvn)
[![Code Climate](https://codeclimate.com/github/cloudmatrix/esky/badges/gpa.svg)](https://codeclimate.com/github/cloudmatrix/esky)

Esky is an auto-update framework for frozen Python applications.  It provides
a simple API through which apps can find, fetch and install updates, and a
bootstrapping mechanism that keeps the app safe in the face of failed or
partial updates. Updates can also be sent as differential patches.

Esky is currently capable of freezing apps with py2exe, py2app, cxfreeze and
bbfreeze. Adding support for other freezer programs should be easy;
patches will be gratefully accepted.

We are tested and running on Python 2.7
Py2app will work on python3 fine, the other freezers not so much.

#### Current Limitations
 - Cannot sign the bootstrap executable
 - Doesn't work with windows resources
 - cxfreeze and py2exe not working on python3
 - Only support cxfreeze 4

For some workarounds to common issues check out the wiki

Installation
------------

The simplest way to install esky is

`pip install esky`

To install the latest development branch you can install directly from github with

`git clone git@github.com:cloudmatrix/esky.git`

`pip install -e esky`

**To uninstall the development version do** `python setup.py develop --uninstall`

Usage
-----

Freezing your app with esky requires small some modification to a setup.py file and then adding the Esky class to your program.
When you are ready just run `python setup.py bdist_esky`
This will produce a zip file which can automatically update as long as the structure is kept in tact.

- The [tutorial](https://github.com/cloudmatrix/esky/tree/master/tutorial) will guide you through setting up and freezing with esky. (get the files by cloning)

- We have an F.A.Q as well as Documentation in our [wiki](https://github.com/cloudmatrix/esky/wiki)

- Ryan has done a talk at Pycon to help you get started: [Keep your frozen app fresh](http://pyvideo.org/video/470/pyconau-2010--esky--keep-your-frozen-apps-fresh)

- There is also a wrapper for esky in the gui library wxpthon, see [blog post](http://www.blog.pythonlibrary.org/2013/07/12/wxpython-updating-your-application-with-esky/)

Features
--------

- Pull updates from a http server or amazon s3 bucket (easily extendable)

- Bootstrap Executable to prevent corruption in failed updates (can be compiled to ~1mb using Rpython)

- Differential Patching (minor updates and fixes can be < 10kb)

- py2exe, py2app, cxfreeze

Getting in Contact
------------------

* Questions about usage can be posted on stackoverflow.
* Bugs and problems can be posted at our github issue tracker.
* Chats and so on can be done through gitter.

Development / Contributing
--------------------------

We welcome all contributors.
See the [Contributing Guide](https://github.com/cloudmatrix/esky/wiki/Contributing)

#### Author

[Ryan Kelly](https://github.com/rfk)

#### Current Core

 - No one

#### Contributors

[Thanks all Contributors](https://github.com/cloudmatrix/esky/graphs/contributors)

The above list isn't complete, some people seem to be missing or contribute in other ways.

* JPFrancoia


text:
namespace SF {

    class Archive;

    template<typename T, std::size_t N>
    void serialize_vc6(SF::Archive & ar, std::tr1::array<T, N> & a, const unsigned int)
    {
        serialize_array_impl(ar, a);
    }

} // namespace SF

#endif // ! INCLUDE_SF_ARRAY_TR1_HPP


text:
package com.siemens.cmiv.avt.mvt.outlier;

/**
 * @author Jie Zheng
 *
 */
public class OutlierEntry {
	String criteriaMeasurement;
	String criteriaScaling;

	/**
	 *
	 */
	public OutlierEntry() {
		// TODO Auto-generated constructor stub
	}

	public String getCriteriaMeasurement(){
		return criteriaMeasurement;
	}
	public String getCriteriaScaling(){
		return criteriaScaling;
	}

	public void setCriteriaMeasurement(String criteriaMeasurement){
		this.criteriaMeasurement = criteriaMeasurement;
	}
	public void setCriteriaScaling(String criteriaScaling){
		this.criteriaScaling = criteriaScaling;
	}
	public int getStatisticsDataID(String statisticData){
		int index = 3;

		if (statisticData.equalsIgnoreCase("NominalGT RECIST"))
			return index;

		index++;
		if (statisticData.equalsIgnoreCase("Annotation RECIST"))
			return index;

		index++;
		if (statisticData.equalsIgnoreCase("RECIST Difference"))
			return index;

		index++;
		if (statisticData.equalsIgnoreCase("NominalGT WHO"))
			return index;

		index++;
		if (statisticData.equalsIgnoreCase("Annotation WHO"))
			return index;

		index++;
		if (statisticData.equalsIgnoreCase("WHO Difference"))
			return index;

		index++;
		if (statisticData.equalsIgnoreCase("NominalGT Volume"))
			return index;

		index++;
		if (statisticData.equalsIgnoreCase("Annotation Volume"))
			return index;

		index++;
		if (statisticData.equalsIgnoreCase("Volume Difference"))
			return index;

		index++;
		if (statisticData.equalsIgnoreCase("Relative VolumeDifference"))
			return index;

		index++;
		if (statisticData.equalsIgnoreCase("Surface Distance(Average)"))
			return index;

		index++;
		if (statisticData.equalsIgnoreCase("Surface Distance(RMS)"))
			return index;

		index++;
		if (statisticData.equalsIgnoreCase("Surface Distance(Maximum)"))
			return index;

		index++;
		if (statisticData.equalsIgnoreCase("Volume Overlap"))
			return index;

		return -1;
	}

	public String getCriteriaScalingID(String CriteriaScaling){
		if (CriteriaScaling.equalsIgnoreCase("Top 25%"))
			return ">0.75";

		if (CriteriaScaling.equalsIgnoreCase("Top 50%"))
			return ">0.5";

		if (CriteriaScaling.equalsIgnoreCase("Bottom 50%"))
			return "<0.5";

		if (CriteriaScaling.equalsIgnoreCase("Bottom 25%"))
			return "<0.25";

		return "";
	}
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
/* @vue/component */
exports.default = {
    methods: {
        genTFoot: function genTFoot() {
            if (!this.$slots.footer) {
                return null;
            }
            var footer = this.$slots.footer;
            var row = this.hasTag(footer, 'td') ? this.genTR(footer) : footer;
            return this.$createElement('tfoot', [row]);
        },
        genActionsFooter: function genActionsFooter() {
            if (this.hideActions) {
                return null;
            }
            return this.$createElement('div', {
                'class': this.classes
            }, this.genActions());
        }
    }
};
//# sourceMappingURL=foot.js.map


text:
package com.spotify.heroic.shell.task;

import com.google.common.base.Charsets;
import com.spotify.heroic.dagger.CoreComponent;
import com.spotify.heroic.shell.AbstractShellTaskParams;
import com.spotify.heroic.shell.ShellIO;
import com.spotify.heroic.shell.ShellTask;
import com.spotify.heroic.shell.TaskName;
import com.spotify.heroic.shell.TaskParameters;
import com.spotify.heroic.shell.TaskUsage;
import dagger.Component;
import eu.toolchain.async.AsyncFramework;
import eu.toolchain.async.AsyncFuture;
import lombok.Getter;
import lombok.ToString;
import org.kohsuke.args4j.Option;

import javax.inject.Inject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

@TaskUsage("(Test) Test to read lines from a file")
@TaskName("test-read-file")
public class TestReadFile implements ShellTask {
    private final AsyncFramework async;

    @Inject
    public TestReadFile(AsyncFramework async) {
        this.async = async;
    }

    @Override
    public TaskParameters params() {
        return new Parameters();
    }

    @Override
    public AsyncFuture<Void> run(final ShellIO io, final TaskParameters base) throws Exception {
        final Parameters params = (Parameters) base;

        try (final BufferedReader in = new BufferedReader(
            new InputStreamReader(io.newInputStream(params.in, StandardOpenOption.READ),
                Charsets.UTF_8))) {

            long i = 0;

            while (true) {
                final String line = in.readLine();

                if (line == null) {
                    break;
                }

                io.out().println(String.format("Read: %d", i++));
            }
        }

        return async.resolved();
    }

    @ToString
    private static class Parameters extends AbstractShellTaskParams {
        @Option(name = "-i", usage = "File to read from")
        @Getter
        private Path in = Paths.get("in.txt");
    }

    public static TestReadFile setup(final CoreComponent core) {
        return DaggerTestReadFile_C.builder().coreComponent(core).build().task();
    }

    @Component(dependencies = CoreComponent.class)
    interface C {
        TestReadFile task();
    }
}


text:
<?php
/**
*   File.class.php
*   This class inlcude some file & folder operation method.
*   WARING: This script can works on linux only.
*   @author     karminski <code.karminski@outlook.com>
*   @version    140721:10
*
*   @changelog
*            140721:10 ADD trim to loadFile() method.
*            140721:9  FIX static method declare.
*            140719:7  ADD move(), loadFile() method.
*            131117:6  FIX txtEcho '>' method should be an atomic action
*            131012:5  FIX loadFolderFilename() read . or .. issue
*            130912:4  ADD txtReadByLineNum
*                          getLineNumByContent
*            130903:3  ADD txtTail
*            130902:2  ADD txtEcho
*                          txtHead
*                          auto_warp
*            130831:1  ADD loadFolderFilename
*                          txtWrite
*
*/

class File{

    /**
    *   PUBLIC STATIC FUNCTION loadFolderFilename
    *   This method load all filenames which in target folder into an array.
    *   @param string $dir, dir path
    *   @return array $files, array which loaded filenames
    */
    public static function loadFolderFilename($dir){
        if(empty($dir)) return false;
        $files = array();
        if($handle = opendir($dir)){
            while(false !== ($file = readdir($handle))){
                if($file === '.' || $file === '..') continue;
                $files[] = $file;
            }
            closedir($handle);
        }else{
            return false;
        }
        return $files;
    }

    /**
    *   PUBLIC STATIC FUNCTION txtWrite
    *   This method use php BIF(build in function) 'error_log' to write files.
    *   @param string $str, what you want to write
    *   @param string $file, target file loaction
    *   @param string $auto_wrap, there's 'unix'. 'windows'('win'), 'mac', null(no-warp) offered.
    *   @return boolean status, write status.
    */
    public static function txtWrite($str='', $file, $auto_wrap = ''){
        if(empty($file)) return false;
        self::auto_warp($str, $auto_wrap);
        return error_log($str, 3, $file);
    }

    /**
     * [txtEcho description]
     * @param  [type] $str       [description]
     * @param  string $mode      [description]
     * @param  [type] $file      [description]
     * @param  string $auto_wrap [description]
     * @return [type]            [description]
     */
    public static function txtEcho($str, $mode ='>', $file, $auto_wrap = ''){
        if(empty($file)) return false;
        self::auto_warp($str, $auto_wrap);
        $com = "echo '{$str}' ";
        if($mode === '>'){
            $com .= ' > ';
            $fileTmp = $file.".tmp";
            $com .= $fileTmp;
            if(exec($com) !== "") return false;
            return (exec("mv $fileTmp $file")===""?true:false);
        }elseif($mode === '>>'){
            $com .= ' >> ';
            $com .= $file;
            return (exec($com)===""?true:false);
        }
        return false;
    }

    /**
     * [txtHead description]
     * @param  [type]  $file  [description]
     * @param  integer $lines [description]
     * @param  string  $bytes [description]
     * @return [type]         [description]
     */
    public static function txtHead($file, $lines = 1, $bytes = ''){
        if(empty($file)) return false;
        $com = "head";
        if(!empty($lines)) $com .= " -n {$lines} ";
        if(!empty($bytes)) $com .= " -c {$bytes} ";
        $com .= $file;
        return exec($com);
    }

    /**
     * [txtTail description]
     * @param  [type]  $file  [description]
     * @param  integer $lines [description]
     * @param  string  $bytes [description]
     * @return [type]         [description]
     */
    public static function txtTail($file, $lines = 1, $bytes = ''){
        if(empty($file)) return false;
        $com = "tail";
        if(!empty($lines)) $com .= " -n {$lines} ";
        if(!empty($bytes)) $com .= " -c {$bytes} ";
        $com .= $file;
        return exec($com);
    }

    /**
     * [txtReadByLineNum description]
     * @param  [type] $line [description]
     * @param  [type] $file [description]
     * @return [type]       [description]
     */
    public static function txtReadByLineNum($line, $file){
        if(empty($line)||empty($file)) return false;
        return exec("sed -n {$line}p {$file}");
    }

    /**
     * [getLineNumByContent description]
     * @param  [type] $content [description]
     * @param  [type] $file    [description]
     * @return [type]          [description]
     */
    public static function getLineNumByContent($content, $file){
        if(empty($content)||empty($file)) return false;
        $lines = exec(" awk '/{$content}/ {print NR}' $file");
        return explode("\n", $lines);
    }

    /**
     * [move description]
     * @param  [type] $target [description]
     * @param  [type] $from   [description]
     * @param  [type] $to     [description]
     * @return [type]         [description]
     */
    public static function move($target, $from, $to){
        if(empty($target)||empty($from)||empty($to)) return false;
        exec("mv {$from}{$target} {$to}",$out, $rc);
        if($rc === 0) return true;
        return false;
    }

    /**
     * [loadFile description]
     * @param  [type] $file_addr [description]
     * @return [type]            [description]
     */
    public static function loadFile($file_addr, &$content, &$content_len){
        $content     = array();
        $content_len = 0;
        $requestDataHandle = @fopen($file_addr, "r");
        if($requestDataHandle){
            while(!feof($requestDataHandle)){
                $content[] = trim(fgets($requestDataHandle));
                $content_len ++;
            }
            fclose($requestDataHandle);
        }else{
            return false;
        }
        unset($requestDataHandle);
        return true;
    }

    /**
     * [auto_warp description]
     * @param  [type] $str  [description]
     * @param  string $mode [description]
     * @return [type]       [description]
     */
    private static function auto_warp(&$str, $mode =''){
        if(!empty($mode)){
            if($mode === 'unix'){
                $str .= "\n";
            }elseif($mode === 'win' || $mode === 'windows'){
                $str .= "\r\n";
            }elseif($mode === 'mac'){
                $str .= "\r";
            }
        }
    }

}


text:
namespace content {
class WebContents;
}

namespace electron {

class ElectronJavaScriptDialogManager
    : public content::JavaScriptDialogManager {
 public:
  ElectronJavaScriptDialogManager();
  ~ElectronJavaScriptDialogManager() override;

  // content::JavaScriptDialogManager implementations.
  void RunJavaScriptDialog(content::WebContents* web_contents,
                           content::RenderFrameHost* rfh,
                           content::JavaScriptDialogType dialog_type,
                           const std::u16string& message_text,
                           const std::u16string& default_prompt_text,
                           DialogClosedCallback callback,
                           bool* did_suppress_message) override;
  void RunBeforeUnloadDialog(content::WebContents* web_contents,
                             content::RenderFrameHost* rfh,
                             bool is_reload,
                             DialogClosedCallback callback) override;
  void CancelDialogs(content::WebContents* web_contents,
                     bool reset_state) override;

 private:
  void OnMessageBoxCallback(DialogClosedCallback callback,
                            const std::string& origin,
                            int code,
                            bool checkbox_checked);

  std::map<std::string, int> origin_counts_;
};

}  // namespace electron

#endif  // ELECTRON_SHELL_BROWSER_ELECTRON_JAVASCRIPT_DIALOG_MANAGER_H_


text:
package com.atlassian.plugins.studio.storage.toolkit;

import com.atlassian.core.ofbiz.test.mock.MockGenericValue;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.project.Project;
import com.atlassian.jira.web.action.JiraWebActionSupport;
import com.atlassian.plugins.studio.storage.toolkit.impl.AbstractDefaultScopeImpl;
import com.google.common.collect.ImmutableMap;
import com.opensymphony.module.propertyset.PropertySet;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Matcher;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mock;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * User: leonidmaslov
 * Date: 12/10/10
 * Time: 6:20 PM
 */
public class ScopesTest
{
    @Mock
    PropertySet propertySet;

    @Test
    public void testProjectScope() throws Exception
    {

        Project project = mock(Project.class);
        when(project.getId()).thenReturn(567L);

        InstanceId id = getId(Scopes.projectScope(project), project);
        Assert.assertThat(id, isEq(567L, "FacadeStorageProject", "project-"));
    }

    @Test
    public void testIssueScope() throws Exception
    {
        Issue issue = mock(Issue.class);
        when(issue.getId()).thenReturn(569L);

        InstanceId id = getId(Scopes.issueScope(issue), issue);
        Assert.assertThat(id, isEq(569L, "FacadeStorageIssue", "issue-"));
    }

    @Test
    public void testGvScope() throws Exception
    {
        MockGenericValue gv = new MockGenericValue("Name", ImmutableMap.of("id", 112L));

        InstanceId id = getId(Scopes.gvScope(gv), gv);
        Assert.assertThat(id, isEq(112L, "FacadeStorageGv", "gv-"));

    }

    @Test
    public void testConstantName() throws Exception
    {
        InstanceId id = getId(Scopes.constantName("cn.name"), "cn.name");
        Assert.assertThat(id, isEq(2L, "FacadeStorageConstant-cn.name", "constant-"));
    }

    @Test
    public void testActionConfigurationInstance() throws Exception
    {
        InstanceId id = getId(Scopes.actionConfiguration(new MyAction()), new MyAction());
        Assert.assertThat(id, isEq(3L, "FacadeStorageAction-com.atlassian.plugins.studio.storage.toolkit.ScopesTest$MyAction", "class-"));
    }

    @Test
    public void testActionConfigurationKlazz() throws Exception
    {
        InstanceId id = getId(Scopes.actionConfiguration(MyAction.class), MyAction.class);
        Assert.assertThat(id, isEq(3L, "FacadeStorageAction-com.atlassian.plugins.studio.storage.toolkit.ScopesTest$MyAction", "class-"));
    }

    private Matcher<InstanceId> isEq(Long id, String name, String prefix)
    {
        return CoreMatchers.equalTo(new InstanceId(id, name, prefix));
    }

    private <U> InstanceId getId(Scope<U> scope, U context)
    {
        return ((AbstractDefaultScopeImpl<U>) scope).getInstanceId(context);
    }

    private static class MyAction extends JiraWebActionSupport
    {
    }

}


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2013 Adam Wulkiewicz, Lodz, Poland.

// This file was modified by Oracle on 2013, 2014.
// Modifications copyright (c) 2013, 2014 Oracle and/or its affiliates.

// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle

#ifndef BOOST_GEOMETRY_STRATEGY_AGNOSTIC_POINT_IN_POLY_WINDING_HPP
#define BOOST_GEOMETRY_STRATEGY_AGNOSTIC_POINT_IN_POLY_WINDING_HPP

#include <boost/geometry/util/math.hpp>
#include <boost/geometry/util/select_calculation_type.hpp>

#include <boost/geometry/strategies/side.hpp>
#include <boost/geometry/strategies/covered_by.hpp>
#include <boost/geometry/strategies/within.hpp>

namespace boost { namespace geometry
{

namespace strategy { namespace within
{

// Fix for https://svn.boost.org/trac/boost/ticket/9628
// For floating point coordinates, the <1> coordinate of a point is compared
// with the segment's points using some EPS. If the coordinates are "equal"
// the sides are calculated. Therefore we can treat a segment as a long areal
// geometry having some width. There is a small ~triangular area somewhere
// between the segment's effective area and a segment's line used in sides
// calculation where the segment is on the one side of the line but on the
// other side of a segment (due to the width).
// For the s1 of a segment going NE the real side is RIGHT but the point may
// be detected as LEFT, like this:
//                     RIGHT
//                 ___----->
//                  ^      O Pt  __ __
//                 EPS     __ __
//                  v__ __ BUT DETECTED AS LEFT OF THIS LINE
//             _____7
//       _____/
// _____/
template <typename CSTag>
struct winding_side_equal
{
    typedef typename strategy::side::services::default_strategy
        <
            CSTag
        >::type strategy_side_type;

    template <size_t D, typename Point, typename PointOfSegment>
    static inline int apply(Point const& point,
                            PointOfSegment const& se,
                            int count)
    {
        // Create a vertical segment intersecting the original segment's endpoint
        // equal to the point, with the derived direction (UP/DOWN).
        // Set only the 2 first coordinates, the other ones are ignored
        PointOfSegment ss1, ss2;
        set<1-D>(ss1, get<1-D>(se));
        set<1-D>(ss2, get<1-D>(se));
        if ( count > 0 ) // UP
        {
            set<D>(ss1, 0);
            set<D>(ss2, 1);
        }
        else // DOWN
        {
            set<D>(ss1, 1);
            set<D>(ss2, 0);
        }
        // Check the side using this vertical segment
        return strategy_side_type::apply(ss1, ss2, point);
    }
};

// The optimization for cartesian
template <>
struct winding_side_equal<cartesian_tag>
{
    template <size_t D, typename Point, typename PointOfSegment>
    static inline int apply(Point const& point,
                            PointOfSegment const& se,
                            int count)
    {
        return math::equals(get<1-D>(point), get<1-D>(se)) ?
                0 :
                get<1-D>(point) < get<1-D>(se) ?
                    // assuming count is equal to 1 or -1
                    count : // ( count > 0 ? 1 : -1) :
                    -count; // ( count > 0 ? -1 : 1) ;
    }
};

/*!
\brief Within detection using winding rule
\ingroup strategies
\tparam Point \tparam_point
\tparam PointOfSegment \tparam_segment_point
\tparam CalculationType \tparam_calculation
\author Barend Gehrels
\note The implementation is inspired by terralib http://www.terralib.org (LGPL)
\note but totally revised afterwards, especially for cases on segments
\note Only dependant on "side", -> agnostic, suitable for spherical/latlong

\qbk{
[heading See also]
[link geometry.reference.algorithms.within.within_3_with_strategy within (with strategy)]
}
 */
template
<
    typename Point,
    typename PointOfSegment = Point,
    typename CalculationType = void
>
class winding
{
    typedef typename select_calculation_type
        <
            Point,
            PointOfSegment,
            CalculationType
        >::type calculation_type;

    typedef typename strategy::side::services::default_strategy
        <
            typename cs_tag<Point>::type
        >::type strategy_side_type;

    /*! subclass to keep state */
    class counter
    {
        int m_count;
        bool m_touches;

        inline int code() const
        {
            return m_touches ? 0 : m_count == 0 ? -1 : 1;
        }

    public :
        friend class winding;

        inline counter()
            : m_count(0)
            , m_touches(false)
        {}

    };

    template <size_t D>
    static inline int check_touch(Point const& point,
                PointOfSegment const& seg1, PointOfSegment const& seg2,
                counter& state)
    {
        calculation_type const p = get<D>(point);
        calculation_type const s1 = get<D>(seg1);
        calculation_type const s2 = get<D>(seg2);
        if ((s1 <= p && s2 >= p) || (s2 <= p && s1 >= p))
        {
            state.m_touches = true;
        }
        return 0;
    }

    template <size_t D>
    static inline int check_segment(Point const& point,
                PointOfSegment const& seg1, PointOfSegment const& seg2,
                counter& state, bool& eq1, bool& eq2)
    {
        calculation_type const p = get<D>(point);
        calculation_type const s1 = get<D>(seg1);
        calculation_type const s2 = get<D>(seg2);

        // Check if one of segment endpoints is at same level of point
        eq1 = math::equals(s1, p);
        eq2 = math::equals(s2, p);

        if (eq1 && eq2)
        {
            // Both equal p -> segment is horizontal (or vertical for D=0)
            // The only thing which has to be done is check if point is ON segment
            return check_touch<1 - D>(point, seg1, seg2, state);
        }

        return
              eq1 ? (s2 > p ?  1 : -1)  // Point on level s1, UP/DOWN depending on s2
            : eq2 ? (s1 > p ? -1 :  1)  // idem
            : s1 < p && s2 > p ?  2     // Point between s1 -> s2 --> UP
            : s2 < p && s1 > p ? -2     // Point between s2 -> s1 --> DOWN
            : 0;
    }

public :

    // Typedefs and static methods to fulfill the concept
    typedef Point point_type;
    typedef PointOfSegment segment_point_type;
    typedef counter state_type;

    static inline bool apply(Point const& point,
                PointOfSegment const& s1, PointOfSegment const& s2,
                counter& state)
    {
        bool eq1 = false;
        bool eq2 = false;
        boost::ignore_unused(eq2);

        int count = check_segment<1>(point, s1, s2, state, eq1, eq2);
        if (count != 0)
        {
            int side = 0;
            if ( count == 1 || count == -1 )
            {
                side = winding_side_equal<typename cs_tag<Point>::type>
                            ::template apply<1>(point, eq1 ? s1 : s2, count);
            }
            else
            {
                side = strategy_side_type::apply(s1, s2, point);
            }

            if (side == 0)
            {
                // Point is lying on segment
                state.m_touches = true;
                state.m_count = 0;
                return false;
            }

            // Side is NEG for right, POS for left.
            // The count is -2 for down, 2 for up (or -1/1)
            // Side positive thus means UP and LEFTSIDE or DOWN and RIGHTSIDE
            // See accompagnying figure (TODO)
            if (side * count > 0)
            {
                state.m_count += count;
            }
        }
        return ! state.m_touches;
    }

    static inline int result(counter const& state)
    {
        return state.code();
    }
};

#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS

namespace services
{

// Register using "areal_tag" for ring, polygon, multi-polygon
template <typename AnyTag, typename Point, typename Geometry>
struct default_strategy<point_tag, AnyTag, point_tag, areal_tag, cartesian_tag, cartesian_tag, Point, Geometry>
{
    typedef winding<Point, typename geometry::point_type<Geometry>::type> type;
};

template <typename AnyTag, typename Point, typename Geometry>
struct default_strategy<point_tag, AnyTag, point_tag, areal_tag, spherical_tag, spherical_tag, Point, Geometry>
{
    typedef winding<Point, typename geometry::point_type<Geometry>::type> type;
};

// TODO: use linear_tag and pointlike_tag the same way how areal_tag is used

template <typename Point, typename Geometry, typename AnyTag>
struct default_strategy<point_tag, AnyTag, point_tag, AnyTag, cartesian_tag, cartesian_tag, Point, Geometry>
{
    typedef winding<Point, typename geometry::point_type<Geometry>::type> type;
};

template <typename Point, typename Geometry, typename AnyTag>
struct default_strategy<point_tag, AnyTag, point_tag, AnyTag, spherical_tag, spherical_tag, Point, Geometry>
{
    typedef winding<Point, typename geometry::point_type<Geometry>::type> type;
};

} // namespace services

#endif

}} // namespace strategy::within

#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS
namespace strategy { namespace covered_by { namespace services
{

// Register using "areal_tag" for ring, polygon, multi-polygon
template <typename AnyTag, typename Point, typename Geometry>
struct default_strategy<point_tag, AnyTag, point_tag, areal_tag, cartesian_tag, cartesian_tag, Point, Geometry>
{
    typedef strategy::within::winding<Point, typename geometry::point_type<Geometry>::type> type;
};

template <typename AnyTag, typename Point, typename Geometry>
struct default_strategy<point_tag, AnyTag, point_tag, areal_tag, spherical_tag, spherical_tag, Point, Geometry>
{
    typedef strategy::within::winding<Point, typename geometry::point_type<Geometry>::type> type;
};

// TODO: use linear_tag and pointlike_tag the same way how areal_tag is used

template <typename Point, typename Geometry, typename AnyTag>
struct default_strategy<point_tag, AnyTag, point_tag, AnyTag, cartesian_tag, cartesian_tag, Point, Geometry>
{
    typedef strategy::within::winding<Point, typename geometry::point_type<Geometry>::type> type;
};

template <typename Point, typename Geometry, typename AnyTag>
struct default_strategy<point_tag, AnyTag, point_tag, AnyTag, spherical_tag, spherical_tag, Point, Geometry>
{
    typedef strategy::within::winding<Point, typename geometry::point_type<Geometry>::type> type;
};

}}} // namespace strategy::covered_by::services
#endif

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_STRATEGY_AGNOSTIC_POINT_IN_POLY_WINDING_HPP


text:
from rest_framework import serializers
from taggit_serializer.serializers import (TagListSerializerField,
                                           TaggitSerializer)
from adventure.models import Adventure, Author, Room, RoomExit, Artifact, Effect, Monster, \
    Hint, HintAnswer

class AuthorSerializer(serializers.ModelSerializer):

    class Meta:
        model = Author
        fields = ('id', 'name')

class AdventureSerializer(serializers.HyperlinkedModelSerializer, TaggitSerializer):
    authors = serializers.StringRelatedField(many=True)
    tags = TagListSerializerField()

    class Meta:
        model = Adventure
        fields = ('id', 'name', 'description', 'full_description', 'intro_text', 'intro_question', 'slug', 'edx',
                  'dead_body_id', 'featured_month', 'date_published', 'authors', 'tags', 'times_played', 'avg_ratings')

class AdventureDesignSerializer(serializers.HyperlinkedModelSerializer, TaggitSerializer):
    """Serializer used for the designer app. Includes additional info."""
    authors = serializers.StringRelatedField(many=True)
    tags = TagListSerializerField()
    # rooms_count = serializers.IntegerField()
    # artifacts_count = serializers.IntegerField()
    # effects_count = serializers.IntegerField()
    # monsters_count = serializers.IntegerField()

    class Meta:
        model = Adventure
        fields = ('id', 'name', 'description', 'full_description', 'intro_text', 'intro_question', 'slug',
                  'featured_month', 'date_published', 'authors', 'tags', 'times_played', 'active'
                  # 'rooms_count', 'artifacts_count', 'effects_count', 'monsters_count'
        )

class RoomExitSerializer(serializers.ModelSerializer):
    class Meta:
        model = RoomExit
        fields = ('direction', 'room_to', 'door_id', 'effect_id')

class RoomSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(source='room_id', read_only=True)
    exits = RoomExitSerializer(many=True, read_only=True)

    class Meta:
        model = Room
        fields = ('id', 'name', 'description', 'is_markdown', 'is_dark',
                  'dark_name', 'dark_description', 'effect', 'effect_inline',
                  'data', 'exits')

class ArtifactSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(source='artifact_id', read_only=True)

    class Meta:
        model = Artifact
        fields = '__all__'

class EffectSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(source='effect_id', read_only=True)

    class Meta:
        model = Effect
        fields = '__all__'

class MonsterSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(source='monster_id', read_only=True)

    class Meta:
        model = Monster
        fields = '__all__'

class HintAnswerSerializer(serializers.ModelSerializer):
    class Meta:
        model = HintAnswer
        fields = ('index', 'answer', 'spoiler')

class HintSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(source='hint_id', read_only=True)
    answers = HintAnswerSerializer(many=True, read_only=True)

    class Meta:
        model = Hint
        fields = ('id', 'index', 'edx', 'question', 'answers')


text:
PRSARCH ;;WOIFO/JAH - Recess Tracking Help List ;11-DEC-2006
 ;;4.0;PAID;**112**;Sep 21, 1995;Build 54
 ;;Per VHA Directive 2004-038, this routine should not be modified.
 Q
EN ;
 D EN^VALM("PRSA RECESS TRACKING HELP")
 S VALMBCK="R"
 Q
HDR ; -- header code
 S VALMHDR(1)="Help Screen for 9 Mo. AWS Recess Tracking Actions"
 S VALMHDR(2)="Enter QU to return to the Schedule"
 Q
 ;
INIT ; -- init variables and list array
 ;
 N TEXT,LEN
 S VALMCNT=0
 F  D  Q:TEXT=""
 .  S VALMCNT=VALMCNT+1
 .  S TEXT=$P($T(HLPTXT+VALMCNT),";",3)
 .  I $E(TEXT,1)?1A D
 ..    S LEN=$L(TEXT)
 ..    S TEXT="              "_TEXT
 ..    D SET^VALM10(VALMCNT,TEXT)
 ..    D CNTRL^VALM10(VALMCNT,15,LEN,IORVON,IORVOFF,0)
 ..   ; D RESTORE^VALM10(VALMCNT)
 .  E  D
 ..   D SET^VALM10(VALMCNT,TEXT)
 Q
HLPTXT ;
 ;;SE  Select Recess Weeks
 ;;    Enter SE at the Select Action prompt to select weeks by the number
 ;;    in the left hand column of the list.  You may select multiple
 ;;    weeks by entering week numbers separated by commas and you may
 ;;    select a range of weeks by using a hyphen.  For example: 3,6-10,12
 ;;    is a valid response to select weeks.  This action will then prompt
 ;;    for the hours to enter for all of the weeks selected.  If the
 ;;    weeks are in the past the tour of duty hours stored in the
 ;;    employee's timecard may be used by accepting the default to use
 ;;    tour of duty hours.  Alternatively you can choose to use the
 ;;    employee's current tour hours from the timecard as the recess
 ;;    hours or you may specify the recess hours for each week of the
 ;;    pay period for the weeks selected.  In all cases the recess hours
 ;;    specified are applied to all the weeks selected.
 ;;EH  Edit Recess Hours
 ;;    Enter EH at the Select Action prompt to select any of the weeks
 ;;    in the list by number.  You will be prompted to enter the recess
 ;;    hours for each week that you selected.
 ;;CR  Cancel Recess Weeks
 ;;    Enter CR at the Select Action prompt to select any of the weeks
 ;;    in the list by number.  Any recess hours from the selection will
 ;;    be removed.
 ;;NS  Change AWS Start
 ;;    Enter NS at the Select Action prompt to change when the AWS
 ;;    schedule takes effect.  Any recess scheduled during the fiscal
 ;;    year that occurs before the new start date is removed.  If you
 ;;    enter a date other than the first day of a pay period the action
 ;;    will automatically set the AWS start date to the first day of
 ;;    the pay period that the date you entered falls within.
 ;;    The number of weeks available for recess is 25% of the weeks
 ;;    from the start date to the end of the fiscal year.
 ;;GH  Recess Hours Summary
 ;;    Enter GH to see a summary screen with recess totals.  Be sure
 ;;    to scroll down to see the whole report.
 ;;SV  Save Recess Schedule
 ;;    Enter SV to save any edits you have made to the schedule and
 ;;    continue editing.
 ;;EX  Exit and Save Recess
 ;;    Enter EX to save any edits you have made to the schedule and exit
 ;;    the option.
 ;;QU  Quit without Saving
 ;;    Enter QU to quit and not save any of the changes you made.
 Q
 ;
HELP ; -- help code
 N X
 S X="?" D DISP^XQORM1 W !!
 Q
 ;
EXIT ; -- exit code
 D CLEAN^VALM10
 Q
 ;
EXPND ; -- expand code
 Q
 ;


text:
__author__ = "Collin Petty"
__copyright__ = "Carnegie Mellon University"
__license__ = "MIT"
__maintainer__ = ["Collin Petty", "Peter Chapman"]
__credits__ = ["David Brumely", "Collin Petty", "Peter Chapman"]
__email__ = ["collin@cmu.edu", "peter@cmu.edu"]
__status__ = "Production"
import os
from random import randint
from operator import add
import tempfile

template_file = "xmlol.xml"
templates = "autogenerators/templates/"

def validate_dependencies():
    print "DEPENDENCY CHECK - xmnlol.py (autogen)"
    if not os.path.exists(_template_path()):
        print "ERROR - xmlol - Could not find the template file (%s)" % template_file
        return False
    return True

def generate():
    template = open(_template_path(), 'r').read()
    key = reduce(add, [str(randint(999, 99999)) for _ in range(6)], '')
    template = template.replace('###KEY###', key)
    output = tempfile.NamedTemporaryFile(delete=False, suffix=".xml")
    output.write(template)
    output.close()
    return [os.path.abspath(output.name)], key, """
The book has instructions on how to dump the corrupted\
     configuration file from the robot's memory. You find a corrupted XML file and are looking for a configuration key.
"""

def _template_path():
    return templates + template_file


text:
<?php

namespace XeroPHP\Models\PayrollAU\Employee;

use XeroPHP\Remote;

class BankAccount extends Remote\Object {

    /**
     * The text that will appear on your employee's bank statement when they receive payment (max length
     * = 18)
     *
     * @property string StatementText
     */

    /**
     * The name of the account (max length = 32)
     *
     * @property string AccountName
     */

    /**
     * The BSB number of the account (length = 6)
     *
     * @property string BSB
     */

    /**
     * The account number (max length = 9)
     *
     * @property string AccountNumber
     */

    /**
     * If this account is the Remaining bank account
     *
     * @property string Remainder
     */

    /**
     * Fixed amounts (for example, if an employee wants to have $100 of their salary transferred to one
     * account, and the remaining amount to another)
     *
     * @property float Amount
     */

    /**
     * Get the resource uri of the class (Contacts) etc
     *
     * @return string
     */
    public static function getResourceURI(){
        return 'BankAccount';
    }

    /**
     * Get the root node name.  Just the unqualified classname
     *
     * @return string
     */
    public static function getRootNodeName(){
        return 'BankAccount';
    }

    /**
     * Get the guid property
     *
     * @return string
     */
    public static function getGUIDProperty(){
        return '';
    }

    /**
     * Get the stem of the API (core.xro) etc
     *
     * @return string|null
     */
    public static function getAPIStem(){
        return Remote\URL::API_PAYROLL;
    }

    /**
     * Get the supported methods
     */
    public static function getSupportedMethods() {
        return array(
        );
    }

    /**
     *
     * Get the properties of the object.  Indexed by constants
     *  [0] - Mandatory
     *  [1] - Type
     *  [2] - PHP type
     *  [3] - Is an Array
     *  [4] - Saves directly
     *
     * @return array
     */
    public static function getProperties() {
        return array(
            'StatementText' => array (false, self::PROPERTY_TYPE_STRING, null, false, false),
            'AccountName' => array (false, self::PROPERTY_TYPE_STRING, null, false, false),
            'BSB' => array (false, self::PROPERTY_TYPE_STRING, null, false, false),
            'AccountNumber' => array (false, self::PROPERTY_TYPE_STRING, null, false, false),
            'Remainder' => array (false, self::PROPERTY_TYPE_STRING, null, false, false),
            'Amount' => array (false, self::PROPERTY_TYPE_FLOAT, null, false, false)
        );
    }

    /**
     * @return string
     */
    public function getStatementText() {
        return isset($this->_data['StatementText']) ? $this->_data['StatementText'] : null;
    }

    /**
     * @param string $value
     * @return BankAccount
     */
    public function setStatementText($value) {
        $this->propertyUpdated('StatementText', $value);
        $this->_data['StatementText'] = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getAccountName() {
        return isset($this->_data['AccountName']) ? $this->_data['AccountName'] : null;
    }

    /**
     * @param string $value
     * @return BankAccount
     */
    public function setAccountName($value) {
        $this->propertyUpdated('AccountName', $value);
        $this->_data['AccountName'] = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getBSB() {
        return isset($this->_data['BSB']) ? $this->_data['BSB'] : null;
    }

    /**
     * @param string $value
     * @return BankAccount
     */
    public function setBSB($value) {
        $this->propertyUpdated('BSB', $value);
        $this->_data['BSB'] = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getAccountNumber() {
        return isset($this->_data['AccountNumber']) ? $this->_data['AccountNumber'] : null;
    }

    /**
     * @param string $value
     * @return BankAccount
     */
    public function setAccountNumber($value) {
        $this->propertyUpdated('AccountNumber', $value);
        $this->_data['AccountNumber'] = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getRemainder() {
        return isset($this->_data['Remainder']) ? $this->_data['Remainder'] : null;
    }

    /**
     * @param string $value
     * @return BankAccount
     */
    public function setRemainder($value) {
        $this->propertyUpdated('Remainder', $value);
        $this->_data['Remainder'] = $value;
        return $this;
    }

    /**
     * @return float
     */
    public function getAmount() {
        return isset($this->_data['Amount']) ? $this->_data['Amount'] : null;
    }

    /**
     * @param float $value
     * @return BankAccount
     */
    public function setAmount($value) {
        $this->propertyUpdated('Amount', $value);
        $this->_data['Amount'] = $value;
        return $this;
    }

}


text:
package com.tassioauad.androiditunesclientlibrary.service.utils;

import com.tassioauad.androiditunesclientlibrary.service.parameter.ParametersListInterface;

/**
 * Created by Tássio on 21/05/2014.
 */
public abstract class ItunesSearchApiUrlBuilder {

    private static final String BASE_URL = "https://itunes.apple.com/search";

    public static String build(ParametersListInterface parametersList) {
        return BASE_URL + "?" + parametersList.toUrlFormat();
    }

}


text:
package com.intellij.ide.util.treeView;

import java.util.Comparator;

public class IndexComparator implements Comparator<NodeDescriptor<?>> {
  public static final IndexComparator INSTANCE = new IndexComparator();

  private IndexComparator() {}

  @Override
  public int compare(NodeDescriptor nodeDescriptor1, NodeDescriptor nodeDescriptor2) {
    return nodeDescriptor1.getIndex() - nodeDescriptor2.getIndex();
  }
}


text:
namespace tpie {

// A bit with two operarators, addition (= XOR) and multiplication (=
// AND).
    class bit {

    private:
	char data;

    public:
	bit(void);
	bit(bool);
	bit(int);
	bit(long int);
	~bit(void);

	operator bool(void);
	operator int(void);
	operator long int(void);

	bit operator+=(bit rhs);
	bit operator*=(bit rhs);

	friend bit operator+(bit op1, bit op2);
	friend bit operator*(bit op1, bit op2);

	friend std::ostream &operator<<(std::ostream &s, bit b);
    };

}  //  tpie namespace

#endif // _TPIE_BIT_H


text:
package com.microsoft.Malmo.MissionHandlers;

public class CommandForHotBarKeysImplementation extends CommandGroup
{
    public CommandForHotBarKeysImplementation()
    {
        setShareParametersWithChildren(true);	// Pass our parameter block on to the following children:
        for (int i = 1; i <= 9; i++)
        {
            addCommandHandler(new CommandForKey("key.hotbar." + i));
        }
    }
}


text:
package com.othershe.dutil.upload;

import java.io.File;

public class DirectUploadBuilder extends BaseUploadBuilder<DirectUploadBuilder> {
    private File file;
    private byte[] bytes;
    private String type;

    public DirectUploadBuilder addFile(File file) {
        bytes = null;
        this.file = file;
        return this;
    }

    public DirectUploadBuilder addByte(byte[] bytes) {
        file = null;
        this.bytes = bytes;
        return this;
    }

    public DirectUploadBuilder addType(String type) {
        this.type = type;
        return this;
    }

    public DirectUploadRequest build() {
        return new DirectUploadRequest(url, file, bytes, type);
    }
}


text:
/**
 * NOTE: This class is auto generated by the swagger code generator program (2.4.0-SNAPSHOT).
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */
package io.github.cloudiator.rest.api;

import io.github.cloudiator.rest.model.Error;
import io.github.cloudiator.rest.model.NewPlatformRuntime;
import io.github.cloudiator.rest.model.PlatformRuntime;
import io.swagger.annotations.*;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import javax.validation.constraints.*;
import java.util.List;

@Api(value = "platformRuntime", description = "the platformRuntime API")
public interface PlatformRuntimeApi {

    @ApiOperation(value = "", nickname = "addPlatformRuntime", notes = "Creates a new PlatformRuntime ", response = PlatformRuntime.class, authorizations = {
        @Authorization(value = "ApiKeyAuth")
    }, tags={ "platform", })
    @ApiResponses(value = {
        @ApiResponse(code = 200, message = "OK ", response = PlatformRuntime.class),
        @ApiResponse(code = 400, message = "Bad Request", response = Error.class),
        @ApiResponse(code = 401, message = "Authorization for this action is missing", response = Error.class),
        @ApiResponse(code = 403, message = "Forbidden action", response = Error.class),
        @ApiResponse(code = 404, message = "Item not found", response = Error.class),
        @ApiResponse(code = 500, message = "An unexpected Error occured", response = Error.class),
        @ApiResponse(code = 504, message = "Server temporary not available", response = Error.class) })
    @RequestMapping(value = "/platformRuntime",
        produces = { "application/json" },
        consumes = { "application/json" },
        method = RequestMethod.POST)
    ResponseEntity<PlatformRuntime> addPlatformRuntime(@ApiParam(value = "PlatformRuntime to be created " ,required=true )  @Valid @RequestBody NewPlatformRuntime platformRuntime);

    @ApiOperation(value = "", nickname = "findPlatformRuntime", notes = "Returns the PlatformRuntime identified by the id parameter. ", response = PlatformRuntime.class, authorizations = {
        @Authorization(value = "ApiKeyAuth")
    }, tags={ "platform", })
    @ApiResponses(value = {
        @ApiResponse(code = 200, message = "OK", response = PlatformRuntime.class),
        @ApiResponse(code = 401, message = "Authorization for this action is missing", response = Error.class),
        @ApiResponse(code = 403, message = "Forbidden action", response = Error.class),
        @ApiResponse(code = 500, message = "An unexpected Error occured", response = Error.class),
        @ApiResponse(code = 504, message = "Server temporary not available", response = Error.class) })
    @RequestMapping(value = "/platformRuntime/{id}",
        produces = { "application/json" },
        method = RequestMethod.GET)
    ResponseEntity<PlatformRuntime> findPlatformRuntime(@ApiParam(value = "Unique identifier of the resource",required=true) @PathVariable("id") String id);

    @ApiOperation(value = "", nickname = "findPlatformRuntimes", notes = "Returns all platform runtime  visible to the user ", response = PlatformRuntime.class, responseContainer = "List", authorizations = {
        @Authorization(value = "ApiKeyAuth")
    }, tags={ "platform", })
    @ApiResponses(value = {
        @ApiResponse(code = 200, message = "OK ", response = PlatformRuntime.class, responseContainer = "List"),
        @ApiResponse(code = 401, message = "Authorization for this action is missing", response = Error.class),
        @ApiResponse(code = 403, message = "Forbidden action", response = Error.class),
        @ApiResponse(code = 500, message = "An unexpected Error occured", response = Error.class),
        @ApiResponse(code = 504, message = "Server temporary not available", response = Error.class) })
    @RequestMapping(value = "/platformRuntime",
        produces = { "application/json" },
        method = RequestMethod.GET)
    ResponseEntity<List<PlatformRuntime>> findPlatformRuntimes();

}


text:
@import url(http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300);
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-weight: 700;
}
body {
  font-family: 'Source Sans Pro', sans-serif;
  color: white;
  font-weight: 300;
  overflow-y: auto;
}
body ::-webkit-input-placeholder {
  /* WebKit browsers */
  font-family: 'Source Sans Pro', sans-serif;
  color: white;
  font-weight: 300;
}
body :-moz-placeholder {
  /* Mozilla Firefox 4 to 18 */
  font-family: 'Source Sans Pro', sans-serif;
  color: white;
  opacity: 1;
  font-weight: 300;
}
body ::-moz-placeholder {
  /* Mozilla Firefox 19+ */
  font-family: 'Source Sans Pro', sans-serif;
  color: white;
  opacity: 1;
  font-weight: 300;
}
body :-ms-input-placeholder {
  /* Internet Explorer 10+ */
  font-family: 'Source Sans Pro', sans-serif;
  color: white;
  font-weight: 300;
}
.wrapper {
  background: #50a3a2;
  background: -webkit-linear-gradient(top left, #50a3a2 0%, #53e3a6 100%);
  background: linear-gradient(to bottom right, #50a3a2 0%, #53e3a6 100%);
  position: absolute;
  left: 0;
  width: 100%;

  overflow: hidden;
}
.wrapper.form-success .container h1 {
  -webkit-transform: translateY(85px);
      -ms-transform: translateY(85px);
          transform: translateY(85px);
}
.container {
  max-width: 600px;
  margin: 0px auto;
  padding: 80px 0;

  text-align: center;
}
.container h1 {
  font-size: 40px;
  -webkit-transition-duration: 1s;
          transition-duration: 1s;
  -webkit-transition-timing-function: ease-in-put;
          transition-timing-function: ease-in-put;
  font-weight: 200;
}

/******************Form CSS********************/
form {
  padding: 20px 0;
  position: relative;
  z-index: 2;
}
form input {
  -webkit-appearance: none;
     -moz-appearance: none;
          appearance: none;
  outline: 0;
  border: 1px solid rgba(255, 255, 255, 0.4);
  background-color: rgba(255, 255, 255, 0.2);
  width: 80%;
  border-radius: 3px;
  padding: 10px 15px;
  margin: 0 auto 15px auto;
  display: block;
  text-align: center;
  font-size: 18px;
  color: white;
  -webkit-transition-duration: 0.25s;
          transition-duration: 0.25s;
  font-weight: 300;
}
form input:hover {
  background-color: rgba(255, 255, 255, 0.4);
}
form input:focus {
  background-color: white;
  width: 300px;
  color: #53e3a6;
}
form button {
  -webkit-appearance: none;
     -moz-appearance: none;
          appearance: none;
  outline: 0;
  background-color: white;
  border: 0;
  padding: 10px 15px;
  color: #53e3a6;
  border-radius: 3px;
  width: 250px;
  cursor: pointer;
  font-size: 18px;
  -webkit-transition-duration: 0.25s;
          transition-duration: 0.25s;
}
form button:hover {
  background-color: #f5f7f9;
}

/************************************************/


text:
angular.module("app.factories").
	factory('releaseFactory', ['$q', '$http', 'url',
		function($q, $http, url) {
			var getRelease = function() {
				var deferred = $q.defer();
				var resource = url.createResourceUrl("release", "releaseId", "1");

				$http.get(resource.toString()).success(function(data, status, headers, config) {
					// this callback will be called asynchronously when the response is available
					deferred.resolve(data);
				});

				return deferred.promise;
			};

			return {
				getRelease: getRelease
			};
	}]
);


text:
module HorizEclat where

import FileIO
import HasseTree

main path file minSupport = do
    dataSet <- importData path file
    let frequents = horizEclat dataSet minSupport
    exportResult path file $ toString frequents
    --putStrLn $ show frequents

condDS :: [ItemSet] -> Item -> ([ItemSet], [ItemSet])
condDS [] _ = ([], [])
condDS ([]:dsT) condition = condDS dsT condition     -- condition occurs when ??? (i'm not sure but it doesn't work without)
condDS (dsH@(dsHH:dsHT):dsT) condition
    | dsHH == condition = ((dsHT:containCondRemoved), (dsHT:allCondRemoved))
    | dsHH /= condition = (containCondRemoved, (dsH:allCondRemoved)) where
        tailResult = condDS dsT condition
        containCondRemoved = fst tailResult
        allCondRemoved = snd tailResult

horizEclat :: [ItemSet] -> Int -> HasseTree
horizEclat ds minSupport = horizEclat' ds minSupport $ resetLeafCounts $ singletons ds 0

horizEclat' :: [ItemSet] -> Int -> HasseTree -> HasseTree
horizEclat' _ _ [] = []
horizEclat' is minSupport remaining@((HasseLeafNode itm n):remT)
    | sup < minSupport = sndSubproblem
    | sup >= minSupport = (HasseTreeNode itm sup fstSubproblem):sndSubproblem where
        sup = length containingRemoved
        containingRemoved = fst conditional
        allRemoved = snd conditional
        conditional = condDS is itm
        sndSubproblem = horizEclat' allRemoved minSupport remT
        fstSubproblem = horizEclat' containingRemoved minSupport remT


text:
package me.prettyprint.cassandra.service;

import java.util.Map;

import me.prettyprint.cassandra.connection.HConnectionManager;
import me.prettyprint.hector.api.ConsistencyLevelPolicy;
import me.prettyprint.hector.api.exceptions.HectorTransportException;

/**
 *
 * @author Ran Tavory (rantav@gmail.com)
 *
 */
/*package*/ class KeyspaceServiceFactory {

  private final CassandraClientMonitor clientMonitor;

  public KeyspaceServiceFactory(CassandraClientMonitor clientMonitor) {
    this.clientMonitor = clientMonitor;
  }

  public KeyspaceService create(String keyspaceName,
      ConsistencyLevelPolicy consistencyLevel,
      HConnectionManager connectionManager,
      FailoverPolicy failoverPolicy)
      throws HectorTransportException {
    return new KeyspaceServiceImpl(keyspaceName, consistencyLevel,
        connectionManager, failoverPolicy);
  }
  public KeyspaceService create(String keyspaceName,
      ConsistencyLevelPolicy consistencyLevel,
      HConnectionManager connectionManager,
      FailoverPolicy failoverPolicy,
      Map<String, String> credentials)
      throws HectorTransportException {
    return new KeyspaceServiceImpl(keyspaceName, consistencyLevel,
        connectionManager, failoverPolicy, credentials);
  }
}


text:
package game_wkc10;

import javafx.animation.KeyFrame;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Duration;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyEvent;

/**
 * BossLevel Instantiator for Game
 * Includes Boiler Code from Robert Duvall
 * @author William Chang
 *
 */
class BossLevel extends GameInteractionPage{
	//Background Image
	private Image image;
	private ImageView imageView;
	/**
	 *  Function to do each game frame
	 */
	private EventHandler<ActionEvent> oneFrame = new EventHandler<ActionEvent>() {
		@Override
		public void handle(ActionEvent event) {
			processKeyStroke();
			manager.updateAllObjects();
			//processKeyRelease();

		}
	};

	/**
	 * Create the game's scene
	 */
	public Scene init (Stage s, int width, int height) {
		// Create a scene graph to organize the scene
		root = new Group();
		// Create a place to see the shapes
		scene = new Scene(root, width, height, Color.LIGHTGREY);
		scene.getStylesheets().add(GameData.STYLE_LOCATION);

		image = new Image(getClass().getResourceAsStream("images/GameBackground.jpg"));
		imageView = new ImageView();
		imageView.setImage(image);
		imageView.setX(GameData.SCREEN_WIDTH/2-image.getWidth()/2);
		imageView.setY(GameData.SCREEN_LENGTH/2-image.getHeight()/2);
		root.getChildren().add(imageView);

		manager = new GameManager(root, new WaveGenerator());
		manager.loadCharacters("boss");
		return scene;
	}

	/**
	 * Create the game's frame
	 */
	public KeyFrame start () {
		return new KeyFrame(Duration.millis(1000/60), oneFrame);
	}

	/**
	 * Processes Key Strokes through GameManager
	 */
	public void processKeyStroke(){
		scene.setOnKeyPressed(new EventHandler<KeyEvent>(){
			@Override
			public void handle(KeyEvent event) {
				manager.doPlayerAction(event.getCode());
			}
		});
	}

}


text:
package org.apache.nutch.net.urlnormalizer.regex;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.nutch.net.URLNormalizers;
import org.apache.nutch.util.NutchConfiguration;

/** Unit tests for RegexUrlNormalizer. */
public class TestRegexURLNormalizer {
  private static final Logger LOG = LoggerFactory
      .getLogger(TestRegexURLNormalizer.class);

  private RegexURLNormalizer normalizer;
  private Configuration conf;
  private HashMap<String, NormalizedURL[]> testData = new HashMap<String, NormalizedURL[]>();

  // This system property is defined in ./src/plugin/build-plugin.xml
  private String sampleDir = System.getProperty("test.data", ".");

  // Make sure sample files are copied to "test.data" as specified in
  // ./src/plugin/urlnormalizer-regex/build.xml during plugin compilation.

  @Before
  public void setUp() throws IOException {
    normalizer = new RegexURLNormalizer();
    conf = NutchConfiguration.create();
    normalizer.setConf(conf);
    File[] configs = new File(sampleDir).listFiles(new FileFilter() {
      public boolean accept(File f) {
        if (f.getName().endsWith(".xml")
            && f.getName().startsWith("regex-normalize-"))
          return true;
        return false;
      }
    });
    for (int i = 0; i < configs.length; i++) {
      try {
        FileReader reader = new FileReader(configs[i]);
        String cname = configs[i].getName();
        cname = cname.substring(16, cname.indexOf(".xml"));
        normalizer.setConfiguration(reader, cname);
        NormalizedURL[] urls = readTestFile(cname);
        testData.put(cname, urls);
      } catch (Exception e) {
        LOG.warn("Could load config from '" + configs[i] + "': " + e.toString());
      }
    }
  }

  @Test
  public void testNormalizerDefault() throws Exception {
    normalizeTest((NormalizedURL[]) testData.get(URLNormalizers.SCOPE_DEFAULT),
        URLNormalizers.SCOPE_DEFAULT);
  }

  @Test
  public void testNormalizerScope() throws Exception {
    Iterator<String> it = testData.keySet().iterator();
    while (it.hasNext()) {
      String scope = it.next();
      normalizeTest((NormalizedURL[]) testData.get(scope), scope);
    }
  }

  private void normalizeTest(NormalizedURL[] urls, String scope)
      throws Exception {
    for (int i = 0; i < urls.length; i++) {
      String url = urls[i].url;
      String normalized = normalizer.normalize(urls[i].url, scope);
      String expected = urls[i].expectedURL;
      LOG.info("scope: " + scope + " url: " + url + " | normalized: "
          + normalized + " | expected: " + expected);
      assertEquals(urls[i].expectedURL, normalized);
    }
  }

  /**
   * Currently this is not being used in this class private void bench(int
   * loops, String scope) { long start = System.currentTimeMillis(); try {
   * NormalizedURL[] expected = (NormalizedURL[])testData.get(scope); if
   * (expected == null) return; for (int i = 0; i < loops; i++) {
   * normalizeTest(expected, scope); } } catch (Exception e) {
   * fail(e.toString()); } LOG.info("bench time (" + loops + ") " +
   * (System.currentTimeMillis() - start) + "ms"); }
   */

  private static class NormalizedURL {
    String url;
    String expectedURL;

    public NormalizedURL(String line) {
      String[] fields = line.split("\\s+");
      url = fields[0];
      expectedURL = fields[1];
    }
  }

  private NormalizedURL[] readTestFile(String scope) throws IOException {
    File f = new File(sampleDir, "regex-normalize-" + scope + ".test");
    BufferedReader in = new BufferedReader(new InputStreamReader(
        new FileInputStream(f), "UTF-8"));
    List<NormalizedURL> list = new ArrayList<NormalizedURL>();
    String line;
    while ((line = in.readLine()) != null) {
      if (line.trim().length() == 0 || line.startsWith("#")
          || line.startsWith(" "))
        continue;
      list.add(new NormalizedURL(line));
    }
    in.close();
    return (NormalizedURL[]) list.toArray(new NormalizedURL[list.size()]);
  }
}


text:
package uk.ac.ebi.eva.pipeline.runner.exceptions;

import java.io.IOException;

/**
 * Unexpected error while reading or processing a file
 */
public class UnexpectedErrorReadingFileException extends Exception {

    public UnexpectedErrorReadingFileException(String filePath, IOException e) {
        super("Unexpected error reading file '" + filePath + "'", e);
    }

}