text:
    In the 'Custom conversion format' field, enter json that describes how to convert tests from raw format to the format of your testing framework.
    After conversion, the result is injected to the "testsToRunConverted" parameter.

    Note: Click "Validate" to check the correctness of the inserted configuration.

    The following are the components that you can use in the "Custom conversion format" :

testPattern - describes the pattern for converting single test. It uses reserved words ($package,$class,$testName) that will be
    replaced by real test data. All other characters in the pattern will appear in the final result as is.

testDelimiter - the delimiter used to separate different tests.

prefix  - a prefix for the whole conversion result.

suffix  - a suffix for the whole conversion result.

testsToRunConvertedParameter  - the parameter name that will contain the conversion result. Default value is "testsToRunConverted".

replacements  - the array of replace methods.

    The minimal configuration is:

{
    "testPattern": "$package.$class#$testName",
    "testDelimiter": ","
}

For example:

    The testsToRun parameter received 2 tests separated by a semicolon: v1:myPackage1|myClass1|myTest1;myPackage2|myClass2|myTest2

    The defined testPattern is: $package.$class#$testName

    The defined testDelimiter is:  ,

$package variable will get a value of myPackage1 for the first test and myPackage2 for the second test.

$class variable will get a value of myClass1 for the first test and myClass2 for the second test.

$testName variable will get a value of myTest1 for the first test and myTest2 for the second test.

The testsToRunConverted parameter will be equal: myPackage1.myClass1#myTest1,myPackage2.myClass2#myTest2

    Optional:

    There is a possibility to alter values received from ALM Octane, for example to set lowercase to the testName, replace spaces by '_', and so on.

    Here are examples of available replace methods. Each replace method contains "target" property that define what parts of the test pattern are affected by replace method,
    available values are $package,$class,$testName. Its possible to put several values separated by '|'. The replacements are executed in the order they appear in the 'Custom conversion format' json.

"replacements": [
{
    "type": "replaceRegex",
    "target": "$package|$class|$testName",
    "regex": "aaa",
    "replacement": "bbb",
    "description": "Replaces all the sequence of characters matching the regex with a replacement string."
},{
    "type": "replaceRegexFirst",
    "target": "$package|$class|$testName",
    "regex": "aaa",
    "replacement": "bbb",
    "description": "Replaces the first substring that matches the given regex with the given replacement."
},{
    "type": "replaceString",
    "target": "$package|$class|$testName",
    "string": "xxx",
    "replacement": "yyy",
    "description": "Replaces all occurrences of 'string' with 'replacement'."
},{
    "type": "joinString",
    "target": "$package|$class|$testName",
    "prefix": "xxx",
    "suffix": "yyy",
    "description": "Add prefix and suffix to the test template."
},{
    "type": "toLowerCase",
    "target": "$package|$class|$testName",
    "description": "Convert test template to lower case."
},{
    "type": "toUpperCase",
    "target": "$package|$class|$testName",
    "description": "Convert test template to upper  case."
},{
    "type": "notLatinAndDigitToOctal",
    "target": "$package|$class|$testName",
    "description": "Replaces all non-latin characters and digits ^[a-zA-Z0-9] to their ASCII octal value."
}]


text:
Hooks that allow you to build a search interface using any component library.

Visit the [docs site](https://react.docs.sajari.com) to learn more.

redpajama_set_name: RedPajamaGithub


text:
Angular Form Wizard

                                <md-button ng-click="stepToggle()" class="md-raised btn-w-md md-accent">Clicking Me Will Toggle Steps On and Off Dynamically</md-button>

                                <wizard on-finish="finished()">
                                    <wz-step wz-title="Start" canexit="exitWithAPromise">

Start

Hey guys, welcome to the wizard :)

Here we will use a promise with a timeout to simulate an async server call. Give the wizard 1 second to progress after clicking next!

Otherwise, let's continue with the wizard. Please click here to continue

                                            <md-button type="submit" wz-next class="md-raised btn-w-md md-primary">Next</md-button>

                                    </wz-step>
                                    <wz-step wz-title="Liking it" canexit="exitValidation">

Liking it

You're now in the second step of this wizard.

This step is an example of using canexit validation with no server call,

Toggle the value to true or false using the button below to see an example of being allowed to exit and being restricted.

                                            <md-button ng-click="exitToggle()" class="md-raised btn-w-md md-accent">Toggle Validation!</md-button>

Value is currently: {{canExit}}

                                            <md-button wz-previous="logStep()"  class="md-raised btn-w-md">BACK</md-button>
                                            <md-button wz-next="logStep()" class="md-raised btn-w-md md-primary" ng-disabled="!canExit">NEXT</md-button>

                                    </wz-step>
                                    <wz-step wz-title="More steps" wz-disabled="{{!stepActive}}">

More steps

Click on the bottom navigation on Liking it to go back to that step for example

                                            <md-button wz-previous="logStep()"  class="md-raised btn-w-md">BACK</md-button>
                                            <md-button wz-next="logStep()" class="md-raised btn-w-md md-primary" ng-disabled="!canExit">NEXT</md-button>

                                    </wz-step>
                                    <wz-step wz-title="Even more">

Even More steps

I can't deal with so many steps. ARGH

                                            <md-button wz-previous="logStep()"  class="md-raised btn-w-md">BACK</md-button>
                                            <md-button wz-next="logStep()" class="md-raised btn-w-md md-primary">NEXT</md-button>

                                    </wz-step>
                                    <wz-step wz-title="Sup?">

Sup?

I don't even know what to write!

                                            <md-button wz-previous="logStep()"  class="md-raised btn-w-md">BACK</md-button>
                                            <md-button wz-next="logStep()" class="md-raised btn-w-md md-primary" >NEXT</md-button>

                                    </wz-step>
                                    <wz-step wz-title="Finish him">

Finish him

Finally this ends!

                                            <md-button ng-click="goBack()" class="md-raised btn-w-md md-accent">Restart</md-button>
                                            <md-button wz-reset class="md-raised btn-w-md md-accent">Reset</md-button>
                                            <md-button wz-previous="logStep()"  class="md-raised btn-w-md">BACK</md-button>
                                            <md-button wz-next="logStep()" class="md-raised btn-w-md md-primary">Finish</md-button>

                                    </wz-step>
                                </wizard>

Simple Form Wizard

First Step

First Content

Second Step

Second Content

Third Step

Third Content

Vertical Form Wizard

First Step

First Content

Second Step

Second Content

Third Step

Third Content


text:
<?php session_start(); ?>
<?php
include "config.php";
?>
<!DOCTYPE html>

        <title>The adminpanel</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="assets/css/bootstrap.min.css" />
        <link rel="stylesheet" href="assets/css/style.css" />

              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                Toggle navigation

              </button>
              The Secretstore

Login

Register

Logout

                <?php
                    $logged_in = $_SESSION['loggedin'];

                    if($logged_in) {
                        echo '
Error
';
                        echo '

You are already registered. No need to register again.
';
                    } else {

                        if(isset($_POST['user']) && isset($_POST['password']) && isset($_POST['secret'])) {
                            $user = $_POST['user'];
                            $password = md5($_POST['password']);
                            $comment = $_POST['secret'];

                            $q = mysqli_prepare($DBCON, "SELECT id FROM usertable where username = ? limit 1");
                            mysqli_stmt_bind_param($q, "s", $user);
                            mysqli_stmt_execute($q);
                            $res = mysqli_stmt_get_result($q);
                            if ($res->num_rows > 0) {
                                echo '
Error
';
                                echo '

User already exists!
';
                            } else {
                                $zero = 0;
                                $q = mysqli_prepare($DBCON, "INSERT INTO usertable (username, pw, comment, is_admin) VALUES (?,?,?,?)");
                                mysqli_stmt_bind_param($q, "sssi", $user, $password, $comment, $zero);
                                $a = mysqli_stmt_execute($q);
                                if($a) {
                                    echo '
YAY!
';
                                    echo '
Kittens love you - You are now registered
';
                                } else {
                                    echo '
Error:
';
                                    echo '
Something went wrong
';
                                }
                            }
                        }
                ?>

                    <form action="" method="POST" class="form-signin">

Create an account

                        Username
                        <input type="text" name="user" id="user" class="form-control" placeholder="Username" required="" autofocus="">
                        Password
                        <input type="password" id="password" name="password" class="form-control" placeholder="Password" required="">
                        Secret
                        <input type="text" name="secret" id="secret" class="form-control" placeholder="Secret" required="" autofocus="">
                        <button class="btn btn-lg btn-primary btn-block" type="submit">Register</button>
                    </form>

                <?php
                    }
                ?>


text:
title:  Lákavá reklama
date:   02/01/2018
---

**16Neboť všechno, co je ve světě, po čem dychtí člověk a co chtějí jeho oči a na čem si v životě zakládá, není z Otce, ale ze světa. 17A svět pomíjí i jeho chtivost; kdo však činí vůli Boží, zůstává na věky. (1J 2,16.17)**

**Chci říci: Žijte z moci Božího Ducha, a nepodlehnete tomu, k čemu vás táhne vaše přirozenost. (Ga 5,16)**

_Osobní studium_

Jaké různé nástrahy mohou spadat do kategorie toho, "po čem dychtí člověk a co chtějí jeho oči"? Na co si jako křesťané máme dávat pozor? Jakým způsobem nás ovlivňuje to, čemu věnujeme pozornost? Jak si představuješ život z moci Božího Ducha?

Svět reklamy je mocný. Firmy utrácejí miliardy, aby nám představily své produkty. Téměř vždy je propagují krásní a atraktivní lidé. Když se na takovou reklamu podíváme, vidíme v ní sami sebe. V naší představě přitom nevlastníme pouze daný produkt, ale sami se jakoby "stáváme" lidmi z reklamy.

Lákavost materializmu by nebyla ani zdaleka tak účinná, kdyby do téměř všech reklam nebyla jemně zapracována smyslnost. Sexuální podtext je jednou z nejmocnějších technik reklamy a na většinu křesťanů působí jako jed.

Reklama spojená se smyslností je velmi účinná. Dojem, který vyvolá, je čirou fantazií, ale funguje. Může poskytnout téměř mystický zážitek, když diváka, byť jen na chvilku, přenese do jiné reality. Může se stát jakýmsi falešným náboženstvím, které nenabízí žádné poznání a žádnou duchovní pravdu, ale v daném okamžiku je tak atraktivní a lákavé, že mu hodně lidí neodolá. Chceme to a víme, že si to zasloužíme. Tak proč si to nevzít? Jen Bůh sám ví, kolik peněz jsme již utratili a kolik ještě utratíme za věci, o jejichž potřebnosti nás přesvědčili tvůrci reklam.

_Aplikace_

`Jak ti může připomínání Božích darů ve tvém životě pomoci v tom, aby ses nenechal zmanipulovat reklamou? Zamysli se, jaké reklamní triky na tebe nejvíce zabírají. Když vidíš v obchodě výhodnou akci, zamyslíš se před tím, než si věc koupíš, zda ji opravdu potřebuješ?`


text:
module Blackjack
  module Brain
    class CountBasedBettingStrategy

      def calculate_bet(data)
        true_count = data[:true_count]
        if true_count <= 2
          10
        elsif true_count <= 10
          50
        elsif true_count <= 20
          75
        else
          100
        end
      end

    end
  end
end


text:
<!DOCTYPE html>

            <title>jQuery Practice Page</title>
            <link rel='stylesheet' href='style1.css'/>

My First jQuery

Meet the DEV Clubbers

Current list of computer-box heroes:

Luke

Morgan

Nick

Chad

Darcy

Zach

Josh

Overview

Does javascript magic

Bakes great cookies

Has been voted most likely to change the world in some meaningful way someday

Overview

Is currently two people

Is one of the smartest people you know

Needs to convince Luke to host a D&D session

Overview

Has a fantastic birth date

Rocks his BCGs

Seemingly reads coding books for fun

Overview

Has lovely locks

Has or is a doppelganger

Is a Git ninja

Overview

Is the only one of us actually emplyed as a programmer

Is setting up what will almost certainly be an awesome birthday trip in Savannah

May very well be radioactive

Overview

Sucks at javascript

Is trying to get better at javascript

Still really sucks at javascript

Overview

Freshly pressed and best dressed

Is absolutely crushing Ironyard

Is Zach's knight in html armor

*apologies to anyone I might have missed. This is purely a training exercise


text:
var debug = require('debug')('FeedImporter'),
    async = require('async'),
    FeedParser = require('./feed-parser');

function FeedImporter(db) {
  if (!(this instanceof FeedImporter)) {
    return new FeedImporter(db);
  }

  debug('ctor');

  this.db = db;
}

FeedImporter.prototype = {
  run: function(callback) {
    debug('run');

    async.waterfall(
      [
        this.findAllFeeds.bind(this),
        this.iterateFeeds.bind(this)
      ],
      callback
    );
  },

  findAllFeeds: function(callback) {
    var Feed = this.db.models.feed;

    debug('findAllFeeds');

    Feed.all(callback);
  },

  iterateFeeds: function(feeds, callback) {
    debug('iterateFeeds');

    async.map(
      feeds,
      this.handleEachFeed.bind(this),
      callback
    );
  },

  handleEachFeed: function(feed, callback) {
    debug('handleEachFeed', feed.id, feed.url);

    feed.articles = [];

    async.waterfall(
      [
        this.parseFeed.bind(this, feed),
        this.handleParsedFeed.bind(this, feed),
        this.updateFeed.bind(this, feed)
      ],
      function(err) {
        if (!err) {
          callback(null, feed.articles.length);
        } else {
          callback(err);
        }
      }
    );
  },

  parseFeed: function(feed, callback) {
    debug('parseFeed', feed.id, feed.url);

    FeedParser(feed.url).parse(callback);
  },

  handleParsedFeed: function(feed, items, callback) {
    debug('handleParsedFeed', feed.id, feed.url);

    async.each(
      items,
      this.mapFeedItem.bind(this, feed),
      callback
    );
  },

  updateFeed: function(feed, callback) {
    debug('updateFeed', feed.id, feed.url);

    feed.save(callback);
  },

  mapFeedItem: function(feed, item, callback) {
    debug('mapFeedItem', feed.id, item.title);

    feed.title = item.meta && item.meta.title;

    async.waterfall(
      [
        this.matchToArticle.bind(this, feed, item),
        this.mapArticle.bind(this, feed, item)
      ],
      callback
    );
  },

  matchToArticle: function(feed, item, callback) {
    debug('matchToArticle', feed.id, item.title);

    var Article = this.db.models.article;

    Article.exists({
      link: item.link
    }, callback);
  },

  mapArticle: function(feed, item, exists, callback) {
    debug('mapArticle', feed.id, exists, item.title);

    if (!exists) {
      var article = {};

      article.link = item.link;
      article.title = item.title;
      article.author = item.author;
      article.summary = item.summary;
      article.description = item.description;
      article.published_at = new Date(item.pubDate);
      article.updated_at = new Date(item.date);
      article.image = item.image && item.image.url;

      feed.articles.push(article);
    }

    callback(null);
  }
};

module.exports = FeedImporter;


text:
<?php declare(strict_types=1);

namespace PHPUnit\Framework\Constraint;

use function is_array;
use function sprintf;

/**
 * @no-named-arguments Parameter names are not covered by the backward compatibility promise for PHPUnit
 */
abstract class TraversableContains extends Constraint
{
    /**
     * @var mixed
     */
    private $value;

    public function __construct($value)
    {
        $this->value = $value;
    }

    /**
     * Returns a string representation of the constraint.
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    public function toString(): string
    {
        return 'contains ' . $this->exporter()->export($this->value);
    }

    /**
     * Returns the description of the failure.
     *
     * The beginning of failure messages is "Failed asserting that" in most
     * cases. This method should return the second part of that sentence.
     *
     * @param mixed $other evaluated value or object
     *
     * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
     */
    protected function failureDescription($other): string
    {
        return sprintf(
            '%s %s',
            is_array($other) ? 'an array' : 'a traversable',
            $this->toString()
        );
    }

    protected function value()
    {
        return $this->value;
    }
}


text:
package com.maxmouchet;

public class AEF2tt extends AEF {

    AEF2tt() {
        states = new State[]{
                new State(0, false),
                new State(1, false),
                new State(2, false),
                new State(3, false),
                new State(4, false),
                new State(5, true)
        };

        addTransition(states[0], states[1], 'a');
        addTransition(states[1], states[2], 'b');
        addTransitions(states[2], states[3], new Character[]{'a', 'b'});
        addSelfTransition(states[3], 'a');
        addTransition(states[3], states[4], 'b');
        addSelfTransition(states[4], 'b');
        addTransition(states[4], states[5], 'a');
        addTransition(states[5], states[4], 'b');
        addTransition(states[5], states[3], 'a');
    }

}


text:
<?php

defined('_JEXEC') or die;

JLoader::register('ContenthistoryHelper', JPATH_ADMINISTRATOR . '/components/com_contenthistory/helpers/contenthistory.php');

/**
 * Methods supporting a list of contenthistory records.
 *
 * @since  3.2
 */
class ContenthistoryModelCompare extends JModelItem
{
	/**
	 * Method to get a version history row.
	 *
	 * @return  array|boolean    On success, array of populated tables. False on failure.
	 *
	 * @since   3.2
	 */
	public function getItems()
	{
		$input = JFactory::getApplication()->input;

		/** @var JTableContenthistory $table1 */
		$table1 = JTable::getInstance('Contenthistory');

		/** @var JTableContenthistory $table2 */
		$table2 = JTable::getInstance('Contenthistory');

		$id1 = $input->getInt('id1');
		$id2 = $input->getInt('id2');
		$result = array();

		if ($table1->load($id1) && $table2->load($id2))
		{
			// Get the first history record's content type record so we can check ACL
			/** @var JTableContenttype $contentTypeTable */
			$contentTypeTable = JTable::getInstance('Contenttype');
			$ucmTypeId        = $table1->ucm_type_id;

			if (!$contentTypeTable->load($ucmTypeId))
			{
				// Assume a failure to load the content type means broken data, abort mission
				return false;
			}

			$user = JFactory::getUser();

			// Access check
			if ($user->authorise('core.edit', $contentTypeTable->type_alias . '.' . (int) $table1->ucm_item_id) || $this->canEdit($table1))
			{
				$return = true;
			}
			else
			{
				$this->setError(JText::_('JERROR_ALERTNOAUTHOR'));

				return false;
			}

			// All's well, process the records
			if ($return == true)
			{
				foreach (array($table1, $table2) as $table)
				{
					$object = new stdClass;
					$object->data = ContenthistoryHelper::prepareData($table);
					$object->version_note = $table->version_note;

					// Let's use custom calendars when present
					$object->save_date = JHtml::_('date', $table->save_date, 'Y-m-d H:i:s');

					$dateProperties = array (
						'modified_time',
						'created_time',
						'modified',
						'created',
						'checked_out_time',
						'publish_up',
						'publish_down',
					);

					foreach ($dateProperties as $dateProperty)
					{
						if (array_key_exists($dateProperty, $object->data) && $object->data->$dateProperty->value != '0000-00-00 00:00:00')
						{
							$object->data->$dateProperty->value = JHtml::_('date', $object->data->$dateProperty->value, 'Y-m-d H:i:s');
						}
					}

					$result[] = $object;
				}

				return $result;
			}
		}

		return false;
	}

	/**
	 * Method to test whether a record is editable
	 *
	 * @param   JTableContenthistory  $record  A JTable object.
	 *
	 * @return  boolean  True if allowed to edit the record. Defaults to the permission set in the component.
	 *
	 * @since   3.6
	 */
	protected function canEdit($record)
	{
		$result = false;

		if (!empty($record->ucm_type_id))
		{
			// Check that the type id matches the type alias
			$typeAlias = JFactory::getApplication()->input->get('type_alias');

			/** @var JTableContenttype $contentTypeTable */
			$contentTypeTable = JTable::getInstance('Contenttype', 'JTable');

			if ($contentTypeTable->getTypeId($typeAlias) == $record->ucm_type_id)
			{
				/**
				 * Make sure user has edit privileges for this content item. Note that we use edit permissions
				 * for the content item, not delete permissions for the content history row.
				 */
				$user   = JFactory::getUser();
				$result = $user->authorise('core.edit', $typeAlias . '.' . (int) $record->ucm_item_id);
			}

			// Finally try session (this catches edit.own case too)
			if (!$result)
			{
				$contentTypeTable->load($record->ucm_type_id);
				$typeEditables = (array) JFactory::getApplication()->getUserState(str_replace('.', '.edit.', $contentTypeTable->type_alias) . '.id');
				$result = in_array((int) $record->ucm_item_id, $typeEditables);
			}
		}

		return $result;
	}
}


text:
id: 439
title: Comment ajouter une information indexable sur un site ?
date: 2015-02-23T08:24:09+00:00
author: Ghislain
layout: post
guid: https://ghislainfo.wordpress.com/?p=439
permalink: /2015/02/23/from-indexed-property-to-refinement-panel/
geo_public:
  - 0
publicize_linkedin_url:
  - 'https://www.linkedin.com/updates?discuss=&scope=155989633&stype=M&topic=5975530005713686528&type=U&a=CngZ'
publicize_twitter_user:
  - GhislaInfo
publicize_twitter_url:
  - http://t.co/geeHEudbYW
categories:
  - PowerShell
  - SharePoint
tags:
  - crawled property
  - IndexedPropertyKeys
  - managed property
  - recherche
  - search
  - SharePoint 2013
---
Avez-vous déjà eu besoin d'ajouter de l'information sur vos sites ? Les property bags sont une solution. Et si vous voulez utiliser cette information dans la recherche ? Les propriétés indexées sont la solution.

[]({{ site.baseurl }}/wp-content/uploads/2015/02/indexedproperty1.png)

Une propriété indexée est un objet similaire à un couple (clé ; valeur) dans le property bag à la différence près qu'elle est indexée par le service de recherche. Après un crawl complet, elle apparait dans les crawled properties. Vous pouvez donc créer une propriété gérée liée à celle-ci. Après un second crawl complet, vous pouvez utiliser cette propriété dans la recherche, notamment dans le refinement panel.

Concrètement l'un de mes projets actuels consiste en la refonte en un seul service de plusieurs services hétérogènes. Je dis hétérogène autant d'un point de vue fonctionnel (social, publication, partage documentaire) que technique car il y a des plateformes Sharepoint 2007, 2010 et 2013. Après la partie migration et récupération de l'existant, je cherchais un moyen pour identifier le type de chaque site dans la recherche.

# Méthode

**1. Créer les propriétés indexées**

Au niveau de chaque site, créer une propriété indexée nommée GlaType.

Tools => http://dev.contoso.com et http://cth.contoso.com

Business => http://bi.contoso.com et http://performancepoint.contoso.com

Collab => http://team.contoso.com

# add an indexed property
$web = Get-SPWeb "http://team.contoso.com"
$web.AllProperties["GlaType"] = "Collab"
$web.IndexedPropertyKeys.Add("GlaType")
$web.Update()
# display all indexed properties
$web.IndexedPropertyKeys

**2. Lancer un crawl complet**

**3. Créer des propriétés gérées**

Vous remarquerez que la propriété indexée GlaType apparait bien dans la centrale d’administration.

[]({{ site.baseurl }}/wp-content/uploads/2015/01/indexedproperty.png)
Nouvelle propriété indexée disponible

Créer une propriété gérée ManagedGlaType liée à la propriété indexée GlaType. La configuration de la propriété gérée : Searchable, Queryable, Retrievable, Refinable, Sortable.

[]({{ site.baseurl }}/wp-content/uploads/2015/01/newmanagedproperty.png)
Nouvelle propriété gérée mappée à la propriété indexée

**4. Lancer un full crawl**

**5. Configurer le refinement panel de la recherche**

[]({{ site.baseurl }}/wp-content/uploads/2015/02/searchresults1.gif)

Vous avez maintenant la possibilité de trier les résultats à l’aide de la nouvelle propriété gérée ManagedGlaType.

Dans un prochain article, nous aborderons les modèles d’affichage pour exploiter cette propriété.


text:
<?xml version="1.0" encoding="UTF-8"?>
<screen xmlns="http://www.scons.org/dbxsd/v1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.scons.org/dbxsd/v1.0 http://www.scons.org/dbxsd/v1.0/scons.xsd">% <userinput>scons -Q</userinput>
sub1/multiple
sub2/multiple
sub3/multiple
scons: `.' is up to date.
</screen>


text:
module Main where

import qualified Easy          as E
import           Test.Hspec
import           Text.Trifecta

isString x (E.EasyString y) = x == y
isString _ _ = False

isArray x (E.EasyArray y) = x == y
isArray _ _ = False

correctParse (Success True) = True
correctParse _ = False

main :: IO ()
main = hspec $ do
  describe "Easy" $ do
    it "Test 1" $ correctParse (isArray [123] <$> E.parseTestData E.test1) `shouldBe` True
    it "Test 2" $ correctParse (isArray [44.234] <$> E.parseTestData E.test2) `shouldBe` True
    it "Test 3" $ correctParse (isString "0x123N" <$> E.parseTestData E.test3) `shouldBe` True
    it "Test 4" $ correctParse (isArray [3.23e5] <$> E.parseTestData E.test4) `shouldBe` True
    it "Test 5" $ correctParse (isArray [1293712938712938172938172391287319237192837329] <$> E.parseTestData E.test5) `shouldBe` True
    it "Test 6" $ correctParse (isArray [0.25] <$> E.parseTestData E.test6) `shouldBe` True
    it "Test 7" $ correctParse (isArray [123,234,345] <$> E.parseTestData E.test7) `shouldBe` True
    it "Test 8" $ correctParse (and . zipWith ($) [isArray [2015,4,4],isString "Challenge #",isArray [261],isString "Easy"] <$> E.mParseTestData E.test8) `shouldBe` True
    it "Test 9" $ correctParse (and . zipWith ($) [isArray [234.2],isString "234ggf 45",isArray [0.0],isString "number string number (0)"] <$> E.mParseTestData E.test9) `shouldBe` True


text:
CREATE TABLE IF NOT EXISTS db_version (
  id serial primary key not null,
  app varchar(255) not null,
  version varchar(255) not null,
  description varchar(255) not null,
  created timestamp with time zone not null
);

-- RESOURCES
CREATE TABLE IF NOT EXISTS resources (
  id varchar(255) not null,
  version integer not null,
  created_by varchar(255) not null,
  created_at timestamp with time zone not null,
  deleted boolean not null,
  latest boolean not null,
  name varchar(255) not null,
  type varchar(255) not null,
  asxml xml,
  asjson json,

  PRIMARY KEY (id, version)
);

-- ORDERS
CREATE TYPE order_state AS ENUM ('CREATED', 'PLANNING', 'PLANNED', 'EXECUTION', 'STOPPED', 'WARNING', 'ERROR', 'EXECUTED', 'CLOSED');

CREATE TABLE IF NOT EXISTS orders (
  id varchar(255) not null,
  version integer not null,
  created_by varchar(255) not null,
  created_at timestamp with time zone not null,
  deleted boolean,
  latest boolean not null,
  name varchar(255),
  type varchar(255),
  state order_state,
  date timestamp with time zone,
  asxml xml,
  asjson json,

  PRIMARY KEY (id, version)
);

-- ACTIVITIES
CREATE TABLE IF NOT EXISTS activities (
  id varchar(255) not null,
  version integer not null,
  created_by varchar(255) not null,
  created_at timestamp with time zone not null,
  deleted boolean not null,
  latest boolean not null,
  name varchar(255) not null,
  type varchar(255) not null,
  state order_state,
  asxml xml,
  asjson json,

  PRIMARY KEY (id, version)
);

-- AUDITS
CREATE TYPE access_type AS ENUM ('READ', 'CREATE', 'UPDATE', 'DELETE');
CREATE TABLE IF NOT EXISTS audits (
  id bigint PRIMARY KEY,
  username varchar(255) NOT NULL,
  firstname varchar(255) NOT NULL,
  lastname varchar(255) NOT NULL,
  date timestamp with time zone NOT NULL,

  element_type varchar(255) NOT NULL,
  element_sub_type varchar(255) NOT NULL,
  element_accessed varchar(255) NOT NULL,
  new_version timestamp with time zone,

  action varchar(255) NOT NULL,
  access_type access_type NOT NULL
);

-- set version
INSERT INTO db_version
  (version, app, description, created)
values(
  '0.1.0',
  'strolch',
  'Initial schema version',
  CURRENT_TIMESTAMP
);

INSERT INTO db_version
  (version, app, description, created)
values(
  '0.2.0',
  'strolch',
  'Added new table for audits',
  CURRENT_TIMESTAMP
);

INSERT INTO db_version
  (version, app, description, created)
values(
  '0.2.1',
  'strolch',
  'Added new column app to table table version',
  CURRENT_TIMESTAMP
);

INSERT INTO db_version
  (version, app, description, created)
values(
  '0.3.0',
  'strolch',
  'Added new column element_sub_type to table audits',
  CURRENT_TIMESTAMP
);

INSERT INTO db_version
  (version, app, description, created)
values(
  '0.4.0',
  'strolch',
  'Added new table activities',
  CURRENT_TIMESTAMP
);

INSERT INTO db_version
  (version, app, description, created)
values(
  '0.5.0',
  'strolch',
  'Added versioning to root elements',
  CURRENT_TIMESTAMP
);

INSERT INTO db_version
  (version, app, description, created)
values(
  '0.5.1',
  'strolch',
  'Added state column to activity, and added new states',
  CURRENT_TIMESTAMP
);

INSERT INTO db_version
  (version, app, description, created)
values(
  '0.6.0',
  'strolch',
  'Added json column to all tables',
  CURRENT_TIMESTAMP
);


text:
class UserRepository
  include Hanami::Repository

  def self.for_token(token)
    query.where(token: token).first
  end

  def self.for_email(email)
    query.where(email: email).first
  end

  def self.authorize(auth)
    user = for_email(auth.email)

    if user.nil? && auth.role == 'admin'
      u = User.from_auth(auth)
      UserRepository.create(u)
    else
      user.generate_token!
      UserRepository.update(user)
    end
  end
end


text:
[![Gem version](https://badge.fury.io/rb/jekyll-minibundle.svg)][MinibundleGem]
[![CI](https://github.com/tkareine/jekyll-minibundle/workflows/CI/badge.svg)][MinibundleCI]

A straightforward asset bundling plugin for [Jekyll], utilizing external
minification tool of your choice. It provides asset concatenation for
bundling and asset fingerprinting with MD5 digest for cache busting.

There are no runtime dependencies, except for the minification tool used
for bundling (fingerprinting has no dependencies).

The plugin requires Jekyll version 3 or 4. It is tested with Ruby MRI
2.5 and later.

The plugin works with Jekyll's watch mode (auto-regeneration, Jekyll
option `--watch`), but not with incremental feature enabled (Jekyll
option `--incremental`).

## Features

There are two features: fingerprinting with [MD5 digest][MD5] over the
contents of the asset file (any type of file will do), and asset
bundling combined with the first feature.

Asset bundling consists of concatenation and minification. The plugin
implements concatenation and leaves choosing the minification tool up to
you. [UglifyJS][UglifyJS2] is a good and fast minifier, for example. The
plugin connects to the minifier with standard unix pipe, feeding asset
file contents to it in desired order via standard input, and reads the
result from standard output.

Why is this good? A fingerprint in asset's path is the [recommended
way][GoogleWebDevHttpCache] to handle caching of static resources,
because you can allow browsers and intermediate proxies to cache the
asset for a very long time. Calculating MD5 digest over the contents of
the file is fast and the resulting digest is reasonably unique to be
generated automatically.

Asset bundling is good for reducing the number of requests to the
backend upon page load. The minification of stylesheets and JavaScript
sources makes asset sizes smaller and thus faster to load over network.

## Usage

The plugin ships as a [RubyGem][MinibundleGem]. To install:

1. Add the following line to the [Gemfile] of your site:

   ``` ruby
   gem 'jekyll-minibundle'
   ```

2. Run `bundle install`.

3. Instruct Jekyll to load the gem by adding this line to the
[configuration file][JekyllConf] of your site (`_config.yml`):

   ``` yaml
   plugins:
     - jekyll/minibundle
   ```

   (Use the `gems` key instead of `plugins` for Jekyll older than v3.5.0.)

An alternative to using the `plugins` configuration option is to add the
`_plugins/minibundle.rb` file to your site project with this line:

``` ruby
require 'jekyll/minibundle'
```

You must allow Jekyll to use custom plugins. That is, do not enable
Jekyll's `safe` configuration option.

### Asset fingerprinting

If you just want to have an MD5 fingerprint in your asset's path, use
the `ministamp` [Liquid] tag in a Liquid template file. For example,
fingerprinting CSS styles:

``` liquid
<link rel="stylesheet" href="{{ site.baseurl }}/{% ministamp _assets/site.css assets/site.css %}" media="screen, projection">
```

When it's time to render the `ministamp` tag, the plugin copies the
source file (`_assets/site.css`, the first tag argument) to the
specified destination path (`assets/site.css`, the second tag argument)
in Jekyll's site destination directory. The filename will contain a
fingerprint.

The tag outputs the asset destination path, encoded for HTML, into
Liquid's template rendering outcome. For example, when `site.baseurl` is
empty:

``` html
<link rel="stylesheet" href="/assets/site-390be921ee0eff063817bb5ef2954300.css" media="screen, projection">
```

Another example, this time fingerprinting an image and using the
[absolute_url][JekyllLiquidFilters] Liquid filter of Jekyll to render
the absolute URL of the image in the `src` attribute:

``` liquid
<img src="{{ "/" | absolute_url }}{% ministamp _assets/dog.jpg assets/dog.jpg %}" alt="My dog smiling to the camera" title="A photo of my dog" width="195" height="258" />
```

This feature can be combined with asset generation tools external to
Jekyll. For example, you can configure [Sass] to take input files from
`_assets/styles/*.scss` and to produce output to `_tmp/site.css`. Then,
you use the `ministamp` tag to copy the file with a fingerprint to
Jekyll's site destination directory:

``` liquid
<link rel="stylesheet" href="{{ site.baseurl }}/{% ministamp _tmp/site.css assets/site.css %}">
```

#### `ministamp` call syntax

The argument for the `ministamp` tag must be in [YAML] syntax, and
parsing the argument as YAML must result either in a String or a
Hash. What you saw previously was the argument being parsed as a String;
it's effectively a shorthand version of passing the argument as a Hash
with certain keys. That is, in the following call:

``` liquid
{% ministamp _tmp/site.css assets/site.css %}
```

the argument is a String: `"_tmp/site.css assets/site.css"`. The call is
equivalent to the following call with a Hash argument:

``` liquid
{% ministamp { source_path: _tmp/site.css, destination_path: assets/site.css } %}
```

The Hash argument allows expressing more options and quoting
`source_path` and `destination_path` values, if needed.

The supported keys for the Hash argument are:

| Key | Required? | Value type | Value example | Default value | Description |
| --- | --- | --- | --- | --- | --- |
| `source_path` | yes | string | `'_tmp/site.css'` | - | The source path of the asset file, relative to the site directory. |
| `destination_path` | yes | string | `'assets/site.css'` | - | The destination path of the asset file, relative to Jekyll's site destination directory. If the value begins with `/` and `render_basename_only` is `false`, `ministamp`'s output will begin with `/`. |
| `render_basename_only` | no | boolean | `true` | `false` | If `true`, `ministamp`'s rendered URL will be the basename of the asset destination path. See [Separating asset destination path from generated URL](#separating-asset-destination-path-from-generated-url) for more. |

With a Hash argument, the plugin processes `source_path` and
`destination_path` values through a tiny template engine. This allows
you to use Liquid's variables as input to `ministamp` tag. An example
with Liquid's [`assign`][LiquidAssignTag] tag:

``` liquid
{% assign asset_dir = 'assets' %}
<link rel="stylesheet" href="{% ministamp { source_path: _tmp/site.css, destination_path: '{{ asset_dir }}/site.css' } %}">
```

The above would use `assets/site.css` as the destination path.

Note that you must quote `destination_path`'s value, otherwise YAML does
not recognize it as a proper string.

To refer to Jekyll's configuration options ([`_config.yml`][JekyllConf])
in the template, prefix the variable name with `site.`. For example, to
refer to `baseurl` option, use syntax `{{ site.baseurl }}` in the
template.

See [Variable templating](#variable-templating) for details about the
template syntax.

### Asset bundling

This is a straightforward way to bundle assets with any minification
tool that supports reading input from stdin and writing the output to
stdout. You write the configuration for input sources directly into the
content file where you want the markup tag for the bundle file to
appear. The markup tag contains the path to the bundle file, and the
Jekyll's site destination directory will have the bundle file at that
path. The path will contain an MD5 fingerprint.

Place the `minibundle` [Liquid] block into the Liquid template file
where you want the block's generated markup to appear. Write bundling
configuration inside the block in [YAML] syntax. For example, to bundle
a set of JavaScript sources:

``` text
{% minibundle js %}
source_dir: _assets/scripts
destination_path: assets/site
baseurl: '{{ site.baseurl }}/'
assets:
  - dependency
  - app
attributes:
  id: my-scripts
  async:
{% endminibundle %}
```

Then, specify the command for launching your favorite minifier in
`_config.yml`:

``` yaml
baseurl: ''

minibundle:
  minifier_commands:
    js: node_modules/.bin/uglifyjs
```

When it's time to render the `minibundle` block, the plugin launches the
minifier and connects to it with a Unix pipe. The plugin feeds the
contents of the asset files in `source_dir` directory as input to the
minifier (stdin). The feeding order is the order of the files in the
`assets` key in the block configuration. The plugin expects the minifier
to produce output (stdout) and writes it to the file at
`destination_path` in Jekyll's site destination directory. The filename
will contain a fingerprint.

The block outputs `<link>` (for `css` type) or `<script>` (for `js`
type) HTML element into Liquid's template rendering outcome. Continuing
the example above, the block's output will be:

``` html
<script src="/assets/site-8e764372a0dbd296033cb2a416f064b5.js" type="text/javascript" id="my-scripts" async></script>
```

You can pass custom attributes, like `id="my-scripts"` and `async`
above, to the generated markup with `attributes` map inside the
`minibundle` block.

As shown above for the `baseurl` key, you can use Liquid template syntax
inside the contents of the block. Liquid renders block contents before
the `minibundle` block gets the turn to render itself. Just ensure that
block contents will result in valid YAML.

For bundling CSS assets, use `css` as the argument to the `minibundle`
block:

``` text
{% minibundle css %}
source_dir: _assets/styles
destination_path: assets/site
baseurl: '{{ site.baseurl }}/'
assets:
  - reset
  - common
attributes:
  media: screen
{% endminibundle %}
```

And then specify the minifier command in `_config.yml`:

``` yaml
minibundle:
  minifier_commands:
    css: _bin/remove_whitespace
    js: node_modules/.bin/uglifyjs
```

#### `minibundle` call syntax

Use `css` or `js` as the argument to the opening tag, for example `{% minibundle css %}`.

The block contents must be in [YAML] syntax. The supported keys are:

| Key | Value type | Value example | Default value | Description |
| --- | --- | --- | --- | --- |
| `source_dir` | string | - | `'_assets'` | The source directory of `assets`, relative to the site directory. You can use period (`.`) to select the site directory itself. |
| `assets` | array of strings | `['deps/one', 'deps/two', 'app']` | `[]` | Array of assets relative to `source_dir` directory, without type extension. These are the asset files to be bundled, in order, into one bundle destination file. |
| `destination_path` | string | - | `'assets/site'` | The destination path of the bundle file, without type extension, relative to Jekyll's site destination directory. If the value begins with `/` and `baseurl` is empty, `baseurl` will be set to `'/'` implicitly. |
| `baseurl` | string | `'{{ site.baseurl }}/'` | `''` | If nonempty, the bundle destination URL inside `minibundle`'s rendered HTML element will be this value prepended to the destination path of the bundle file. Ignored if `destination_baseurl` is nonempty. |
| `destination_baseurl` | string | `'{{ site.cdn_baseurl }}/'` | `''` | If nonempty, the bundle destination URL inside `minibundle`'s rendered HTML element will be this value prepended to the basename of the bundle destination path. See [Separating asset destination path from generated URL](#separating-asset-destination-path-from-generated-url) for more. |
| `attributes` | map of keys to string values | `{id: my-link, media: screen}` | `{}` | Custom HTML element attributes to be added to `minibundle`'s rendered HTML element. |
| `minifier_cmd` | string | `'node_modules/.bin/uglifyjs'` | - | Minifier command specific to this bundle. See [Minifier command specification](#minifier-command-specification) for more. |

### Minifier command specification

You can specify minifier commands in three places:

1. In `_config.yml` (as shown earlier):

   ``` yaml
   minibundle:
     minifier_commands:
       css: _bin/remove_whitespace
       js: node_modules/.bin/uglifyjs
   ```

2. As environment variables:

   ``` bash
   export JEKYLL_MINIBUNDLE_CMD_CSS=_bin/remove_whitespace
   export JEKYLL_MINIBUNDLE_CMD_JS="node_modules/.bin/uglifyjs"
   ```

3. Inside the `minibundle` block with `minifier_cmd` option, allowing
   blocks to have different commands from each other:

   ``` text
   {% minibundle js %}
   source_dir: _assets/scripts
   destination_path: assets/site
   minifier_cmd: node_modules/.bin/uglifyjs
   assets:
     - dependency
     - app
   attributes:
     id: my-scripts
   {% endminibundle %}
   ```

These ways of specification are listed in increasing order of
specificity. Should multiple commands apply to a block, the most
specific one wins. For example, the `minifier_cmd` option inside the `{%
minibundle js }%` block overrides the setting in the
`$JEKYLL_MINIBUNDLE_CMD_JS` environment variable.

### Recommended directory layout

It's recommended that you exclude the files you use as asset sources
from Jekyll itself. Otherwise, you end up with duplicate files in the
site destination directory.

For example, in the following snippet we're using `assets/src.css` as
asset source to `ministamp` tag:

``` liquid
<!-- BAD: unless assets dir is excluded, both src.css and dest.css will be copied to site destination directory -->
<link rel="stylesheet" href="{{ site.baseurl }}/{% ministamp assets/src.css assets/dest.css %}" media="screen, projection">
```

By default, Jekyll includes this file to the site destination
directory. As a result, there will be both `src.css` and
`dest-<md5>.css` files in `_site/assets/` directory, which you probably
do not want.

In order to avoid this, exclude the asset source file from Jekyll.
Because Jekyll's site generation excludes underscore directories (that
is, directories whose name begins with underscore character), consider
using the following directory layout:

* `_assets/` for JavaScript and CSS assets handled by the plugin that
  are in version control
* `_tmp/` for temporary JavaScript and CSS assets handled by the plugin
  that are not in version control (for example, Sass output files)
* `assets/` for images and other assets handled by Jekyll directly

However, Jekyll's watch mode (auto-regeneration) does monitor files
inside underscore directories. If such a file is modified, the watch
mode triggers site generation. For Minibundle's functionality, this is
beneficial: it allows the plugin to check if assets need to be updated
to the site destination directory.

The `exclude` [Jekyll configuration][JekyllConf] option affects Jekyll's
watch mode. Given the recommended directory layout above, if you set the
following in `_config.yml`:

``` yaml
exclude:
  - _assets
  - _tmp
```

Then Jekyll won't see if files inside those directories have changed and
the plugin won't get the chance to update assets to the site destination
directory. So, don't explicitly exclude the `_assets` and `_tmp`
directories.

See [Jekyll configuration][JekyllConf] for more about excluding files
and directories.

### Development mode

If you set the `$JEKYLL_MINIBUNDLE_MODE` environment variable to
`development`, then the plugin will copy asset files as is to Jekyll's
site destination directory and omit fingerprinting.

The development mode changes `minibundle` block's `destination_path`
option to be the base directory for files mentioned in the `assets`
option. This is useful in development workflow, where you need the
filenames and line numbers of the original asset sources.

``` bash
$ JEKYLL_MINIBUNDLE_MODE=development jekyll serve --watch
```

Alternatively, you can enable development mode from `_config.yml`:

``` yaml
minibundle:
  mode: development
```

Should both be defined, the setting from the environment variable wins.

### Variable templating

The template engine used by `ministamp` tag's Hash argument has syntax
resembling the ones of [Liquid] and [Mustache], with `{{` and `}}` tags
surrounding the variable to be substituted into the output string. For
example, given Liquid variable `var = 'foo'`, the template `begin{{ var
}}end` results in `beginfooend`.

The engine supports variable substitution only. It does not support
other expressions. If you need to, you can write complex expressions in
Liquid, store the result to a variable, and use the variable in the
template.

If you need literal `{` or `}` characters in the template, you can
escape them with backslash. For example, `\{` results in `{` in the
output. To output backslash character itself, write it twice: `\\`
results in `\` in the output.

Inside variable subsitution (between `{{` and `}}`), anything before the
closing `}}` tag is interpreted as part of the variable name, except
that the engine removes any leading and trailing whitespace from the
name. For example, in the template `{{ var } }}`, `var }` is treated as
the name of the variable.

A reference to undefined variable results in empty string. For example,
`begin{{ nosuch }}end` will output `beginend` if there's no variable
named `nosuch`.

### Separating asset destination path from generated URL

Use the `render_basename_only: true` option of the `ministamp` tag and
the `destination_baseurl` option of the `minibundle` block to separate
the destination path of the asset file from the generated URL of the
asset. This allows you to serve the asset from a separate domain, for
example.

Example usage, with the following content in `_config.yml`:

``` yaml
cdn_baseurl: 'https://cdn.example.com'
```

For the `ministamp` tag:

``` liquid
<link rel="stylesheet" href="{{ site.cdn_baseurl }}/css/{% ministamp { source_path: '_tmp/site.css', destination_path: assets/site.css, render_basename_only: true } %}">
```

The asset file will be in Jekyll's site destination directory with path
`assets/site-ff9c63f843b11f9c3666fe46caaddea8.css`, and Liquid's
rendering will result in:

``` html
<link rel="stylesheet" href="https://cdn.example.com/css/site-ff9c63f843b11f9c3666fe46caaddea8.css">
```

For the `minibundle` block:

``` liquid
{% minibundle js %}
source_dir: _assets/scripts
destination_path: assets/site
destination_baseurl: '{{ site.cdn_baseurl }}/js/'
assets:
  - dependency
  - app
{% endminibundle %}
```

The bundle file will be in Jekyll's site destination directory with path
`assets/site-4782a1f67803038d4f8351051e67deb8.js`, and Liquid's
rendering will result in:

``` html
<script type="text/javascript" src="https://cdn.example.com/js/site-4782a1f67803038d4f8351051e67deb8.js"></script>
```

### Capturing Liquid output

Use Liquid's [`capture`][LiquidCaptureBlock] block to store output
rendered inside the block to a variable, as a string. Then you can
process the string as you like.

For example:

``` liquid
{% capture site_css %}{% ministamp _assets/site.css assets/site.css %}{% endcapture %}
<link rel="stylesheet" href="{{ site_css | remove_first: "assets/" }}">
```

Liquid's rendering outcome:

``` html
<link rel="stylesheet" href="site-390be921ee0eff063817bb5ef2954300.css">
```

## Example site

See the sources of [an example site][JekyllMinibundleExampleSite].

## Known caveats

The plugin does not work with Jekyll's incremental rebuild feature
(Jekyll option `--incremental`).

## License

MIT. See [LICENSE.txt].

[Gemfile]: https://bundler.io/gemfile.html
[GoogleWebDevHttpCache]: https://web.dev/http-cache/
[JekyllConf]: https://jekyllrb.com/docs/configuration/
[JekyllLiquidFilters]: https://jekyllrb.com/docs/liquid/filters/
[JekyllMinibundleExampleSite]: https://github.com/tkareine/jekyll-minibundle-example
[Jekyll]: https://jekyllrb.com/
[LICENSE.txt]: https://raw.githubusercontent.com/tkareine/jekyll-minibundle/master/LICENSE.txt
[LiquidAssignTag]: https://shopify.github.io/liquid/tags/variable/#assign
[LiquidCaptureBlock]: https://shopify.github.io/liquid/tags/variable/#capture
[Liquid]: https://shopify.github.io/liquid/
[MD5]: https://en.wikipedia.org/wiki/MD5
[MinibundleCI]: https://github.com/tkareine/jekyll-minibundle/actions?workflow=CI
[MinibundleGem]: https://rubygems.org/gems/jekyll-minibundle
[Mustache]: https://mustache.github.io/
[Sass]: https://sass-lang.com/
[UglifyJS2]: https://github.com/mishoo/UglifyJS2
[YAML]: https://yaml.org/


text:
import Ember from 'ember';
import layout from '../../templates/components/activating-item';

const ALLOWED_PREFIXES = ['', 'dashboard.', 'dashboard.catch-redirects.'];

export default Ember.Component.extend({
  routingService: Ember.inject.service('routing'),
  layout: layout,
  classNameBindings: ['active'],

  currentWhen: null,

  active: Ember.computed('routingService.currentPath', 'currentWhen', function() {
    let currentPath = this.get('routingService.currentPath');
    let currentWhen = this.get('currentWhen');

    return ALLOWED_PREFIXES.some((prefix) => {
      // NOTE: Perhaps we could have babel give us startsWith?
      let prefixedCurrentWhen = `${prefix}${currentWhen}`;
      return currentPath.substring(0, prefixedCurrentWhen.length) === prefixedCurrentWhen;
    });
  })
});


text:
from torch.utils.data.sampler import Sampler
import math

def trainable_param(model):
    training = []
    for p in model.parameters():
        if p.requires_grad:
            training.append(p)
    return training

class DistributedSequentialSampler(Sampler):
    """
    A sequential sampler used in FeatureSet when get (train=false) iterator .
    """
    def __init__(self, dataset, num_replicas, rank):
        self.dataset = dataset
        self.num_samples = int(math.floor(len(self.dataset) * 1.0 / num_replicas))
        extra_samples = len(self.dataset) % num_replicas
        self.epoch = 0
        if extra_samples > rank:
            self.num_samples += 1
            self.offset = self.num_samples * rank
        else:
            self.offset = self.num_samples * rank + extra_samples
        self.total_size = len(dataset)

    def __iter__(self):
        indices = list(range(self.offset, self.num_samples + self.offset))

        assert len(indices) == self.num_samples

        return iter(indices)

    def __len__(self):
        return self.num_samples

    def set_epoch(self, epoch):
        self.epoch = epoch


text:
using System;

namespace Atata
{
    /// <summary>
    /// Indicates that a control should use the first occurring element matching the control's definition.
    /// </summary>
    public class FindFirstAttribute : FindAttribute
    {
        public new int Index => base.Index;

        protected override Type DefaultStrategy => typeof(FindFirstDescendantStrategy);

        public override string BuildComponentName(UIComponentMetadata metadata) =>
            1.Ordinalize();
    }
}


text:
.. currentmodule:: dlkit.commenting.records
.. automodule:: dlkit.commenting.records

Records
=======

Comment Record
--------------

.. autoclass:: CommentRecord
   :show-inheritance:

Comment Query Record
--------------------

.. autoclass:: CommentQueryRecord
   :show-inheritance:

Comment Form Record
-------------------

.. autoclass:: CommentFormRecord
   :show-inheritance:

Comment Search Record
---------------------

.. autoclass:: CommentSearchRecord
   :show-inheritance:

Book Record
-----------

.. autoclass:: BookRecord
   :show-inheritance:

Book Query Record
-----------------

.. autoclass:: BookQueryRecord
   :show-inheritance:

Book Form Record
----------------

.. autoclass:: BookFormRecord
   :show-inheritance:

Book Search Record
------------------

.. autoclass:: BookSearchRecord
   :show-inheritance:


text:
package org.apache.aries.versioning.tests;

import static org.junit.Assert.assertEquals;

import org.apache.aries.versioning.utils.SemanticVersioningUtils;
import org.junit.Test;

public class SemanticVersionUtilsTest {

    @Test
    public void testMethodTransform() {

        String returnStr = SemanticVersioningUtils.getReadableMethodSignature("getAccountNum", "(Ljava/lang/String;)Ljava/lang/String;");
        String expectedStr = "method java.lang.String getAccountNum(java.lang.String)";
        assertEquals("The return str is incorrect.", expectedStr, returnStr);

        returnStr = SemanticVersioningUtils.getReadableMethodSignature("handleNotification", "(Ljavax/management/Notification;Ljava/lang/Object;)V");
        expectedStr = "method void handleNotification(javax.management.Notification, java.lang.Object)";
        assertEquals("The return str is incorrect.", expectedStr, returnStr);

        returnStr = SemanticVersioningUtils.getReadableMethodSignature("addItemDeepCopy", "(Lcom/xml/xci/Cursor$Area;Lcom/xml/xci/Cursor;Lcom/xml/xci/Cursor$Profile;Lcom/xml/xci/Cursor$Profile;ZZZ)Lcom/xml/xci/Cursor;");
        expectedStr = "method com.xml.xci.Cursor addItemDeepCopy(com.xml.xci.Cursor$Area, com.xml.xci.Cursor, com.xml.xci.Cursor$Profile, com.xml.xci.Cursor$Profile, boolean, boolean, boolean)";
        assertEquals("The return str is incorrect.", expectedStr, returnStr);

        returnStr = SemanticVersioningUtils.getReadableMethodSignature("createParserAndCompiler", "(Ljavax/xml/transform/Source;Lcom/xltxe/rnm1/xtq/exec/XTQStaticContext;Lcom/xltxe/rnm1/xtq/common/utils/ErrorHandler;)Lcom/xltxe/rnm1/xtq/xquery/drivers/XQueryCompiler;");
        expectedStr = "method com.xltxe.rnm1.xtq.xquery.drivers.XQueryCompiler createParserAndCompiler(javax.xml.transform.Source, com.xltxe.rnm1.xtq.exec.XTQStaticContext, com.xltxe.rnm1.xtq.common.utils.ErrorHandler)";
        assertEquals("The return str is incorrect.", expectedStr, returnStr);

        returnStr = SemanticVersioningUtils.getReadableMethodSignature("getAxis", "()Lcom/xml/xci/exec/Axis;");
        expectedStr = "method com.xml.xci.exec.Axis getAxis()";
        assertEquals("The return str is incorrect.", expectedStr, returnStr);

        returnStr = SemanticVersioningUtils.getReadableMethodSignature("createEmpty", "()Lcom/xml/xci/dp/cache/dom/InternalNodeData;");
        expectedStr = "method com.xml.xci.dp.cache.dom.InternalNodeData createEmpty()";
        assertEquals("The return str is incorrect.", expectedStr, returnStr);

        returnStr = SemanticVersioningUtils.getReadableMethodSignature("addElement", "(Lorg/w3c/dom/Node;)V");
        expectedStr = "method void addElement(org.w3c.dom.Node)";
        assertEquals("The return str is incorrect.", expectedStr, returnStr);

        returnStr = SemanticVersioningUtils.getReadableMethodSignature("isExternalFunctionCall", "(Lcom/xltxe/rnm1/xtq/ast/nodes/FunctionCall;Lcom/xltxe/rnm1/xtq/xpath/drivers/XPathCompiler;)Z");
        expectedStr = "method boolean isExternalFunctionCall(com.xltxe.rnm1.xtq.ast.nodes.FunctionCall, com.xltxe.rnm1.xtq.xpath.drivers.XPathCompiler)";
        assertEquals("The return str is incorrect.", expectedStr, returnStr);

        returnStr = SemanticVersioningUtils.getReadableMethodSignature("wrapForTracing", "(Lcom/xltxe/rnm1/xtq/xslt/runtime/output/ResultTreeSequenceWriterStream$TraceOutputEventGenerator;Lcom/xml/xci/SessionContext;Lcom/xml/xci/Cursor;Lcom/xml/xci/RequestInfo;Lcom/xltxe/rnm1/xtq/xslt/runtime/output/ResultTreeSequenceWriterStream$DeferredTraceResultTreeSequenceWriterStream;)Lcom/xml/xci/Cursor;");
        expectedStr = "method com.xml.xci.Cursor wrapForTracing(com.xltxe.rnm1.xtq.xslt.runtime.output.ResultTreeSequenceWriterStream$TraceOutputEventGenerator, com.xml.xci.SessionContext, com.xml.xci.Cursor, com.xml.xci.RequestInfo, com.xltxe.rnm1.xtq.xslt.runtime.output.ResultTreeSequenceWriterStream$DeferredTraceResultTreeSequenceWriterStream)";
        assertEquals("The return str is incorrect.", expectedStr, returnStr);

        returnStr = SemanticVersioningUtils.getReadableMethodSignature("<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/security/Key;Ljava/security/Key;Ljava/security/cert/Certificate;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IJJLjava/lang/String;)V");
        expectedStr = "constructor with parameter list (java.lang.String, java.lang.String, java.lang.String, java.security.Key, java.security.Key, java.security.cert.Certificate, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, int, long, long, java.lang.String)";
        assertEquals("The return str is incorrect.", expectedStr, returnStr);

    }
}


text:
//
//  boost/detail/atomic_count_sync.hpp
//
//  atomic_count for g++ 4.1+
//
//  http://gcc.gnu.org/onlinedocs/gcc-4.1.1/gcc/Atomic-Builtins.html
//
//  Copyright 2007 Peter Dimov
//
//  Distributed under 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)
//

namespace boost
{

namespace detail
{

class atomic_count
{
public:

    explicit atomic_count( long v ) : value_( v ) {}

    void operator++()
    {
        __sync_add_and_fetch( &value_, 1 );
    }

    long operator--()
    {
        return __sync_add_and_fetch( &value_, -1 );
    }

    operator long() const
    {
        return __sync_fetch_and_add( &value_, 0 );
    }

private:

    atomic_count(atomic_count const &);
    atomic_count & operator=(atomic_count const &);

    mutable long value_;
};

} // namespace detail

} // namespace boost

#endif // #ifndef BOOST_DETAIL_ATOMIC_COUNT_SYNC_HPP_INCLUDED


text:
package com.csvsim;

import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.util.Iterator;

import javassist.CannotCompileException;
import javassist.NotFoundException;

import org.yaml.snakeyaml.Yaml;

import com.csvsim.generator.Generator;
import com.csvsim.wrapper.CsvGenerator;
import com.csvsim.wrapper.utils.CsvGenerator2Graph;
import com.csvsim.wrapper.utils.Wrapper2Object;
import com.martiansoftware.jsap.FlaggedOption;
import com.martiansoftware.jsap.JSAP;
import com.martiansoftware.jsap.JSAPException;
import com.martiansoftware.jsap.JSAPResult;

public class CsvSimulator {

	public static void simulate(CsvGenerator csvGenerator, Integer numRecords) throws InstantiationException, IllegalAccessException, NotFoundException, CannotCompileException {
		Object csvObject = Wrapper2Object.createCsvObject(csvGenerator);
		Generator generator = Wrapper2Object.getGenerator(csvGenerator, csvObject);
		if(numRecords!=null){
			for (int i = 0; i < numRecords; i++) {
				generator.generate();
				System.out.println(csvObject);
			}
		}
		else{
			while (true) {
				generator.generate();
				System.out.println(csvObject);
			}
		}

	}

	@SuppressWarnings("resource")
	public static void simulate(CsvGenerator csvGenerator, Integer numRecords, Integer port) throws InstantiationException, IllegalAccessException, NotFoundException, CannotCompileException {
		try {
			ServerSocket serverSocket = new ServerSocket(port);

			System.out.println("Waiting for connections on port " + port);
			CsvSimulatorServerThread current = new CsvSimulatorServerThread(csvGenerator, numRecords, serverSocket.accept());
			current.start();
			System.out.println("Connected client...");

			while (true) {
				System.out.println("Waiting for connections on port " + port);
				CsvSimulatorServerThread newThread = new CsvSimulatorServerThread(csvGenerator, numRecords, serverSocket.accept());
				current.stopListening();
				current = newThread;
				current.start();
				System.out.println("Connected client...");
			}
		} catch (IOException e) {
			System.err.println(e.getMessage());
			System.exit(-1);
		}
	}

	public static JSAPResult parse(String[] args) throws JSAPException {

		JSAP jsap = new JSAP();

		FlaggedOption configFileOpt = new FlaggedOption("yamlFile", JSAP.STRING_PARSER, null, JSAP.REQUIRED, 'f', JSAP.NO_LONGFLAG, "YAML configuration file");
		FlaggedOption numRecordsOpt = new FlaggedOption("numRecords", JSAP.INTEGER_PARSER, "-1", JSAP.NOT_REQUIRED, 'n', JSAP.NO_LONGFLAG, "Number of records to simulate");
		FlaggedOption dotFileOpt = new FlaggedOption("dotFile", JSAP.STRING_PARSER, null, JSAP.NOT_REQUIRED, 'd', JSAP.NO_LONGFLAG, "DOT filename destiny");
		FlaggedOption portOpt = new FlaggedOption("port", JSAP.INTEGER_PARSER, "-1", JSAP.NOT_REQUIRED, 'p', JSAP.NO_LONGFLAG, "TCP server port");

		jsap.registerParameter(configFileOpt);
		jsap.registerParameter(numRecordsOpt);
		jsap.registerParameter(dotFileOpt);
		jsap.registerParameter(portOpt);

		JSAPResult configuration = jsap.parse(args);

		if (!configuration.success()) {

			@SuppressWarnings("rawtypes")
			Iterator errs = configuration.getErrorMessageIterator();
			while (errs.hasNext()) {
				System.err.println("Error: " + errs.next());
			}

			System.err.println();
			System.err.println("Usage: simulator [OPTIONS]");
			System.err.println("                " + jsap.getUsage());
			System.err.println();
			System.err.println(jsap.getHelp());
			System.exit(1);
		}

		return configuration;
	}

	public static void main(String[] args) throws InstantiationException,
			IllegalAccessException, NotFoundException, CannotCompileException,
			IOException, JSAPException {

		JSAPResult configuration = parse(args);

		String yamlConfigFile = configuration.getString("yamlFile");
		Integer numRecords = (configuration.getInt("numRecords") > 0 ? configuration.getInt("numRecords") : null);
		String dotFilename = configuration.getString("dotFile");
		Integer port = (configuration.getInt("port") > 0 ? configuration.getInt("port") : null);

		Yaml yaml = new Yaml();
		InputStream input = new FileInputStream(yamlConfigFile);
		CsvGenerator csvGenerator = (CsvGenerator) yaml.load(input);

		if (dotFilename != null) {
			CsvGenerator2Graph.toDot(new FileWriter(dotFilename), csvGenerator);
			System.exit(0);
		}

		if (port != null) {
			CsvSimulator.simulate(csvGenerator, numRecords, port);
		} else {
			CsvSimulator.simulate(csvGenerator, numRecords);
		}

	}

}


text:
package org.jboss.arquillian.graphene.ftest.enricher.page.fragment;

import org.jboss.arquillian.graphene.fragment.Root;
import org.openqa.selenium.WebElement;

public abstract class PageFragmentImplementingWebElement implements WebElement {

    @Root
    private WebElement input;

    public String getInputText() {
        return input.getAttribute("value");
    }

    public String getStyleClass() {
        return input.getAttribute("class");
    }
}


text: define("dojox/editor/plugins/nls/sr/InsertEntity",{insertEntity:"Umetni simbol"});


text:
package com.xfhy.daily.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.trello.rxlifecycle2.LifecycleTransformer;
import com.xfhy.androidbasiclibs.basekit.activity.BaseMvpActivity;
import com.xfhy.androidbasiclibs.util.DevicesUtils;
import com.xfhy.androidbasiclibs.util.GlideUtils;
import com.xfhy.androidbasiclibs.util.SnackbarUtil;
import com.xfhy.androidbasiclibs.util.StringUtils;
import com.xfhy.androidbasiclibs.adapter.BaseQuickAdapter;
import com.xfhy.androidbasiclibs.widget.StatefulLayout;
import com.xfhy.daily.R;
import com.xfhy.daily.model.bean.ThemeDailyDetailsBean;
import com.xfhy.daily.presenter.ZHThemeDetailsContract;
import com.xfhy.daily.presenter.impl.ZHThemeDetailsPresenter;
import com.xfhy.daily.ui.adapter.ZHThemeDetailsAdapter;

import java.util.List;

import butterknife.BindView;

public class ThemeActivity extends BaseMvpActivity<ZHThemeDetailsContract.Presenter> implements
        ZHThemeDetailsContract.View, SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter
        .OnItemClickListener {

    private static final String THEME_ID = "theme_id";

    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.sfl_state_view)
    StatefulLayout mStateView;
    @BindView(R.id.cl_theme_top_des)
    CoordinatorLayout mCoordinatorLayout;
    @BindView(R.id.abl_daily_details)
    AppBarLayout mAppBarLayout;
    @BindView(R.id.iv_theme_background)
    ImageView ivThemeBackground;
    @BindView(R.id.tv_theme_description)
    TextView tvThemeDescription;
    @BindView(R.id.rv_th_details_list)
    RecyclerView rvThDetailsList;
    @BindView(R.id.sfl_refresh_layout)
    SwipeRefreshLayout mRefreshLayout;

    /**
     * 当前日报类别的id
     */
    private int mThemeId = -1;
    private ZHThemeDetailsAdapter mThemeDetailsAdapter;

    @Override
    protected int getContentViewResId() {
        return R.layout.activity_theme;
    }

    @Override
    protected void initView() {
        //设置默认标题栏文字
        setToolBar(mToolbar, "...");
        //下拉刷新颜色
        mRefreshLayout.setColorSchemeResources(R.color.colorAccent);
        mThemeDetailsAdapter = new ZHThemeDetailsAdapter(R.layout
                .item_zh_theme_details, null, mContext);
        rvThDetailsList.setLayoutManager(new LinearLayoutManager(this));
        rvThDetailsList.setAdapter(mThemeDetailsAdapter);

        //动画
        mThemeDetailsAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        // 循环播放动画
        mThemeDetailsAdapter.isFirstOnly(false);

        mRefreshLayout.setOnRefreshListener(this);
        mThemeDetailsAdapter.setOnItemClickListener(this);

        //为解决SwipeRefreshLayout和RecyclerView冲突  详情见项目doc文档
        mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                /*
                * 如果竖直的偏移大于0,则设置SwipeRefreshLayout为可用.
                    当我在AppBarLayout可见时,手机由下往上滑动时,verticalOffset<0;
                    当手指由上往下,滑动到顶部,这时手指再由上往下滑动时,verticalOffset=0,
                    这时可以设置SwipeRefreshLayout为可用了.
                * */
                mRefreshLayout.setEnabled(verticalOffset >= 0);
            }
        });

    }

    @Override
    protected void initIntentData() {
        super.initIntentData();
        Intent intent = getIntent();
        if (intent != null) {
            mThemeId = intent.getIntExtra(THEME_ID, -1);
        }
    }

    @Override
    protected void initData() {
        super.initData();
        mPresenter.reqDataFromNet(String.valueOf(mThemeId));
    }

    @Override
    public void onLoading() {
        mStateView.showLoading();
    }

    @Override
    public void closeLoading() {
        mStateView.showContent();
    }

    @Override
    public void showErrorMsg(String msg) {
        closeLoading();
        SnackbarUtil.showBarLongTime(mStateView, msg, SnackbarUtil.ALERT);
    }

    @Override
    public void showEmptyView() {
        closeRefresh();
        mStateView.showEmpty(R.string.stfEmptyMessage, R.string.stfButtonRetry);
    }

    private void closeRefresh() {
        mRefreshLayout.setRefreshing(false);
    }

    @Override
    public void showOffline() {
        closeRefresh();
        closeLoading();
        SnackbarUtil.showBarLongTime(mStateView, StringUtils
                        .getStringByResId(mContext, R.string.stfOfflineMessage), SnackbarUtil
                        .WARNING, StringUtils.getStringByResId(mContext, R.string.stfButtonSetting),
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //未联网  跳转到设置界面
                        DevicesUtils.goSetting(mContext);
                    }
                });
    }

    @Override
    public void showContent() {
        closeRefresh();
        mStateView.showContent();
    }

    @Override
    public void initPresenter() {
        mPresenter = new ZHThemeDetailsPresenter();
    }

    @Override
    public void loadSuccess(ThemeDailyDetailsBean themeDailyDetailsBean) {
        closeRefresh();
        mStateView.showContent();
        setToolBar(mToolbar, themeDailyDetailsBean.getName());
        mThemeDetailsAdapter.replaceData(themeDailyDetailsBean.getStories());
        GlideUtils.loadCustomImage(mContext, themeDailyDetailsBean.getBackground(),
                ivThemeBackground);
        tvThemeDescription.setText(themeDailyDetailsBean.getDescription());
    }

    @Override
    public int getmThemeId() {
        return mThemeId;
    }

    @Override
    protected void initViewEvent() {

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            default:
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 进入知乎主题详情 Activity
     *
     * @param context Context
     * @param id      日报id
     */
    public static void enterZHThemeDetailsActi(Context context, int id) {
        Intent intent = new Intent(context, ThemeActivity.class);
        intent.putExtra(THEME_ID, id);
        context.startActivity(intent);
    }

    @Override
    public void onRefresh() {
        mPresenter.reqDataFromNet(String.valueOf(mThemeId));
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        //进入日报详情页
        ThemeDailyDetailsBean themeDailyDetailsBean = mPresenter.getData();
        if (themeDailyDetailsBean != null) {
            List<ThemeDailyDetailsBean.StoriesBean> stories = themeDailyDetailsBean.getStories();
            if (stories != null && stories.size() > position) {
                ZHDailyDetailsActivity.enterZHDailyDetailsActi(mContext, stories.get(position)
                        .getId());
            }
        }
    }
}


text:
<?php

namespace Italodom\PagseguroBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class ItalodomPagseguroBundle extends Bundle
{
}


text:
import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

import {
  ViroARScene,
  ViroARPlane,
  ViroMaterials,
  ViroImage,
  ViroARPlaneSelector,
  ViroQuad,
  ViroConstants,
  ViroVideo,
  ViroText,
  ViroUtils,
  ViroBox,
  ViroPolygon
} from 'react-viro';

var createReactClass = require('create-react-class');

let polarToCartesian = ViroUtils.polarToCartesian;

var testARScene = createReactClass({
  getInitialState: function() {
    return {
      polygonOpacity : 0,
      updateMap : undefined,
      minValue : 0,
      detectType : 0,
    }
  },
  render: function() {
    return (
    <ViroARScene position={[0,0,0]} reticleEnabled={false} anchorDetectionTypes={this._getDetectType()} displayPointCloud={true}>
      <ViroARPlane
          minHeight={0.3}
          minWidth={0.3}
          alignment={this.state.detectType == 1 ? "Vertical" : "Horizontal"}
          key={"firstPlane"}
          onAnchorFound={this._onAnchorFound}
          onAnchorUpdated={this._onAnchorUpdated}
          onAnchorRemoved={this._onAnchorRemoved} >

        <ViroPolygon
          opacity={this.state.polygonOpacity}
          ref={component=>{this._polySurface = component}}
          rotation={[-90, 0, 0]}
          position={[0,0,0]}
          vertices={[[0,0], [1, 0], [0,1]]}
          materials={"blue_plane"}/>

        <ViroQuad
            ref={component=>{this._surface = component}}
            rotation={[-90, 0, 0]}
            position={[0,-0.0001,0]}
            scale={[1,1,1]}
            materials={"red_plane"}/>

      <ViroBox
      ref={component=>{this._box = component}}

      position={[0,-0.0001,0]}
      scale={[0.05,0.05,0.05]}
          />

      </ViroARPlane>

      <ViroText position={polarToCartesian([6, 50, 20])} text={"Detect Type: " + this._getDetectType()}
        style={styles.instructionText} transformBehaviors={["billboard"]}
        onClick={this._changeDetectType}/>

      {/* Release Menu */}
      <ViroText position={polarToCartesian([6, -30, 25])} text={"Release Menu"}
        style={styles.instructionText} onClick={()=>{this.props.arSceneNavigator.replace("ARReleaseMenu", {scene: require("./ARReleaseMenu")})}}
        transformBehaviors={["billboard"]}/>
    </ViroARScene>);
  },
  _changeDetectType() {
    this.setState({
      detectType : (this.state.detectType == 2) ? 0 : this.state.detectType + 1
    })
  },
  _getDetectType() {
    if (this.state.detectType == 0) {
      return "PlanesHorizontal"
    } else if (this.state.detectType == 1) {
      return "PlanesVertical"
    } else {
      return "None"
    }
  },

  _onAnchorUpdated(updateMap) {
    var polygonPoint = [];
    for (i = 0; i < updateMap.vertices.length; i ++){
      var point = [];
      point.push(updateMap.vertices[i][0]);
      point.push(updateMap.vertices[i][2]);
      polygonPoint.push(point);
    }

    if (!this.state.polygonOpacity){
      this.setState({
        polygonOpacity : 1,
      });
    }

    this.debugSurfacesAndPlanes(updateMap);

    var centeroffset = [updateMap.center[0], updateMap.center[1] - 0.001, updateMap.center[2]];
    this._polySurface.setNativeProps({"position" :centeroffset});
    this._polySurface.setNativeProps({"vertices" : polygonPoint});

    this._surface.setNativeProps({"position" : updateMap.center});
    this._surface.setNativeProps({"width" : updateMap.width});
    this._surface.setNativeProps({"height" : updateMap.height});
  },

  debugSurfacesAndPlanes(updateMap){

        var minX = 999999;
        var minY = 999999;
        var maxX = -999999;
        var maxY = -999999;
        for (i = 0; i < updateMap.vertices.length; i ++){
          var x = updateMap.vertices[i][0];
          var y = updateMap.vertices[i][2];

          if (x < minX){
            minX = x;
          }
          if (x > maxX){
            maxX = x;
          }

          if (y < minY){
            minY = y;
          }
          if (y > maxY){
            maxY = y;
          }
        }

        var mapMinX = updateMap.center[0] - (updateMap.width/2);
        var mapMinY = updateMap.center[2] - (updateMap.height/2);

        var mapMaxX = updateMap.center[0] +(updateMap.width/2);
        var mapMaxY = updateMap.center[2] + (updateMap.height/2);
        // console.log("Viro Surface width/height : " + mapMinX + " , " + mapMinY + " || " + mapMaxX + " , " + mapMaxY  );
        // console.log("Viro  Polygon width/height : " + (maxX - minX) + " , " + (maxY - minY) + "," + (mapMaxX - mapMinX) + " , " + (mapMaxY - mapMinY)  );

        console.log("Viro center is : " + updateMap.center[0]+ ", " + updateMap.center[1] +", " + updateMap.center[2]);
        console.log("Viro position is : " + updateMap.position[0] +", " + updateMap.position[1] +", " + updateMap.position[2]);
  },

  _goToNextTest() {
    this.props.arSceneNavigator.replace("ARPlaneManualTest", {scene:require("./ARPlaneManualTest")})
  },
});

var styles = StyleSheet.create({
  instructionText: {
      fontFamily: 'Arial',
      fontSize: 25,
      width: 2,
      color: '#cccccc',
      flex: 1,
      textAlignVertical: 'center',
      textAlign: 'center',
  },
});

ViroMaterials.createMaterials({
  blue_plane: {
    lightingModel: "Constant",
    diffuseColor: "#0000ff50",
    cullMode:'None'
  },
  red_plane: {
    lightingModel: "Constant",
    diffuseColor: "#ff000050"
  },
});

module.exports = testARScene;


text:
package org.kuali.kfs.module.purap.document.service.impl;

import java.util.ArrayList;
import java.util.Collection;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.kuali.kfs.module.purap.PurapConstants;
import org.kuali.kfs.module.purap.businessobject.PurchaseOrderVendorQuote;
import org.kuali.kfs.module.purap.document.PurchaseOrderDocument;
import org.kuali.kfs.module.purap.document.service.FaxService;
import org.kuali.kfs.module.purap.exception.FaxServerUnavailableError;
import org.kuali.kfs.module.purap.exception.FaxSubmissionError;
import org.kuali.kfs.module.purap.exception.PurError;
import org.kuali.kfs.module.purap.pdf.PurchaseOrderParameters;
import org.kuali.kfs.module.purap.pdf.PurchaseOrderPdf;
import org.kuali.kfs.module.purap.pdf.PurchaseOrderQuotePdf;
import org.kuali.kfs.module.purap.pdf.PurchaseOrderTransmitParameters;
import org.kuali.kfs.sys.KFSConstants;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.sys.service.impl.KfsParameterConstants;
import org.kuali.kfs.vnd.document.service.VendorService;
import org.kuali.rice.core.api.config.property.ConfigurationService;
import org.kuali.rice.coreservice.framework.parameter.ParameterService;
import org.kuali.rice.krad.service.BusinessObjectService;
import org.kuali.rice.krad.util.GlobalVariables;
import org.kuali.rice.location.api.country.Country;
import org.kuali.rice.location.api.country.CountryService;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public class FaxServiceImpl implements FaxService {

    private static final Logger LOG = Logger.getLogger(FaxServiceImpl.class);

    protected ConfigurationService kualiConfigurationService;
    protected ParameterService parameterService;
    protected VendorService vendorService;
    protected BusinessObjectService businessObjectService;
    protected CountryService countryService;

    /**
     * Create the Purchase Order Pdf document and send it via fax to the recipient in the PO
     *
     * @param po PurchaseOrder that holds the Quote
     * @param isRetransmit if passed true then PO is being retransmitted
     * @return Collection of ServiceError objects
     */
    @Override
    public void faxPurchaseOrderPdf(PurchaseOrderDocument po, boolean isRetransmit) {
        LOG.debug("faxPurchaseOrderPdf(po,reTransmit) started");
        String pdfFileLocation = getPdfFileLocation();
        if (pdfFileLocation == null) {
            throw new RuntimeException("Application Setting PDF_DIRECTORY is missing.");
        }

        String imageTempLocation = kualiConfigurationService.getPropertyValueAsString(KFSConstants.TEMP_DIRECTORY_KEY) + "/";
        if (imageTempLocation == null) {
            throw new RuntimeException("Application Setting TEMP_DIRECTORY_KEY is missing.");
        }

        LOG.debug("faxPurchaseOrderPdf() ended");
        this.faxPurchaseOrderPdf(po, pdfFileLocation, imageTempLocation, isRetransmit);
    }

    /**
     * Create the Purchase Order Pdf document and send it via fax to the recipient in the PO
     *
     * @param po PurchaseOrder that holds the Quote
     * @param isRetransmit if passed true then PO is being retransmitted
     * @return Collection of ServiceError objects
     */
    @Override
    public void faxPurchaseOrderPdf(PurchaseOrderDocument po, String pdfFileLocation, String imageTempLocation, boolean isRetransmit) {
        LOG.debug("faxPurchaseOrderPdf() started with locations");

        // Get the vendor's country name.
        if ( StringUtils.isNotBlank( po.getVendorCountryCode() ) ) {
            Country vendorCountry = countryService.getCountry(po.getVendorCountryCode());
            if (vendorCountry != null) {
                po.setVendorCountryCode(vendorCountry.getCode());
            } else {
                po.setVendorCountryCode("NA");
            }
        } else {
            po.setVendorCountryCode("NA");
        }

        PurchaseOrderParameters purchaseOrderParameters = getPurchaseOrderParameters();
        purchaseOrderParameters.setPurchaseOrderPdfAndFaxParameters(po);

        PurchaseOrderPdf poPdf = null;
        try {
            String environment = kualiConfigurationService.getPropertyValueAsString(KFSConstants.ENVIRONMENT_KEY);
            poPdf = new PurchaseOrderPdf();
            poPdf.savePdf(po, purchaseOrderParameters , isRetransmit, environment);
        }
        catch (PurError e) {
            GlobalVariables.getMessageMap().putError("errors", "error.blank");
                                                                                // only need to call once.
            LOG.debug("faxPurchaseOrderPdf() ended");
        }
        catch (Throwable e) {
            LOG.error("faxPurchaseOrderPdf() Faxing Failed on PDF creation - Exception was " + e.getMessage(), e);
            GlobalVariables.getMessageMap().putError("errors", "error.blank", "Faxing Error.  Unable to save pdf file. Please Contact Purchasing");
                                                                                // only need to call once.
            LOG.debug("faxPurchaseOrderPdf() ended");
        }

        PurchaseOrderTransmitParameters transmitParameters =  (PurchaseOrderTransmitParameters)purchaseOrderParameters;
        String[] files = new String[1];
        files[0] = transmitParameters.getPdfFileName();

        try {
            this.faxPDF(files,purchaseOrderParameters);
        }
        catch (FaxSubmissionError e) {
            GlobalVariables.getMessageMap().putError("errors", "error.blank");
        }
        catch (FaxServerUnavailableError e) {
            GlobalVariables.getMessageMap().putError("errors", "error.blank");
        }
        catch (PurError e) {
            GlobalVariables.getMessageMap().putError("errors", "error.blank");
        }
        catch (Throwable e) {
            LOG.error("faxPurchaseOrderPdf() Faxing Failed Exception was " + e.getMessage(), e);
            GlobalVariables.getMessageMap().putError("errors", "error.blank", "Faxing Error.  Please Contact Purchasing");
        }
        finally {
            try {
                if (poPdf != null) {
                    poPdf.deletePdf(pdfFileLocation, transmitParameters.getPdfFileName());
                }
                else {
                    // ignore - PDF can't be deleted if PDF doesn't exist
                }
            }
            catch (Throwable e) {
                LOG.error("faxPurchaseOrderPdf() Error deleting PDF - Exception was " + e.getMessage(), e);
                GlobalVariables.getMessageMap().putError("errors", "error.blank","Your fax was sent successfully but an error occurred that is unrelated to faxing. Please report this problem to Purchasing");
            }
        }

        LOG.debug("faxPurchaseOrderPdf() ended");
    }

    @Override
    public void faxPurchaseOrderQuotePdf(PurchaseOrderDocument po, PurchaseOrderVendorQuote povq) {
        LOG.debug("faxPurchaseOrderQuotePdf() started");

        PurchaseOrderParameters purchaseOrderParameters = getPurchaseOrderParameters();
        purchaseOrderParameters.setPurchaseOrderPdfAndFaxParameters(po,povq);
        String environmentCode = kualiConfigurationService.getPropertyValueAsString(KFSConstants.ENVIRONMENT_KEY);

        PurchaseOrderQuotePdf poQuotePdf = new PurchaseOrderQuotePdf();
        Collection errors = new ArrayList();

        try {

          // Get the vendor's country name.
          if ( StringUtils.isNotBlank( povq.getVendorCountryCode() ) ) {
              Country vendorCountry = countryService.getCountry(po.getVendorCountryCode());
              if (vendorCountry != null) {
                  povq.setVendorCountryCode(vendorCountry.getCode());
              }
              else {
                  povq.setVendorCountryCode("NA");
              }
          }
          else {
              povq.setVendorCountryCode("NA");
          }

          poQuotePdf.savePOQuotePDF(po, povq, purchaseOrderParameters, environmentCode);
        } catch (PurError e) {
          GlobalVariables.getMessageMap().putError("errors", "error.blank");
          LOG.debug("faxPurchaseOrderQuotePdf() ended");

        } catch (Throwable e) {
          LOG.error("faxPurchaseOrderQuotePdf() Faxing Failed on PDF creation - Exception was " + e.getMessage(), e);
          LOG.error("faxPurchaseOrderQuotePdf() Faxing Failed on PDF creation - Exception was " + e.getMessage(), e);
          GlobalVariables.getMessageMap().putError("errors", "error.blank", "Faxing Error.  Unable to save pdf file. Please Contact Purchasing");
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("faxPurchaseOrderQuotePdf() Quote PDF saved successfully for PO " + po.getPurapDocumentIdentifier() + " and Quote ID " + povq.getPurchaseOrderVendorQuoteIdentifier());
        }

        PurchaseOrderTransmitParameters transmitParameters =  (PurchaseOrderTransmitParameters)purchaseOrderParameters;
        String pdfFileLocation = transmitParameters.getPdfFileLocation();
        String pdfFileName     = transmitParameters.getPdfFileName();
        String[] files = new String[1];
        files[0] = pdfFileName;

        try {
          this.faxPDF(files,transmitParameters);
        } catch (FaxSubmissionError e) {
            LOG.error("faxPurchaseOrderQuotePdf() Error faxing Quote PDF" + pdfFileName + " - Exception was " + e.getMessage(), e);
            GlobalVariables.getMessageMap().putError("errors", "error.blank");

        } catch (FaxServerUnavailableError e) {
            LOG.error("faxPurchaseOrderQuotePdf() Error faxing Quote PDF" + pdfFileName + " - Exception was " + e.getMessage(), e);
            GlobalVariables.getMessageMap().putError("errors", "error.blank","The document did not successfully transmit to the fax server. Report this to the Procurement Services Technology group, make note of the document you attempted to transmit and try again when the issue has been resolved");

        } catch (PurError e) {
            LOG.error("faxPurchaseOrderQuotePdf() Error faxing Quote PDF" + pdfFileName + " - Exception was " + e.getMessage(), e);
            GlobalVariables.getMessageMap().putError("errors", "error.blank","The document did not successfully transmit to the fax server. Report this to the Procurement Services Technology group, make note of the document you attempted to transmit and try again when the issue has been resolved");

        } catch (Throwable e) {
            LOG.error("faxPurchaseOrderQuotePdf() Error faxing Quote PDF" + pdfFileName + " - Exception was " + e.getMessage(), e);
            GlobalVariables.getMessageMap().putError("errors", "error.blank","The document did not successfully transmit to the fax server. Report this to the Procurement Services Technology group, make note of the document you attempted to transmit and try again when the issue has been resolved");

        } finally {
          try {
            poQuotePdf.deletePdf(pdfFileLocation, pdfFileName);
          } catch (Throwable e) {
            LOG.error("faxPurchaseOrderQuotePdf() Error deleting Quote PDF" + pdfFileName + " - Exception was " + e.getMessage(), e);
            GlobalVariables.getMessageMap().putError("errors", "error.blank","Your fax was sent successfully but an error occurred that is unrelated to faxing. Please report this problem to Purchasing");

          }
        }

        LOG.debug("faxPurchaseOrderQuotePdf() ended");

    }

    /**
     * Here is where the PDF is actually faxed, needs to be implemented at each institution
     */
    protected void faxPDF(String[] files, PurchaseOrderParameters transmitParameters ) {
        LOG.info("faxPDF() NEEDS TO BE IMPLEMENTED!");
        throw new RuntimeException("faxPDF() NEEDS TO BE IMPLEMENTED!");
    }

    public ConfigurationService getConfigurationService() {
        return kualiConfigurationService;
    }

    public void setConfigurationService(ConfigurationService kualiConfigurationService) {
        this.kualiConfigurationService = kualiConfigurationService;
    }

    public ParameterService getParameterService() {
        return parameterService;
    }

    public void setParameterService(ParameterService parameterService) {
        this.parameterService = parameterService;
    }

    public VendorService getVendorService() {
        return vendorService;
    }

    public void setVendorService(VendorService vendorService) {
        this.vendorService = vendorService;
    }

    public BusinessObjectService getBusinessObjectService() {
        return businessObjectService;
    }

    public void setBusinessObjectService(BusinessObjectService businessObjectService) {
        this.businessObjectService = businessObjectService;
    }

    public CountryService getCountryService() {
        return countryService;
    }

    public PurchaseOrderParameters getPurchaseOrderParameters() {
        return SpringContext.getBean(PurchaseOrderParameters.class);
    }

    public void setCountryService(CountryService countryService) {
        this.countryService = countryService;
    }

    public String getPdfFileLocation() {
        return parameterService.getParameterValueAsString(KfsParameterConstants.PURCHASING_DOCUMENT.class, PurapConstants.PDF_DIRECTORY);
    }

}


text:
package no.kantega.publishing.jobs.contentstate;

import no.kantega.publishing.api.content.ContentIdHelper;
import no.kantega.publishing.api.content.ContentIdentifier;
import no.kantega.publishing.api.link.LinkDao;
import no.kantega.publishing.event.ContentEvent;
import no.kantega.publishing.event.ContentEventListenerAdapter;
import org.springframework.beans.factory.annotation.Autowired;

public class RemoveFromLinkCheckerListener extends ContentEventListenerAdapter {
    @Autowired
    private LinkDao linkDao;

    @Autowired
    private ContentIdHelper contentIdHelper;

    public void contentExpired(ContentEvent event) {
        linkDao.deleteLinksForContentId(event.getContent().getId());
    }

    public void contentSaved(ContentEvent event) {
        if (!event.getContent().isNew()) {
            linkDao.deleteLinksForContentId(event.getContent().getId());
        }
    }

    public void contentPermanentlyDeleted(ContentIdentifier contentIdentifier) {
        contentIdHelper.assureContentIdAndAssociationIdSet(contentIdentifier);
        linkDao.deleteLinksForContentId(contentIdentifier.getContentId());
    }
}


text:
namespace Microsoft.Azure.Management.Compute
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// SharedGalleriesOperations operations.
    /// </summary>
    public partial interface ISharedGalleriesOperations
    {
        /// <summary>
        /// List shared galleries by subscription id or tenant id.
        /// </summary>
        /// <param name='location'>
        /// Resource location.
        /// </param>
        /// <param name='sharedTo'>
        /// The query parameter to decide what shared galleries to fetch when
        /// doing listing operations. Possible values include: 'tenant'
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<IPage<SharedGallery>>> ListWithHttpMessagesAsync(string location, string sharedTo = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Get a shared gallery by subscription id or tenant id.
        /// </summary>
        /// <param name='location'>
        /// Resource location.
        /// </param>
        /// <param name='galleryUniqueName'>
        /// The unique name of the Shared Gallery.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<SharedGallery>> GetWithHttpMessagesAsync(string location, string galleryUniqueName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// List shared galleries by subscription id or tenant id.
        /// </summary>
        /// <param name='nextPageLink'>
        /// The NextLink from the previous successful call to List operation.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<IPage<SharedGallery>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
    }
}


text:
class CreateJoinTablePrivilegeUser < ActiveRecord::Migration
  def change
    create_join_table :privileges, :users do |t|
      t.index [:privilege_id, :user_id]
      t.index [:user_id, :privilege_id]
    end
  end
end


text:
package types

type Node interface {
	Name() string

	Accept(visitor NodeVisitor)
}

type NodeSlice []Node

func (n NodeSlice) ContainsNode(node Node) bool {
	for _, n2 := range n {
		if n2 == node {
			return true
		}
	}
	return false
}


text:
package com.pacinetes.dom.polizalct;

import java.util.List;
import org.apache.isis.applib.annotation.Action;
import org.apache.isis.applib.annotation.ActionLayout;
import org.apache.isis.applib.annotation.BookmarkPolicy;
import org.apache.isis.applib.annotation.DomainService;
import org.apache.isis.applib.annotation.DomainServiceLayout;
import org.apache.isis.applib.annotation.MemberOrder;
import org.apache.isis.applib.annotation.NatureOfService;
import org.apache.isis.applib.annotation.SemanticsOf;

@DomainService(
        nature = NatureOfService.VIEW_MENU_ONLY,
        repositoryFor = PolizaLCT.class
)
@DomainServiceLayout(
        named = "Polizas Listar",
        menuOrder = "30"
)
public class PolizaLCTListarMenu {

	  @Action(semantics = SemanticsOf.SAFE)
	  @ActionLayout(bookmarking = BookmarkPolicy.AS_ROOT, named="Listar Polizas LCT")
	  @MemberOrder(sequence = "90")
	  public List<PolizaLCT> listar() {
			  List<PolizaLCT> listaPolizaRiesgoLCT = polizasRepository.listar();
			  for(int i=0; i< listaPolizaRiesgoLCT.size(); i++) {
				  listaPolizaRiesgoLCT.get(i).actualizarPoliza();
		        }
		      return listaPolizaRiesgoLCT;
	    }

	    @javax.inject.Inject
	    PolizaLCTRepository polizasRepository;
}