text:
<?php

// PATHS
define('TMP_DIR', './tmp/liquipedia/');
define('SMILIES_DIR', './forum/images/smilies/');
define('LOGFILE', './log/lp_embed.log');

define('IMG_PROTOSS', 'Protoss.png');
define('IMG_TERRAN', 'Terran.png');
define('IMG_ZERG', 'Zerg.png');
define('IMG_RANDOM', 'Random.png');

// LOG
define('LOG', true);

// CACHE
define('CACHE_DUR', 60 * 30); // 30 min for ongoing events
define('CACHE_DUR_FIN', 60 * 60 * 24 * 90); // 90 days for finished events
define('CACHE_DUR_FUT', 60 * 60 * 24 * 7); // 7 days for future events

// TIME
define('TIMEZONE', 2); // hours to UTC
date_default_timezone_set('Europe/Helsinki');
setlocale(LC_ALL, array('fi_FI.UTF-8', 'fi_FI@euro', 'fi_FI', 'finnish'));

// LAYOUT
define('GROUPS_PER_ROW', 3);

// TEXTS
define('EMPTY_NAME', 'tbd');
define('BYE_NAME', 'bye');

define('BAD_URL', 'Error: Bad URL.');
define('BRACKET_NOT_FOUND', 'No brackets found.');
define('GROUP_NOT_FOUND', 'No groups found.');

define('GROUP_NAME', 'Lohko');
define('SHOW_GROUP_MATCHES', 'Ottelut ↓');
define('HIDE_GROUP_MATCHES', 'Piilota ↑');

define('FINAL_MATCH', 'Finaali');
define('SEMIFINAL_MATCH', 'Semifinaali');
define('BRONZE_MATCH', 'Pronssi');
define('GRAND_FINAL', 'Suurfinaali');


text:
package be.degreyt.mmdoc.byndr.services.impl;

import be.degreyt.mmdoc.byndr.services.ByndrService;
import com.google.inject.AbstractModule;

public class ByndrServicesModule extends AbstractModule {

    @Override
    protected void configure() {
        bind(ByndrService.class).to(ByndrServiceImpl.class);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>net.cupric</groupId>
    <artifactId>samson-parent</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent>

  <artifactId>samson-jvm</artifactId>
  <name>SamsoN JVM</name>

  <dependencies>
    <dependency>
      <groupId>net.cupric</groupId>
      <artifactId>samson-core</artifactId>
      <version>${project.version}</version>
    </dependency>
  </dependencies>
</project>


text:
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', 'build'))

import time
import psmove

while True:
    print('checking...')
    psmove.reinit() # need this to re-enumerate new/disconnected devices
    moves = [psmove.PSMove(x) for x in range(psmove.count_connected())]

    print('connections:', sum(m.connection_type == psmove.Conn_USB
            for m in moves), 'usb,', \
                    sum(m.connection_type == psmove.Conn_Bluetooth
            for m in moves), 'bluetooth.')

    for move in moves:
        if move.connection_type == psmove.Conn_Bluetooth:
            # wait for the first valid input report from that controller
            while not move.poll():
                pass

            battery = move.get_battery()

            if battery == 5: # 100% - green
                move.set_leds(0, 255, 0)
            elif battery == 4: # 80% - green-ish
                move.set_leds(128, 200, 0)
            elif battery == 3: # 60% - yellow
                move.set_leds(255, 255, 0)
            else: # <= 40% - red
                move.set_leds(255, 0, 0)
            move.update_leds()
        del move # make sure the controller object is freed to avoid segfaults
    moves = []
    time.sleep(1)


text:
/*
* <auto-generated>
*     This code was generated by a tool.
*
*     Changes to this file may cause incorrect behavior and will be lost if
*     the code is regenerated.
* </auto-generated>
*/

#import "MOZUURLComponents.h"

@interface MOZUAdjustmentURLComponents : NSObject

//
#pragma mark -
#pragma mark Get Operations
#pragma mark -
//

//
#pragma mark -
#pragma mark POST Operations
#pragma mark -
//

//
#pragma mark -
#pragma mark PUT Operations
#pragma mark -
//

/**
Resource Url Components for applyShippingAdjustment
@param orderId Unique identifier of the order.
@param updateMode Specifies whether to update the original order, update the order in draft mode, or update the order in draft mode and then commit the changes to the original. Draft mode enables users to make incremental order changes before committing the changes to the original order. Valid values are "ApplyToOriginal," "ApplyToDraft," or "ApplyAndCommit."
@param version System-supplied integer that represents the current version of the order, which prevents users from unintentionally overriding changes to the order. When a user performs an operation for a defined order, the system validates that the version of the updated order matches the version of the order on the server. After the operation completes successfully, the system increments the version number by one.
@param responseFields Use this field to include those fields which are not included by default.
*/
+ (MOZUURLComponents *)URLComponentsForApplyShippingAdjustmentOperationWithOrderId:(NSString *)orderId updateMode:(NSString *)updateMode version:(NSString *)version responseFields:(NSString *)responseFields;

/**
Resource Url Components for applyAdjustment
@param orderId Unique identifier of the order.
@param updateMode Specifies whether to update the original order, update the order in draft mode, or update the order in draft mode and then commit the changes to the original. Draft mode enables users to make incremental order changes before committing the changes to the original order. Valid values are "ApplyToOriginal," "ApplyToDraft," or "ApplyAndCommit."
@param version System-supplied integer that represents the current version of the order, which prevents users from unintentionally overriding changes to the order. When a user performs an operation for a defined order, the system validates that the version of the updated order matches the version of the order on the server. After the operation completes successfully, the system increments the version number by one.
@param responseFields Use this field to include those fields which are not included by default.
*/
+ (MOZUURLComponents *)URLComponentsForApplyAdjustmentOperationWithOrderId:(NSString *)orderId updateMode:(NSString *)updateMode version:(NSString *)version responseFields:(NSString *)responseFields;

//
#pragma mark -
#pragma mark Delete Operations
#pragma mark -
//

/**
Resource Url Components for removeShippingAdjustment
@param orderId Unique identifier of the order.
@param updateMode Specifies whether to update the original order, update the order in draft mode, or update the order in draft mode and then commit the changes to the original. Draft mode enables users to make incremental order changes before committing the changes to the original order. Valid values are "ApplyToOriginal," "ApplyToDraft," or "ApplyAndCommit."
@param version System-supplied integer that represents the current version of the order, which prevents users from unintentionally overriding changes to the order. When a user performs an operation for a defined order, the system validates that the version of the updated order matches the version of the order on the server. After the operation completes successfully, the system increments the version number by one.
*/
+ (MOZUURLComponents *)URLComponentsForRemoveShippingAdjustmentOperationWithOrderId:(NSString *)orderId updateMode:(NSString *)updateMode version:(NSString *)version;

/**
Resource Url Components for removeAdjustment
@param orderId Unique identifier of the order.
@param updateMode Specifies whether to update the original order, update the order in draft mode, or update the order in draft mode and then commit the changes to the original. Draft mode enables users to make incremental order changes before committing the changes to the original order. Valid values are "ApplyToOriginal," "ApplyToDraft," or "ApplyAndCommit."
@param version System-supplied integer that represents the current version of the order, which prevents users from unintentionally overriding changes to the order. When a user performs an operation for a defined order, the system validates that the version of the updated order matches the version of the order on the server. After the operation completes successfully, the system increments the version number by one.
*/
+ (MOZUURLComponents *)URLComponentsForRemoveAdjustmentOperationWithOrderId:(NSString *)orderId updateMode:(NSString *)updateMode version:(NSString *)version;

@end


text:
var _ = require('lodash');

exports.parse = function(node, state) {
	state = _.extend(state, {
		itemContainerDefinition: {
			children: [
				{ name:'Alloy.Abstract.BarItemTypes', property:'labels' }
			],
			translations: [
				{ from: 'Alloy.Abstract.Labels', to: 'Alloy.Abstract.BarItemTypes' }
			]
		}
	});
	return require('./Alloy.Abstract._ItemContainer').parse(node, state);
};


text:
#ifndef RTCONFIG_PROJECT_H__
#define RTCONFIG_PROJECT_H__

#define RT_HEAP_SIZE   (1024*1024*8)

#if defined(_MSC_VER)
#define NORESOURCE  /* RT_VESRION in winuser.h */
#define _CRT_ERRNO_DEFINED  /* errno macro redefinition */
#define _INC_WTIME_INL /* dfs_elm.c time.h conflicts with wtime.inl */
#define _INC_TIME_INL /* dfs_elm.c time.h conflicts with wtime.inl */
#define _CRT_DECLARE_NONSTDC_NAMES 0 /* avoid to conflict with the inherent STDC in VS */

/* disable some warning in MSC */
#pragma warning(disable:4273)   /* to ignore: warning C4273: inconsistent dll linkage */
#pragma warning(disable:4312)   /* to ignore: warning C4312: 'type cast' : conversion from 'rt_uint32_t' to 'rt_uint32_t *' */
#pragma warning(disable:4311)   /* to ignore: warning C4311: 'type cast' : pointer truncation from 'short *__w64 ' to 'long' */
#pragma warning(disable:4996)   /* to ignore: warning C4996: The POSIX name for this item is deprecated. */
#pragma warning(disable:4267)   /* to ignore: warning C4267: conversion from 'size_t' to 'rt_size_t', possible loss of data */
#pragma warning(disable:4244)   /* to ignore: warning C4244: '=' : conversion from '__w64 int' to 'rt_size_t', possible loss of data */

#endif /* end of _MSC_VER */

#endif


text:
__all__ = ['compare_traces']

from typing import Tuple, List, Tuple, Set, Type
import argparse
import logging
import json
import os
import sys
import numpy as np

import houston
import houston.ardu.copter
from houston import System
from houston.exceptions import HoustonException
from houston import Mission, MissionTrace, State
from houston.state import Variable

logger = logging.getLogger("houston")  # type: logging.Logger
logger.setLevel(logging.DEBUG)

DESCRIPTION = """
Compares two sets of traces, generated using the same mission, to determine
whether there is a significant difference between them (i.e., does the robot
appear to behave differently?).
""".strip()

SYSTEM = System.get_by_name('arducopter')

categorical=['mode', 'armed', 'ekf_ok', 'armable']
continuous=['heading', 'home_latitude', 'groundspeed', 'airspeed', 'roll', 'pitch', 'latitude', 'longitude', 'home_longitude', 'yaw', 'altitude'] #'vx', 'vy', 'vz']

def traces_contain_same_commands(traces: List[MissionTrace]) -> bool:
    """
    Determines whether a list of traces contain the same sequence of
    command executions.
    """
    assert traces is not []

    expected = [ct.command for ct in traces[0].commands]
    for t in traces[1:]:
        actual = [ct.command for ct in t.commands]
        if actual != expected:
            logger.debug("expected: %s, actual: %s", expected, actual)
            return False

    return True

# FIXME precompute
def obtain_var_names(cls_state: Type[State]) -> Tuple[Set[str], Set[str]]:
    """
    Obtains the names of the categorial and continuous variables for a system.

    Parameters:
        cls_state: The class used to model the state of the system.

    Returns:
        A tuple of the form, (categorial, continuous), where each member of
        that tuple contains the set of the names of the categorial/continuous
        variables for the system.
    """
    variables = list(cls_state.variables[v] for v in cls_state.variables)
    categorical = set()  # type: Set[str]
    continuous = set()  # type: Set[str]
    for var in variables:
        if var.typ in [int, float]:
            continuous.add(var.name)
        else:
            categorical.add(var.name)
    logger.debug("categorical variables: %s", ', '.join(categorical))
    logger.debug("continuous variables: %s", ', '.join(continuous))
    return (categorical, continuous)

# TODO implement SimpleTrace class
# simplify each trace to a sequence of states, representing the state
# of the system after the completion (or non-completion) of each command.
def simplify_trace(t: MissionTrace) -> Tuple[State, ...]:
    return tuple(ct.states[-1] for ct in t.commands)

def is_truth_valid(truth: List[MissionTrace],
                   tol: float = 2.0) -> bool:
    """
    Determines whether the ground truth traces are valid to be considered
    for evaluation.

    Parameters:
        truth: a set of ground truth traces, generated
            from repeat executions using an identical configuration/version of
            the SUT.

    Returns:
        True if the ground truth is valid, False otherwise.
    """

    if not truth:
        logger.debug("ground truth set must not be empty.")
        return False

    if not truth[0].commands:
        logger.debug("ground truth execution must perform at least one command.")
        return False

    # ensure that all traces within the ground truth set execute an identical
    # sequence of commands
    if not traces_contain_same_commands(truth):
        for i, trace in enumerate(truth):
            logger.debug("trace %d: #%d commands", i, len(trace.commands))
        logger.debug("ground truth traces have inconsistent structure")
        return False

    state_cls = truth[0].commands[0].states[0].__class__
#    categorical, continuous = obtain_var_names(state_cls)
    simple_truth = [simplify_trace(t) for t in truth]

    # check that categorical variable values are consistent between ground
    # truth traces
    def categorical_eq(var: str,
                       state_traces: List[Tuple[State]]) -> bool:
        collapse = lambda st: tuple(s[var] for s in st)
        expected = collapse(state_traces[0])
        return all(collapse(st) == expected for st in state_traces)

    def all_categoricals_eq(state_traces: List[Tuple[State]]) -> bool:
        return all(categorical_eq(v, state_traces) for v in categorical)

#    if not all_categoricals_eq(simple_truth):
#        logger.debug("failed to compare traces: inconsistent categorical values within ground truth.")
#        return False

    num_commands = len(truth[0].commands)
    size_truth = len(truth)
    all_vars = SYSTEM.state.variables
    for i in range(num_commands):
        for var in continuous:
            vals = np.array([float(simple_truth[j][i][var])
                             for j in range(size_truth)])
            max_diff = max(vals) - min(vals)
            tolerance = (all_vars[var].noise or 0.0) * tol
            is_nearly_eq = np.isclose(max_diff, 0.0,
                                      rtol=1e-05, atol=tolerance, equal_nan=False)
            # logger.debug("%d:%s (%.9f +/-%.9f)", i, var, mid, tolerance)
            logger.debug("parameter [%s]: |%f|",
                         var, max_diff)
            if not is_nearly_eq:
                logger.debug("difference for parameter [%s] exceeds threshold (+/-%f)",
                             var, tolerance)
                return False

    return True

def matches_ground_truth(
        candidate: MissionTrace,
        truth: List[MissionTrace],
        tolerance_factor: float = 1.0
        ) -> bool:
    """
    Determines whether a given trace, referred to as the candidate trace,
    is approximately equivalent to a set of ground truth traces for the
    same mission.

    Parameters:
        mission: the mission used to generate all traces.
        candidate: the candidate trace.
        truth: a set of ground truth traces for the provided mission, generated
            from repeat executions using an identical configuration/version of
            the SUT.
        tolerance_factor: the number of standard deviations that an observed
            (continuous) variable is allowed to deviate from the mean before
            that observation is considered to be an outlier.

    Returns:
        True if candidate trace is approximately equivalent to the ground
        truth.
    """

    truth = [t for t in truth if t.commands]
    if not is_truth_valid(truth):
        return False

    # determine the sets of categorical and continuous variables
    state_cls = truth[0].commands[0].states[0].__class__
    categorical, continuous = obtain_var_names(state_cls)

    simple_candidate = simplify_trace(candidate)
    simple_truth = [simplify_trace(t) for t in truth]

    # check if the candidate trace executes a different sequence of commands
    # to the ground truth
    if not traces_contain_same_commands([candidate, truth[0]]):
        logger.debug("candidate trace doesn't have same commands as the truth")
        return False

    # use the ground truth to build a distribution of expected values for
    # each continuous variable after the completion of each command
    num_commands = len(truth[0].commands)
    size_truth = len(truth)
    all_vars = SYSTEM.state.variables
    for i in range(num_commands):
        for var in continuous:
            vals = np.array([float(simple_truth[j][i][var])
                             for j in range(size_truth)])
            actual = simple_candidate[i][var]
            mid = max(vals) - ((max(vals) - min(vals)) / 2)
#            tolerance = (max(vals) - min(vals)) / 2
#            tolerance *= tolerance_factor
            tolerance = (all_vars[var].noise or 0.0) * tolerance_factor
            diff = abs(mid - actual)
            is_nearly_eq = np.isclose(mid, actual,
                                      rtol=1e-05, atol=tolerance, equal_nan=False)
            # logger.debug("%d:%s (%.9f +/-%.9f)", i, var, mid, tolerance)
            logger.debug("parameter [%s]: |%f - %f| = %f",
                         var, mid, actual, diff)
            if not is_nearly_eq:
                logger.debug("difference for parameter [%s] exceeds threshold (+/-%f)",
                             var, all_vars[var].noise)
                return False

    return True

def setup_logging(verbose: bool = False) -> None:
    log_to_stdout = logging.StreamHandler()
    log_to_stdout.setLevel(logging.DEBUG if verbose else logging.INFO)
    logger.addHandler(log_to_stdout)
    logging.getLogger('houston').addHandler(log_to_stdout)

def parse_args():
    p = argparse.ArgumentParser(description=DESCRIPTION)
    p.add_argument('candidate', type=str, help='path to a candidate trace file.')
    p.add_argument('groundtruth', type=str,
                   help='path to a ground truth trace file.')
    p.add_argument('--verbose', action='store_true',
                   help='increases logging verbosity.')
    return p.parse_args()

def load_file(fn: str) -> Tuple[Mission, List[MissionTrace]]:
    system = System.get_by_name('arducopter')
    try:
        with open(fn, 'r') as f:
            jsn = json.load(f)
            mission = Mission.from_dict(jsn['mission'])
            traces = [MissionTrace.from_dict(t, SYSTEM) for t in jsn['traces']]
        return (mission, traces)
    except FileNotFoundError:
        logger.error("failed to load trace file [%s]: file not found",
                     fn)
        raise
    except Exception:
        logger.exception("failed to load trace file [%s]", fn)
        raise

def main():
    args = parse_args()
    setup_logging(args.verbose)

    try:
        mission_cand, traces_cand = load_file(args.candidate)
        mission_truth, traces_truth = load_file(args.groundtruth)
    except Exception:
        logger.exception("failed to load trace files")
        sys.exit(1)

    if len(traces_cand) != 1:
        logger.error("candidate trace file must only contain one trace.")
        sys.exit(1)

    if mission_cand != mission_truth:
        logger.error("failed to compare traces: %s",
                     "all traces should come from the same mission.")
        sys.exit(1)

    if matches_ground_truth(traces_cand[0], traces_truth):
        logger.info("RESULT: Equivalent.")
    else:
        logger.info("RESULT: Nonequivalent")

if __name__ == '__main__':
    main()


text:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateReactionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('reactions', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('post_id')->index();
            $table->unsignedInteger('user_id')->index();
            $table->string('type');
            $table->timestamps();
            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');
            $table->foreign('post_id')
                ->references('id')
                ->on('posts')
                ->onDelete('cascade');
            $table->unique(['user_id', 'post_id']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('reactions');
    }
}


text:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>js-graph.it homepage</title>

<link rel="stylesheet" type="text/css" href="js-graph-it.css" />
<link rel="stylesheet" type="text/css" href="sf-homepage.css" />

overview

story of this project

getting started

forum

bugs

download

Getting started

Drag and drop

	<html>

	  <head>

	    <script type="text/javascript" src="../js-graph-it.js"></script>

	    <link rel="stylesheet" type="text/css" href="../js-graph-it.css">

	    <style>

	      .block { position: absolute; }

	    </style>

	  </head>

	  <body onload="initPageObjects();">

	    <div class="canvas" id="mainCanvas"

	      style="width: 350px; height: 250px; border: 1px solid black;">

	      <h1 class="block draggable" id="h1_block"

	        style="left: 10px; top: 10px;">

	          h1 block

	      </h1>

	      <h2 class="block draggable" id="h2_block"

	        style="left: 200px; top: 100px;">

	        h2 block

	      </h2>

	      <div class="connector h1_block h2_block"></div>

	    </div>

	  </body>

	</html>

Activating drag and drop on the blocks is very simple: just add the draggable class to them.

The draggable class can be applied to any element in an html page... A little bonus that
comes with <dfn>js-graph-it</dfn>.

Just a note: draggable elements must have absolute positioning and
they cannot be dragged outside the bounds of their parent element (as it happens with the canvas).

	« previous

	next »


text:
#region Copyright notice and license

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

#endregion

using System.CommandLine.IO;
using System.CommandLine.Parsing;
using Grpc.Dotnet.Cli.Commands;
using Microsoft.Build.Evaluation;
using NUnit.Framework;

namespace Grpc.Dotnet.Cli.Tests;

[TestFixture]
public class RemoveCommandTests : TestBase
{
    [Test]
    [NonParallelizable]
    public async Task Commandline_Remove_RemovesReferences()
    {
        // Arrange
        var currentDir = Directory.GetCurrentDirectory();
        var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
        var testConsole = new TestConsole();
        new DirectoryInfo(Path.Combine(currentDir, "TestAssets", "ProjectWithReference")).CopyTo(tempDir);

        var parser = Program.BuildParser(CreateClient());

        // Act
        var result = await parser.InvokeAsync($"remove -p {tempDir} {Path.Combine("Proto", "a.proto")}", testConsole);

        // Assert
        Assert.AreEqual(0, result, testConsole.Error.ToString());

        var project = ProjectCollection.GlobalProjectCollection.LoadedProjects.Single(p => p.DirectoryPath == tempDir);
        project.ReevaluateIfNecessary();

        var protoRefs = project.GetItems(CommandBase.ProtobufElement);
        Assert.AreEqual(0, protoRefs.Count);
        Assert.True(File.Exists(Path.Combine(project.DirectoryPath, "Proto", "a.proto")));

        // Cleanup
        Directory.Delete(tempDir, true);
    }

    [Test]
    [NonParallelizable]
    public void Remove_RemovesReferences()
    {
        // Arrange
        var currentDir = Directory.GetCurrentDirectory();
        var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
        new DirectoryInfo(Path.Combine(currentDir, "TestAssets", "ProjectWithReference")).CopyTo(tempDir);

        // Act
        Directory.SetCurrentDirectory(tempDir);
        var command = new RemoveCommand(new TestConsole(), null, CreateClient());
        command.Remove(new[] { Path.Combine("Proto", "a.proto") });

        // Assert
        var protoRefs = command.Project.GetItems(CommandBase.ProtobufElement);
        Assert.AreEqual(0, protoRefs.Count);
        Assert.True(File.Exists(Path.Combine(command.Project.DirectoryPath, "Proto", "a.proto")));

        // Cleanup
        Directory.SetCurrentDirectory(currentDir);
        Directory.Delete(tempDir, true);
    }
}


text:
mlpack: a scalable C++ machine learning library
===============================================

mlpack is an intuitive, fast, scalable C++ machine learning library, meant to be
a machine learning analog to LAPACK. It aims to implement a wide array of
machine learning methods and functions as a "swiss army knife" for machine
learning researchers.

**Download [current stable version (2.0.1)](http://www.mlpack.org/files/mlpack-2.0.1.tar.gz).**

[![Build Status](http://big.mlpack.org:7780/job/mlpack%20-%20git%20commit%20test/badge/icon)](http://big.mlpack.org:7780/job/mlpack%20-%20git%20commit%20test/)

0. Contents
-----------

  1. [Introduction](#1-introduction)
  2. [Citation details](#2-citation-details)
  3. [Dependencies](#3-dependencies)
  4. [Building mlpack from source](#4-building-mlpack-from-source)
  5. [Running mlpack programs](#5-running-mlpack-programs)
  6. [Further documentation](#6-further-documentation)
  7. [Bug reporting](#7-bug-reporting)

1. Introduction
---------------

The mlpack website can be found at http://www.mlpack.org and contains numerous
tutorials and extensive documentation.  This README serves as a guide for what
mlpack is, how to install it, how to run it, and where to find more
documentation. The website should be consulted for further information:

  - [mlpack homepage](http://www.mlpack.org/)
  - [Tutorials](http://www.mlpack.org/docs/mlpack-git/doxygen.php?doc=tutorials.html)
  - [Development Site (Github)](http://www.github.com/mlpack/mlpack/)
  - [API documentation](http://www.mlpack.org/docs/mlpack-git/doxygen.php)

2. Citation details
-------------------

If you use mlpack in your research or software, please cite mlpack using the
citation below (given in BiBTeX format):

    @article{mlpack2013,
      title     = {{mlpack}: A Scalable {C++} Machine Learning Library},
      author    = {Curtin, Ryan R. and Cline, James R. and Slagle, Neil P. and
                   March, William B. and Ram, P. and Mehta, Nishant A. and Gray,
                   Alexander G.},
      journal   = {Journal of Machine Learning Research},
      volume    = {14},
      pages     = {801--805},
      year      = {2013}
    }

Citations are beneficial for the growth and improvement of mlpack.

3. Dependencies
---------------

mlpack has the following dependencies:

      Armadillo     >= 4.100.0
      Boost (program_options, math_c99, unit_test_framework, serialization)
      CMake         >= 2.8.5

All of those should be available in your distribution's package manager.  If
not, you will have to compile each of them by hand.  See the documentation for
each of those packages for more information.

If you are compiling Armadillo by hand, ensure that LAPACK and BLAS are enabled.

4. Building mlpack from source
------------------------------

(see also [Building mlpack From Source](http://www.mlpack.org/doxygen.php?doc=build.html))

mlpack uses CMake as a build system and allows several flexible build
configuration options. One can consult any of numerous CMake tutorials for
further documentation, but this tutorial should be enough to get mlpack built
and installed.

First, unpack the mlpack source and change into the unpacked directory.  Here we
use mlpack-x.y.z where x.y.z is the version.

    $ tar -xzf mlpack-x.y.z.tar.gz
    $ cd mlpack-x.y.z

Then, make a build directory.  The directory can have any name, not just
'build', but 'build' is sufficient.

    $ mkdir build
    $ cd build

The next step is to run CMake to configure the project.  Running CMake is the
equivalent to running `./configure` with autotools. If you run CMake with no
options, it will configure the project to build with no debugging symbols and no
profiling information:

    $ cmake ../

You can specify options to compile with debugging information and profiling
information:

    $ cmake -D DEBUG=ON -D PROFILE=ON ../

Options are specified with the -D flag.  A list of options allowed:

    DEBUG=(ON/OFF): compile with debugging symbols
    PROFILE=(ON/OFF): compile with profiling symbols
    ARMA_EXTRA_DEBUG=(ON/OFF): compile with extra Armadillo debugging symbols
    BOOST_ROOT=(/path/to/boost/): path to root of boost installation
    ARMADILLO_INCLUDE_DIR=(/path/to/armadillo/include/): path to Armadillo headers
    ARMADILLO_LIBRARY=(/path/to/armadillo/libarmadillo.so): Armadillo library

Other tools can also be used to configure CMake, but those are not documented
here.

Once CMake is configured, building the library is as simple as typing 'make'.
This will build all library components as well as 'mlpack_test'.

    $ make

You can specify individual components which you want to build, if you do not
want to build everything in the library:

    $ make mlpack_pca mlpack_knn mlpack_kfn

If the build fails and you cannot figure out why, register an account on Github
and submit an issue; the mlpack developers will quickly help you figure it out:

[mlpack on Github](https://www.github.com/mlpack/mlpack/)

Alternately, mlpack help can be found in IRC at `#mlpack` on irc.freenode.net.

If you wish to install mlpack to `/usr/local/include/mlpack/` and `/usr/local/lib/`
and `/usr/local/bin/`, once it has built, make sure you have root privileges (or
write permissions to those three directories), and simply type

    $ make install

You can now run the executables by name; you can link against mlpack with
    `-lmlpack`
and the mlpack headers are found in
    `/usr/local/include/mlpack/`.

If running the programs (i.e. `$ mlpack_knn -h`) gives an error of the form

    error while loading shared libraries: libmlpack.so.2: cannot open shared object file: No such file or directory

then be sure that the runtime linker is searching the directory where
`libmlpack.so` was installed (probably `/usr/local/lib/` unless you set it
manually).  One way to do this, on Linux, is to ensure that the
`LD_LIBRARY_PATH` environment variable has the directory that contains
`libmlpack.so`.  Using bash, this can be set easily:

    export LD_LIBRARY_PATH=/usr/local/lib/

(or whatever directory `libmlpack.so` is installed in.)

5. Running mlpack programs
--------------------------

After building mlpack, the executables will reside in `build/bin/`.  You can call
them from there, or you can install the library and (depending on system
settings) they should be added to your PATH and you can call them directly.  The
documentation below assumes the executables are in your PATH.

Consider the 'mlpack_knn' program, which finds the k nearest neighbors in a
reference dataset of all the points in a query set.  That is, we have a query
and a reference dataset. For each point in the query dataset, we wish to know
the k points in the reference dataset which are closest to the given query
point.

Alternately, if the query and reference datasets are the same, the problem can
be stated more simply: for each point in the dataset, we wish to know the k
nearest points to that point.

Each mlpack program has extensive help documentation which details what the
method does, what each of the parameters are, and how to use them:

    $ mlpack_knn --help

Running `mlpack_knn` on one dataset (that is, the query and reference
datasets are the same) and finding the 5 nearest neighbors is very simple:

    $ mlpack_knn -r dataset.csv -n neighbors_out.csv -d distances_out.csv -k 5 -v

The `-v (--verbose)` flag is optional; it gives informational output.  It is not
unique to `mlpack_knn` but is available in all mlpack programs.  Verbose
output also gives timing output at the end of the program, which can be very
useful.

6. Further documentation
------------------------

The documentation given here is only a fraction of the available documentation
for mlpack.  If doxygen is installed, you can type `make doc` to build the
documentation locally.  Alternately, up-to-date documentation is available for
older versions of mlpack:

  - [mlpack homepage](http://www.mlpack.org/)
  - [Tutorials](http://www.mlpack.org/tutorials.html)
  - [Development Site (Github)](https://www.github.com/mlpack/mlpack/)
  - [API documentation](http://www.mlpack.org/doxygen.php)

7. Bug reporting
----------------
   (see also [mlpack help](http://www.mlpack.org/help.html))

If you find a bug in mlpack or have any problems, numerous routes are available
for help.

Github is used for bug tracking, and can be found at
https://github.com/mlpack/mlpack/.
It is easy to register an account and file a bug there, and the mlpack
development team will try to quickly resolve your issue.

In addition, mailing lists are available.  The mlpack discussion list is
available at

  [mlpack discussion list](https://lists.cc.gatech.edu/mailman/listinfo/mlpack)

and the git commit list is available at

  [commit list](https://lists.cc.gatech.edu/mailman/listinfo/mlpack-git)

Lastly, the IRC channel ```#mlpack``` on Freenode can be used to get help.


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Leafl. bot. observ. 2:263. 1912

#### Original name
null

### Remarks
null


text:
require 'rails_helper'

RSpec.describe V1::SocialKinds::FinderService, type: [:service, :social_kind], slow: true do
  subject {V1::SocialKinds::FinderService.new}
  let(:repository) { V1::SocialKind }
  let(:contact_repository) { V1::Contact }
  let(:social_kinds) {create(:social_kinds)}
  let(:social_kinds01) {create(:social_kinds, name: "ExampleName01")}
  let(:result_social_kinds){subject.only(repository, social_kinds.id)}
  let(:result_social_kinds01){subject.only(repository, social_kinds01.id)}
  let(:contacts) {create(:contacts, social_kind_id: social_kinds01.id)}
  let(:social_kinds_from_contact){subject.from_contact(repository, contacts.id)}

  describe "Initialize" do

    before do
      social_kinds
      social_kinds01
      result_social_kinds
      result_social_kinds01
    end

    context "When use two records to return it" do
      it 'returns all records' do
        expect(subject.all(repository)).to eq [social_kinds, social_kinds01]
      end
    end

    context "When created two records and using it" do
      it 'find a record social_kinds comparing the result' do
        expect(result_social_kinds).to eq social_kinds
      end
      it 'find a record social_kinds_01 and compare the name field value' do
        expect(result_social_kinds01.name).to eq 'ExampleName01'
      end
    end
    context "When created a contact records and using it" do
      it 'find a record social_kinds01 from contact comparing the result' do
        expect(social_kinds_from_contact).to eq social_kinds01
      end
      it 'find a record social_kinds_01 from contact and compare the name field value' do
        expect(social_kinds_from_contact.name).to eq 'ExampleName01'
      end
    end
  end
end


text:
cd /tmp

# libopus
wget -O opus.tar.gz http://downloads.xiph.org/releases/opus/opus-${OPUS_VERSION}.tar.gz

mkdir opus
tar -xzvf opus.tar.gz -C ./opus --strip-components=1

cd opus
./configure
make all && make install

# asterisk
cd /tmp
wget -O asterisk.tar.gz http://downloads.asterisk.org/pub/telephony/asterisk/releases/asterisk-${ASTERISK_VERSION}.tar.gz

mkdir asterisk
tar -xzvf asterisk.tar.gz -C ./asterisk --strip-components=1

cd ./asterisk
./bootstrap.sh

sh contrib/scripts/get_mp3_source.sh
sh contrib/scripts/install_prereq install

./configure --with-crypto --with-ssl --with-srtp=/usr/include/srtp/ --libdir=/usr/lib/x86_64-linux-gnu

# menuselect
make menuselect.makeopts
/bin/sh /menuselect.sh

make && make install && make samples

# add g729
wget http://asterisk.hosting.lv/bin/codec_g729-ast140-gcc4-glibc-x86_64-pentium4.so -O codec_g729.so
mv codec_g729.so /usr/lib/x86_64-linux-gnu/asterisk/modules/

# logs
touch /var/log/auth.log /var/log/asterisk/messages /var/log/asterisk/security /var/log/asterisk/cdr-csv


text:
$marketplace = Balanced\Marketplace::mine();
$settlements = $marketplace->settlements->query()->all();


text:
AddCSLuaFile()

if SERVER then
	API_YT_SEARCH_URL = "https://www.googleapis.com/youtube/v3/search?key=%s&part=id&type=video&q=%s"
	API_YT_KEY = file.Read("translation_key.txt")

	local function RequestYTSearch( q, c )
		local url = string.format( API_YT_SEARCH_URL, API_YT_KEY, q )
		url = string.Replace( url, " ", "%20" ) // Encoding Url

		http.Fetch(url,
			function( res )
				local tab = util.JSONToTable(res)

				if tab then
					local vid = tab.items[1].id.videoId

					if vid then
						c( vid )
					end
				end

				c( false )
			end,
			function( err )
				c( false )
			end
		)
	end

	util.AddNetworkString( "s2c_mpyt" )

	local urls = {
		"youtu%.be/([%w_%-]+)",
		"youtube%.com/watch%?v%=([%w_%-]+)"
	}

	local function getYoutubeID( url )
		for _, v in pairs( urls ) do
			for m in string.gmatch( url, v ) do
				return m
			end
		end

		return false
	end

	aowl.AddCommand("ytplay", function(ply, line, q)
		local id = getYoutubeID( q )

		if id then
			net.Start( "s2c_mpyt" )
			net.WriteString( id )
			net.Send( ply )
		else
			RequestYTSearch( q, function( data )
				if data then
					net.Start( "s2c_mpyt" )
					net.WriteString( data )
					net.Send( ply )
				end
			end )
		end
	end)
end

if CLIENT then
	net.Receive("s2c_mpyt", function()
		local data = net.ReadString()
		local ent = LocalPlayer():GetEyeTrace().Entity

		if ent.IsMediaPlayerEntity then
			local q = string.format( "https://www.youtube.com/watch?v=%s", data )
			MediaPlayer.Request( ent, q )
		end
	end)
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>P-Index</title>
<meta name="date" content="2014-11-12">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I J L M N O P R S T U V W

P

panel_1 - Variable in class Application.Application

The panel_1.

panel_10 - Variable in class Application.Application

The panel_10.

panel_4 - Variable in class Application.Application

The panel_4.

panel_7 - Variable in class Application.Application

The panel_7.

People - package People

people - Variable in class Application.ApplicationData

The people.

Person - Class in People

The Class Person.

Person(String) - Constructor for class People.Person

Constructor for Person, initializes all emotions and personality traits to default.

PersonalityTrait - Class in PersonalityTraits

The Class PersonalityTrait, containing variables and methods common to all personality traits.

PersonalityTrait(String, double) - Constructor for class PersonalityTraits.PersonalityTrait

Instantiates a new personality trait.

PersonalityTraits - package PersonalityTraits

personalityTraits - Variable in class People.Person

The personality traits: OpennessToExperience, Conscientiousness, Extraversion, Agreeableness, Neuroticism.

PersonalityType - Class in PersonalityTraits

A class defining a specific personality type.

PersonalityType(String, double, double, double, double, double) - Constructor for class PersonalityTraits.PersonalityType

Instantiates a new personality type.

PersonInfoLeft - Variable in class Application.Application

The Person info left.

PersonInfoRight - Variable in class Application.Application

The Person info right.

PersonLeft_A - Variable in class Application.Application

The Person left_ a.

PersonLeft_Anger - Variable in class Application.Application

The Person left_ anger.

PersonLeft_Antic - Variable in class Application.Application

The Person left_ antic.

PersonLeft_C - Variable in class Application.Application

The Person left_ c.

PersonLeft_Disgust - Variable in class Application.Application

The Person left_ disgust.

PersonLeft_E - Variable in class Application.Application

The Person left_ e.

PersonLeft_Fear - Variable in class Application.Application

The Person left_ fear.

PersonLeft_Joy - Variable in class Application.Application

The Person left_ joy.

PersonLeft_N - Variable in class Application.Application

The Person left_ n.

PersonLeft_O - Variable in class Application.Application

The Person left_ o.

PersonLeft_Sad - Variable in class Application.Application

The Person left_ sad.

PersonLeft_Surprise - Variable in class Application.Application

The Person left_ surprise.

PersonLeft_Trust - Variable in class Application.Application

The Person left_ trust.

PersonRight_A - Variable in class Application.Application

The Person right_ a.

PersonRight_Anger - Variable in class Application.Application

The Person right_ anger.

PersonRight_Antic - Variable in class Application.Application

The Person right_ antic.

PersonRight_C - Variable in class Application.Application

The Person right_ c.

PersonRight_Disgust - Variable in class Application.Application

The Person right_ disgust.

PersonRight_E - Variable in class Application.Application

The Person right_ e.

PersonRight_Fear - Variable in class Application.Application

The Person right_ fear.

PersonRight_Joy - Variable in class Application.Application

The Person right_ joy.

PersonRight_N - Variable in class Application.Application

The Person right_ n.

PersonRight_O - Variable in class Application.Application

The Person right_ o.

PersonRight_Sad - Variable in class Application.Application

The Person right_ sad.

PersonRight_Surprise - Variable in class Application.Application

The Person right_ surprise.

PersonRight_Trust - Variable in class Application.Application

The Person right_ trust.

previousTopicBox - Variable in class Application.Application

The place holder.

prevStatements - Variable in class Conversation.Conversation

The previous statements in the conversation.

prevTopics - Variable in class Conversation.Conversation

The previous topics in the conversation.

A B C D E F G H I J L M N O P R S T U V W

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace Suppliers.Business.DomainModel
{
    /// Represents a named collection of suppliers.
    public class SupplierGroup
    {
        private int id;
        /// Uniquely identifies the supplier group.
        public int Id
        {
            get { return id; }
            set
            {
                if (id != 0 && id != value) throw new InvalidOperationException("Supplier group id can't change after setting it");
                {
                    id = value;
                }
            }

        }

        /// A name of the group.
        public string Name { get; private set; }

        private IList<Supplier> suppliers;
        /// A collection of suppliers that belong to this group.
        public IList<Supplier> Suppliers { get { return suppliers; } }

        /// Creates a new instance of <see cref="SupplierGroup"/>.
        /// <exception cref="ArgumentException">Thrown when group name is not provided.</exception>
        public SupplierGroup(int id, string name)
        {
            if (string.IsNullOrEmpty(name)) throw new ArgumentException("Supplier group's name must be provided.");

            Id = id;
            Name = name;
            suppliers = new List<Supplier>();
        }

        /// Adds a new supplier to the collection.
        /// <param name="supplier">The supplier we are adding.</param>
        /// <returns>True, if supplier was successfully added to collection, otherwise false.</returns>
        public bool AddSupplier(Supplier supplier)
        {
            if (supplier != null && !suppliers.Any(s => s.EmailAddress.Address == supplier.EmailAddress.Address))
            {
                suppliers.Add(supplier);
                if (supplier.Group != null && supplier.Group != this)
                {
                    supplier.UpdateGroup(this);
                }

                return true;
            }
            return false;
        }
    }
}


text:
package org.kuali.coeus.propdev.api.person;

import org.kuali.coeus.propdev.api.person.creditsplit.ProposalUnitCreditSplitContract;

import java.util.List;

public interface ProposalPersonUnitContract extends ProposalPersonLink {

    String getUnitNumber();

    boolean isLeadUnit();

    List<? extends ProposalUnitCreditSplitContract> getCreditSplits();
}


text:
import Enzyme, { shallow } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'

import withData from '../withData'

Enzyme.configure({ adapter: new Adapter() })

describe('withData', () => {
  let wrapper
  let HOC
  let Component

  beforeAll(() => {
    Component = () => {
      return (

withData

      )
    }

    HOC = withData(Component)
    wrapper = shallow(<HOC />)
  })

  test('Should has initialState', () => {
    const instance = wrapper.instance()
    expect(typeof instance.props.initialState === 'object').toBeTruthy()
  })

  describe('When Component has not getInitialProps', () => {
    test('Should be return object', (done) => {
      const resultPromise = HOC.getInitialProps({})
      resultPromise.then(data => {
        expect(typeof data === 'object').toBeTruthy()
        done()
      })
    })
  })

  describe('When Component has getInitialProps', () => {
    test('Should be called getInitialProps', () => {
      Component.getInitialProps = jest.fn()
      HOC.getInitialProps({})
      expect(Component.getInitialProps).toHaveBeenCalled()
    })
  })
})


text:
namespace Nested_loops
{
    using System;
    public class StartUp
    {
        private static int[] loops;

        static void Main(string[] args)
        {
            int count = int.Parse(Console.ReadLine());

            loops = new int[count];

            NestedLoops(0, count);
        }

        private static void NestedLoops(int current, int count)
        {
            if (current == count)
            {
                Print(loops);
                return;
            }

            for (int i = 1; i <= count; i++)
            {
                loops[current] = i;
                NestedLoops(count, current + 1);
            }
        }

        private static void Print(int[] loops)
        {
            Console.WriteLine(string.Join(" ", loops));
        }
    }
}


text:
const x = "literal";
/**
 * An object literal.
 */
const objectLiteral = {
    valueZ: "foo",
    valueY: function () {
        return "foo";
    },
    valueX: {
        valueZ: "foo",
        valueY: (z: string) => {
            return { a: "test", b: z };
        },
        valueA: [100, 200, 300],
    },
    valueA: 100,
    valueB: true,
    [Symbol.toStringTag]: "computed",
    [x]: true,
    ["literal2"]: true,
};

/**
 * A typed literal without an initializer.
 */
export let typeLiteral: {
    valueZ: string;
    valueY: { (): string };
    valueX: {
        valueZ: string;
        valueY: { (z: string): { a: string; b: string } };
        valueA: number[];
    };
    valueA?: number;
    valueB?: boolean;
};

let onSuccess: any = function () {};
let onError: any = function () {};
let onFinally: any = function () {};

export const callbackReturn = {
    success: (successCallback: () => any) => {
        onSuccess = successCallback;
        return callbackReturn;
    },
    error: (errorCallback: () => any) => {
        onError = errorCallback;
        return callbackReturn;
    },
    finally: (finallyCallback: () => any) => {
        onFinally = finallyCallback;
        return callbackReturn;
    },
};

export { objectLiteral };


text:
<?php

namespace Drupal\Core\Routing;

use Symfony\Component\Routing\RouteCompilerInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCompiler as SymfonyRouteCompiler;

/**
 * Compiler to generate derived information from a Route necessary for matching.
 */
class RouteCompiler extends SymfonyRouteCompiler implements RouteCompilerInterface {

  /**
   * Utility constant to use for regular expressions against the path.
   */
  const REGEX_DELIMITER = '#';

  /**
   * Compiles the current route instance.
   *
   * Because so much of the parent class is private, we need to call the parent
   * class's compile() method and then dissect its return value to build our
   * new compiled object.  If upstream gets refactored so we can subclass more
   * easily then this may not be necessary.
   *
   * @param \Symfony\Component\Routing\Route $route
   *   A Route instance.
   *
   * @return \Drupal\Core\Routing\CompiledRoute
   *   A CompiledRoute instance.
   */
  public static function compile(Route $route) {

    $symfony_compiled = parent::compile($route);

    // The Drupal-specific compiled information.
    $stripped_path = static::getPathWithoutDefaults($route);
    $fit = static::getFit($stripped_path);
    $pattern_outline = static::getPatternOutline($stripped_path);
    // We count the number of parts including any optional trailing parts. This
    // allows the RouteProvider to filter candidate routes more efficiently.
    $num_parts = count(explode('/', trim($route->getPath(), '/')));

    return new CompiledRoute(
      $fit,
      $pattern_outline,
      $num_parts,

      // The following parameters are what Symfony uses in
      // \Symfony\Component\Routing\Matcher\UrlMatcher::matchCollection().

      // Set the static prefix to an empty string since it is redundant to
      // the matching in \Drupal\Core\Routing\RouteProvider::getRoutesByPath()
      // and by skipping it we more easily make the routing case-insensitive.
      '',
      $symfony_compiled->getRegex(),
      $symfony_compiled->getTokens(),
      $symfony_compiled->getPathVariables(),
      $symfony_compiled->getHostRegex(),
      $symfony_compiled->getHostTokens(),
      $symfony_compiled->getHostVariables(),
      $symfony_compiled->getVariables()
    );
  }

  /**
   * Returns the pattern outline.
   *
   * The pattern outline is the path pattern but normalized so that all
   * placeholders are the string '%'.
   *
   * @param string $path
   *   The path for which we want the normalized outline.
   *
   * @return string
   *   The path pattern outline.
   */
  public static function getPatternOutline($path) {
    return preg_replace('#\{\w+\}#', '%', $path);
  }

  /**
   * Determines the fitness of the provided path.
   *
   * @param string $path
   *   The path whose fitness we want.
   *
   * @return int
   *   The fitness of the path, as an integer.
   */
  public static function getFit($path) {
    $parts = explode('/', trim($path, '/'));
    $number_parts = count($parts);
    // We store the highest index of parts here to save some work in the fit
    // calculation loop.
    $slashes = $number_parts - 1;
    // The fit value is a binary number which has 1 at every fixed path
    // position and 0 where there is a wildcard. We keep track of all such
    // patterns that exist so that we can minimize the number of path
    // patterns we need to check in the RouteProvider.
    $fit = 0;
    foreach ($parts as $k => $part) {
      if (strpos($part, '{') === FALSE) {
        $fit |= 1 << ($slashes - $k);
      }
    }

    return $fit;
  }

  /**
   * Returns the path of the route, without placeholders with a default value.
   *
   * When computing the path outline and fit, we want to skip default-value
   * placeholders.  If we didn't, the path would never match.  Note that this
   * only works for placeholders at the end of the path. Infix placeholders
   * with default values don't make sense anyway, so that should not be a
   * problem.
   *
   * @param \Symfony\Component\Routing\Route $route
   *   The route to have the placeholders removed from.
   *
   * @return string
   *   The path string, stripped of placeholders that have default values.
   */
  public static function getPathWithoutDefaults(Route $route) {
    $path = $route->getPath();
    $defaults = $route->getDefaults();

    // Remove placeholders with default values from the outline, so that they
    // will still match.
    $remove = array_map(function($a) {
      return '/{' . $a . '}';
    }, array_keys($defaults));
    $path = str_replace($remove, '', $path);

    return $path;
  }

}


text:
OauthService::Engine.routes.draw do
  get 'callback/:provider_name',  to: 'base#callback'
  get 'logout',  to: 'base#logout'
  get 'login', to: 'base#login'
  get 'info', to: 'base#info'
  get 'token', to: 'base#token'

  root to: 'base#login'
end


text:
package rapture.orm
import scala.collection.mutable.HashMap

object LruCache {
  trait Cacheable[A] {
    def cacheKey: A
    def onEvict(): Unit
  }
}

/** Implements a fixed-size cache that discards the least recently used entry.
 * Multiple values may exist for the same key, in which case any one might be
 * returned. Note that this class is not threadsafe. */
class LruCache[Key, Value >: Null <% LruCache.Cacheable[Key]](capacity: Int) {
  private class Entry(var prev: Int, var next: Int) {
    var value: Value = null
    var parent = -1
    var child = -1
  }

  private val arr = new Array[Entry](capacity)
  private val hash = new HashMap[Key, Int]
  private var count = 0
  private var free = 0
  private var first = -1
  private var last = -1

  for(i <- 0 until capacity) arr(i) = new Entry(i - 1, i + 1)
  arr(capacity - 1).next = -1

  /** Returns a matching value if it is present in the cache. */
  def peek(k: Key): Option[Value] =
    hash.get(k) match {
      case Some(i) => Some(arr(i).value)
      case None => None
    }

  /** Removes and returns a matching value if it is present. */
  def take(k: Key): Option[Value] =
    hash.get(k) match {
      case Some(i) =>
        val v = arr(i).value
        remove(i, true)
        Some(v)
      case None =>
        None
    }

  /** Adds a new value, removing the LRU if necessary. */
  def put(v: Value): Unit = {
    if(count == capacity) {
      arr(last).value.onEvict()
      remove(last, false)
    }

    val k = v.cacheKey
    val i = free
    val e = arr(i)
    if(first == -1) last = i
    else arr(first).prev = i
    free = e.next
    e.next = first
    first = i
    if(free != -1) arr(free).prev = -1
    e.prev = -1
    count += 1
    e.value = v
    hash.get(k) match {
      case Some(j) =>
        e.child = j
        arr(j).parent = i
      case None => ()
    }
    hash(k) = i
  }

  /** Evicts all values matching the given key. */
  def evict(k: Key): Unit =
    hash.get(k) match {
      case Some(i) =>
        arr(i).value.onEvict()
        remove(i, false)
        evict(k)
      case None => ()
    }

  /** Has the cache reached capacity yet? */
  def isFull = (count == capacity)

  private def remove(i: Int, isHead: Boolean): Unit = {
    val e = arr(i)
    if(e.prev == -1) first = e.next
    else arr(e.prev).next = e.next
    if(e.next == -1) last = e.prev
    else arr(e.next).prev = e.prev
    e.next = free
    e.prev = -1
    free = i
    val k = e.value.cacheKey
    if(isHead || hash(k) == i) {
      if(e.child == -1) hash -= k
      else hash(k) = e.child
    }
    if(e.parent != -1) arr(e.parent).child = e.child
    if(e.child != -1) arr(e.child).parent = e.parent
    count -= 1
    e.parent = -1
    e.child = -1
    e.value = null
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>UGA Women</title>

    <meta name="viewport" content="initial-scale=1, maximum-scale=1">

    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">

    <link href="css/ratchet.min.css" rel="stylesheet">

*App Name*

    New
    For you

    Home

    Peek

    Me

    More

Hey hi hello is this working?

              Ratchet documentation

              Ratchet on Github

              Ratchet Google group

              Ratchet on Twitter


text:
<bill session="115" type="h" number="1338" updated="2017-09-21T15:45:13Z">
  <state datetime="2017-03-02">REFERRED</state>
  <status>
    <introduced datetime="2017-03-02"/>
  </status>
  <introduced datetime="2017-03-02"/>
  <titles>
    <title type="short" as="introduced">Horse Protection Amendments Act</title>
    <title type="short" as="introduced">Horse Protection Amendments Act</title>
    <title type="official" as="introduced">To amend the Horse Protection Act to provide increased protection for horses participating in shows, exhibitions, or sales, and for other purposes.</title>
    <title type="display">Horse Protection Amendments Act</title>
  </titles>
  <sponsor bioguide_id="D000616"/>
  <cosponsors>
    <cosponsor bioguide_id="B001282" joined="2017-03-02"/>
    <cosponsor bioguide_id="B001273" joined="2017-03-02"/>
    <cosponsor bioguide_id="B001243" joined="2017-03-02"/>
    <cosponsor bioguide_id="C001108" joined="2017-03-02"/>
    <cosponsor bioguide_id="D000533" joined="2017-03-02"/>
    <cosponsor bioguide_id="F000459" joined="2017-03-02"/>
    <cosponsor bioguide_id="G000558" joined="2017-03-02"/>
    <cosponsor bioguide_id="P000601" joined="2017-03-17"/>
    <cosponsor bioguide_id="R000582" joined="2017-03-02"/>
    <cosponsor bioguide_id="R000395" joined="2017-03-02"/>
  </cosponsors>
  <actions>
    <action datetime="2017-03-02">
      <text>Introduced in House</text>
    </action>
    <action datetime="2017-03-02" state="REFERRED">
      <text>Referred to the House Committee on Energy and Commerce.</text>
    </action>
    <action datetime="2017-03-17">
      <text>Referred to the Subcommittee on Digital Commerce and Consumer Protection.</text>
    </action>
  </actions>
  <committees>
    <committee subcommittee="" code="HSIF" name="House Energy and Commerce" activity="Referral"/>
    <committee subcommittee="Commerce, Manufacturing, and Trade" code="HSIF17" name="House Energy and Commerce" activity="Referral"/>
  </committees>
  <relatedbills/>
  <subjects>
    <term name="Animals"/>
    <term name="Administrative law and regulatory procedures"/>
    <term name="Animal protection and human-animal relationships"/>
    <term name="Department of Agriculture"/>
    <term name="Mammals"/>
    <term name="Medical tests and diagnostic methods"/>
    <term name="Museums, exhibitions, cultural centers"/>
    <term name="Public-private cooperation"/>
    <term name="Veterinary medicine and animal diseases"/>
  </subjects>
  <amendments/>
  <summary date="2017-03-02T05:00:00Z" status="Introduced in House">Horse Protection Amendments Act

This bill amends the Horse Protection Act to replace the Designated Qualified Persons program responsible for inspecting horses for soring with a new inspection system. (The soring of horses is any of various actions taken on a horse's limb to produce a higher gait that may cause pain, distress, inflammation, or lameness.)

The Department of Agriculture must establish a single Horse Industry Organization (HIO) in order to establish a formal affiliation with the management of each horse sale, horse exhibition, and horse sale or auction, appoint inspectors to conduct inspections, and otherwise ensure compliance with the Horse Protection Act.

The Commissioners of Agriculture for Tennessee and Kentucky must appoint individuals to the HIO. Those individuals must appoint individuals representing the Tennessee Walking Horse industry.</summary>
  <committee-reports/>
</bill>