text:
<?php

/**
* Class CBlogManage is the administrative part of the system - for news items.
*/
class CBlogManage {

	private $db;

	/**
	* @param object $db
	*/
	public function __construct($db) {
		$this->db = $db;
	}

	/**
 	* Create a slug of a string, to be used as url.
	*
	* @param string $str the string to format as slug.
	* @returns str the formatted slug.
	*/
	function slugify($str) {
	  	$str = mb_strtolower(trim($str));
	  	$str = str_replace(array('å','ä','ö'), array('a','a','o'), $str);
	  	$str = preg_replace('/[^a-z0-9-]/', '-', $str);
	  	$str = trim(preg_replace('/-+/', '-', $str), '-');
	  	return $str;
	}

	/**
	* getAllContent selecting everything from table content.
	*/
	public function getAllContent() {
		// Select from database
        $sql = "SELECT * FROM content";

		$param = array();
		$res = $this->db->ExecuteSelectQueryAndFetchAll($sql, $param);

		if(isset($res)) {
			return $res;
		} else {
			die("Något gick fel!");
		}
	}

	/**
	* getContentOneID selecting content from a specific given id.
	* @param string $idRef
	* @return array $resArray
	*/
	public function getContentOneID($idRef) {
		//Select from database
        $sql = "
			SELECT c1.*, c2.*
			FROM content c1, category c2, content2category m2g
			WHERE c1.id = m2g.idContent AND m2g.idCategory = c2.id
			AND c1.id = ?;
		";

        $res = $this->db->ExecuteSelectQueryAndFetchAll($sql, array($idRef));

        //If the ID was found and $res is not null...
        if(isset($res[0])) {
        	//Get genres and trim
			$categories = "";
			foreach($res as $val) {
				$categories .= $val->name . ', ';
			}

			$categories = rtrim($categories, ", ");
            $value	= $res[0];
            $title  = htmlentities($value->title, null, 'UTF-8');

            //Put content in array
			$resArray 	= array (
				"title" 	=> "{$title}",
				"text" 		=> "{$value->DATA}",
				"slug"		=> "{$value->slug}",
				"category" 	=> "{$categories}",
				"type" 		=> "{$value->TYPE}",
				"filter" 	=> "{$value->FILTER}",
				"published" => "{$value->published}",
				"created" 	=> "{$value->created}",
			);
        } else {
            die('Misslyckades: det finns inget innehåll med sådant id.');
        }
        return $resArray;
	}

	/**
	* createInformation makes it possible to create a news item.
	* @return string $output
	*/
	public function createInformation() {

		//call function $this->checkValid() and put boolean in $validUpdate.
		$validUpdate 	= $this->checkValid();

		//If $validUpdate is true...
		if($validUpdate == true) {

			//Post-variables
			$title 		= strip_tags($_POST['title']);
	        $text       = strip_tags($_POST['text']);
	        $slug     	= strip_tags($_POST['slug']);
	        $slug 		= $this->slugify($slug);
	        $filter 	= "";
	        $setDisplay = "";

	        //Publish or not.
	        if($_POST['published']	=='yes') {
	        	$published = date("Y-m-d H:i:s");
	        	$display = "yes"; //published
	        } else {
	        	$published = 'null';
	        	$display = "no";
	        }

	        //Filters...
			if($_POST['bbcode']		=='yes') {$filter .= 'bbcode,';} 		//bbcode
			if($_POST['link']		=='yes') {$filter .= 'link,';} 			//link
			if($_POST['shortcode']	=='yes') {$filter .= 'shortcode,';} 	//shortcode
			if($_POST['nl2br']		=='yes') {$filter .= 'nl2br,';} 		//nl2br
			if($_POST['markdown']	=='yes') {$filter .= 'markdown';} 		//markdown
			$filter = rtrim($filter, ',');

			//SQL
			$sql = "
	        	INSERT INTO content
	        	(title, data, slug, filter, display, published)
	        	VALUES(?, ?, ?, ?, ?, ?)
	        ";

	        $paramArray = array($title, $text, $slug, $filter, $display, $published);
	        $res = $this->db->ExecuteQuery($sql, $paramArray);

	        //If $res is not null then insert data.
	        if($res) {
	        	//get the last inserted id.
	        	$id = $this->db->LastInsertId();

	        	//Fill $categoryArray and call categorySQLInsert() to insert chosen categories.
		        if(isset($_POST['rmstore'])) 	{$category = $_POST['rmstore']; 	$categoryArray[] = $category;}
		        if(isset($_POST['newmovies'])) 	{$category = $_POST['newmovies']; 	$categoryArray[] = $category;}
		        if(isset($_POST['oldmovies'])) 	{$category = $_POST['oldmovies']; 	$categoryArray[] = $category;}
		        if(isset($_POST['movieworld'])) {$category = $_POST['movieworld']; 	$categoryArray[] = $category;}

		        foreach($categoryArray as $val) {
		        	$this->categorySQLInsert($id, $val);
		        }

	            $output = "
Informationen sparades.
";
	        } else {
	         	$output = "
Informationen sparades EJ.
";
	        }
		} else {
			$output = "
Vänligen fyll i alla rutor.
";
		}
		return $output;
	}

	/**
	* updateInformation makes it possible to update a news item.
	* @return string $output
	*/
	public function updateInformation() {
		//define $id by the $_POST['id'] and call function $this->checkValid() and put boolean in $validUpdate.
		$id         	= $_POST['id'];
		$validUpdate 	= $this->checkValid($id);

		//If $validUpdate is true...
		if($validUpdate == true) {

			//call function to delete categories...
			$this->categorySQLDelete($id);
			$categoryArray = array();

			//Fill $categoryArray and call categorySQLInsert() to insert chosen categories.
	        if(isset($_POST['rmstore'])) 	{$category = $_POST['rmstore']; 	$categoryArray[] = $category;}
	        if(isset($_POST['newmovies'])) 	{$category = $_POST['newmovies']; 	$categoryArray[] = $category;}
	        if(isset($_POST['oldmovies'])) 	{$category = $_POST['oldmovies']; 	$categoryArray[] = $category;}
	        if(isset($_POST['movieworld'])) {$category = $_POST['movieworld']; 	$categoryArray[] = $category;}

	        foreach($categoryArray as $val) {
	        	$this->categorySQLInsert($id, $val);
	        }

			//Post-variables
			$title 		= strip_tags($_POST['title']);
	        $text       = strip_tags($_POST['text']);
	        $slug     	= strip_tags($_POST['slug']);
	        $slug 		= $this->slugify($slug);
	        $filter 	= "";
	        $setDisplay = "";
	        $where = " WHERE content.id = ?";

	        //Publish or not.
	        if($_POST['published']	=='yes') {
	        	$published = date("Y-m-d H:i:s");
	        	$setDisplay = "content.display = 'yes'"; //published
	        } else {
	        	$published = 'null';
	        	$setDisplay = "content.display = 'no'";
	        }

	        //Filters...
			if($_POST['bbcode']		=='yes') {$filter .= 'bbcode,';} 		//bbcode
			if($_POST['link']		=='yes') {$filter .= 'link,';} 			//link
			if($_POST['shortcode']	=='yes') {$filter .= 'shortcode,';} 	//shortcode
			if($_POST['nl2br']		=='yes') {$filter .= 'nl2br,';} 		//nl2br
			if($_POST['markdown']	=='yes') {$filter .= 'markdown';} 		//markdown
			$filter = rtrim($filter, ',');

			//SQL
	        $sqlOrig = '
	            UPDATE content SET
	            content.title = ?,
	            content.DATA = ?,
	            content.slug = ?,
	            content.filter = ?,
	            content.published = ?,
	        ';

	        $sql = $sqlOrig . $setDisplay . $where;

	        $paramArray = array($title, $text, $slug, $filter, $published, $id);
	        $res = $this->db->ExecuteQuery($sql, $paramArray);

	        //If $res is not null...
	        if($res) {
	            $output = "
Informationen sparades.
";
	        } else {
	         	$output = "
Informationen sparades EJ.
";
	        }
		} else {
			$output = "
Vänligen fyll i alla rutor.
";
		}
		return $output;
	}

	/**
	* deleteInformation makes it possible to delete a news item.
	*/
	public function deleteInformation() {
		//Define ID and query
		$id         = strip_tags($_POST['id']);
		$sql = '
		DELETE FROM content2category
		WHERE idContent = ' . $id . ';

		DELETE FROM content
		WHERE id = ' . $id . ';
		';

        $res = $this->db->ExecuteQuery($sql, array($id));
        header("Location: news.php");
        die();
	}

	/**
	* checkValid will return a boolean with a true or false-state depending on what $_POST[]'s that has been filled out.
	* @return bool $returnBool
	*/
	private function checkValid() {
		if (
	        !empty($_POST['title'])			&& !empty($_POST['text']) 		&& !empty($_POST['slug']) &&
	        !empty($_POST['published']) 	&& !empty($_POST['shortcode']) 	&& !empty($_POST['bbcode'])  &&
	        !empty($_POST['link'])			&& !empty($_POST['markdown'])	&& !empty($_POST['nl2br'])
	    ) {
			if (
	        	isset($_POST['rmstore'])	|| isset($_POST['newmovies']) 	|| isset($_POST['oldmovies']) 	||
	        	isset($_POST['movieworld'])
	        ) {
	        	$returnBool = true;
	        } else {
	        	$returnBool = false;
	        }
	    } else {
	    	$returnBool = false;
	    }
        return $returnBool;
	}

	/**
	* categorySQLDelete will delete all categories with a specific given ID.
	* @param string $id
	*/
	private function categorySQLDelete($id) {
		//Ta bort från DB först för att undvika dubletter.
		$sql = "DELETE FROM content2category WHERE idContent=?";
		$paramArray = array($id);
        $res = $this->db->ExecuteQuery($sql, $paramArray);
	}

	/**
	* categorySQLInsert will insert the given categories to a news item.
	* @param string $id, strinng $category
	*/
	private function categorySQLInsert($id, $category) {
		$sql = "INSERT INTO content2category(idContent, idCategory) VALUES(?, ?)";
        $paramArray = array($id, $category);
        $res = $this->db->ExecuteQuery($sql, $paramArray);
	}

	/**
	* createNewsUserPanel will create the HTML markup for a overview of available news item.
	* @param array $movieObject
	* @return string $out
	*/
	public function createNewsUserPanel($movieObject) {
		$out = '

Nyhetshantering

Är biblioteket lite klent? - Lägg till nyhet

		';

		foreach($movieObject AS $key => $val) {
			$out .= '

'
					. $val->title . ' -
					slug .'">Visa -
					id.'">Redigera -
					id.'">Ta bort

'
			;
		}
		$out .= '
';
		return $out;
	}

	/**
	* createForm will create the HTML markup for creating a news item.
	* @return string $out
	*/
	public function createForm() {
		$out = "
			<form method='post' class='edit-form-properties'>

  				<fieldset>
					<legend>Skapa nyhet</legend>

Titel:
		<input class='movie-search-full' type='text' 		name='title'/>

Text:
		<textarea style='max-width: 100%;width:100%;'		name='text'></textarea>

Slug:
			<input class='movie-search-full' type='text' 	name='slug'/>

Kategori

						RM Store <input type='checkbox' 		name='rmstore' value='1' />
						New Movies <input type='checkbox' 		name='newmovies' value='2' />
						Old Movies <input type='checkbox' 		name='oldmovies' value='3' />
						Movieworld <input type='checkbox' 		name='movieworld' value='4' />

bbcode2html

								Yes <input type='radio' name='bbcode' value='yes'>
		    					No <input type='radio' name='bbcode' value='no'>

makeClickable

								Yes <input type='radio' name='link' value='yes'>
		    					No <input type='radio' name='link' value='no'>

Markdown

								Yes <input type='radio' name='markdown' value='yes'>
		    					No <input type='radio' name='markdown' value='no'>

nl2br

								Yes <input type='radio' name='nl2br' value='yes'>
		    					No <input type='radio' name='nl2br' value='no'>

Shortcode

								Yes <input type='radio' name='shortcode' value='yes'>
		    					No <input type='radio' name='shortcode' value='no'>

Publicera din nyhet?

						Ja <input type='radio' name='published' value='yes' />
						Nej <input type='radio' name='published' value='no' />

<input type='submit' name='save' value='Spara'/>

				</fieldset>

			</form>

				Tillbaks till nyheterna

		";
		return $out;
	}

	/**
	* createEditForm will create the HTML markup for editing a news item.
	* @return string $out
	* @param string $id, array $editArray
	*/
	public function createEditForm($id, $editArray) {

		//Define variables for the form.
		$title 		= htmlentities($editArray['title'], null, 'UTF-8');
		$text 		= htmlentities($editArray['text'], null, 'UTF-8');
		$genres 	= htmlentities($editArray['category'], null, 'UTF-8');
		$type 		= htmlentities($editArray['type'], null, 'UTF-8');
		$filter 	= htmlentities($editArray['filter'], null, 'UTF-8');
		$published 	= htmlentities($editArray['published'], null, 'UTF-8');
		$created 	= htmlentities($editArray['created'], null, 'UTF-8');
		$slug 		= htmlentities($editArray['slug'], null, 'UTF-8');

		$out = "
			<form method='post' class='edit-form-properties'>

  				<fieldset>
					<legend>Uppdatera innehåll</legend>

					<input type='hidden' name='id' value='{$id}'/>

Titel:
		<input class='movie-search-full' type='text' 		name='title' value='{$title}'/>

Text:
		<textarea style='max-width: 100%;width:100%;'		name='text'>{$text}</textarea>

Slug:
			<input class='movie-search-full' type='text' 	name='slug' value='{$slug}'/>

Kategori

						RM Store <input type='checkbox' 		name='rmstore' value='1' />
						New Movies <input type='checkbox' 		name='newmovies' value='2' />
						Old Movies <input type='checkbox' 		name='oldmovies' value='3' />
						Movieworld <input type='checkbox' 		name='movieworld' value='4' />

bbcode2html

								Yes <input type='radio' name='bbcode' value='yes'>
		    					No <input type='radio' name='bbcode' value='no'>

makeClickable

								Yes <input type='radio' name='link' value='yes'>
		    					No <input type='radio' name='link' value='no'>

Markdown

								Yes <input type='radio' name='markdown' value='yes'>
		    					No <input type='radio' name='markdown' value='no'>

nl2br

								Yes <input type='radio' name='nl2br' value='yes'>
		    					No <input type='radio' name='nl2br' value='no'>

Shortcode

								Yes <input type='radio' name='shortcode' value='yes'>
		    					No <input type='radio' name='shortcode' value='no'>

Publicera din nyhet?

						Ja <input type='radio' name='published' value='yes' />
						Nej <input type='radio' name='published' value='no' />

<input type='submit' name='save' value='Spara'/>

				</fieldset>

			</form>

				Tillbaks till filmen

		";
		return $out;
	}

	/**
	* createDeleteForm will create the HTML markup for deleting a news item.
	* @return string $out
	* @param string $id, array $deleteArray
	*/
	public function createDeleteForm($id, $deleteArray) {

		//Define the title of the news item.
		$title 		= htmlentities($deleteArray['title'], null, 'UTF-8');

		$out = "
			<form method='post' class='delete-form-properties'>
  				<fieldset>
					<legend>Ta bort</legend>
					<input type='hidden' name='id' value='{$id}'/>
					<input type='hidden' name='title' value='{$title}'/>

						Titel: {$title}

						<input type='submit' name='delete' value='Ta Bort'/>

				</fieldset>
			</form>

				Tillbaks till nyheten

		";
		return $out;
	}
}


text:
package org.ohdsi.webapi.source;

import java.util.List;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;

public interface SourceDaimonRepository extends CrudRepository<SourceDaimon, Integer> {

    @Query("select sd from SourceDaimon sd join sd.source s where s.deletedDate is null and sd.daimonType = :daimonType and sd.priority >= 0")
    List<SourceDaimon> findByDaimonType(@Param("daimonType") SourceDaimon.DaimonType daimonType);

    List<SourceDaimon> findBySource(Source source);
}

redpajama_set_name: RedPajamaGithub


text:
package com.datatorrent.lib.streamquery.condition;

import java.util.Map;

import javax.validation.constraints.NotNull;

/**
 * An implementation of equal join condition class.
 *

 * This compares values of given keys in both row data.
 *

 *  Properties :

 * <b. equalkeys :  Keys for which value must be compared.

 *

 * @displayName Join Column Equal Condition
 * @category Stream Manipulators
 * @tags sql condition, equal join
 * @since 0.3.3
 */
public class JoinColumnEqualCondition  extends Condition
{

  /**
   * column names to be compared.
   */
  @NotNull
  private String column1;
  @NotNull
  private String column2;

  public JoinColumnEqualCondition(@NotNull String column1, @NotNull String column2)
  {
    this.column1 = column1;
    this.column2 = column2;
  }

  /**
   * Must never be called.
   */
  @Override
  public boolean isValidRow(Map<String, Object> row)
  {
    assert (false);
    return false;
  }

  /**
   *
   */
  @Override
  public boolean isValidJoin(Map<String, Object> row1, Map<String, Object> row2)
  {
    if (!row1.containsKey(column1) || !row2.containsKey(column2)) {
      return false;
    }
    Object value1 = row1.get(column1);
    Object value2 = row2.get(column2);
    return value1.equals(value2);
  }
}


text:
#ifndef QTCONCURRENT_MAPKERNEL_H
#define QTCONCURRENT_MAPKERNEL_H

#include <QtConcurrent/qtconcurrent_global.h>

#ifndef QT_NO_CONCURRENT

#include <QtConcurrent/qtconcurrentiteratekernel.h>
#include <QtConcurrent/qtconcurrentreducekernel.h>

QT_BEGIN_NAMESPACE

#ifndef Q_QDOC
namespace QtConcurrent {

// map kernel, works with both parallel-for and parallel-while
template <typename Iterator, typename MapFunctor>
class MapKernel : public IterateKernel<Iterator, void>
{
    MapFunctor map;
public:
    typedef void ReturnType;
    MapKernel(Iterator begin, Iterator end, MapFunctor _map)
        : IterateKernel<Iterator, void>(begin, end), map(_map)
    { }

    bool runIteration(Iterator it, int, void *)
    {
        map(*it);
        return false;
    }

    bool runIterations(Iterator sequenceBeginIterator, int beginIndex, int endIndex, void *)
    {
        Iterator it = sequenceBeginIterator;
        std::advance(it, beginIndex);
        for (int i = beginIndex; i < endIndex; ++i) {
            runIteration(it, i, 0);
            std::advance(it, 1);
        }

        return false;
    }
};

template <typename ReducedResultType,
          typename Iterator,
          typename MapFunctor,
          typename ReduceFunctor,
          typename Reducer = ReduceKernel<ReduceFunctor,
                                          ReducedResultType,
                                          typename MapFunctor::result_type> >
class MappedReducedKernel : public IterateKernel<Iterator, ReducedResultType>
{
    ReducedResultType reducedResult;
    MapFunctor map;
    ReduceFunctor reduce;
    Reducer reducer;
public:
    typedef ReducedResultType ReturnType;
    MappedReducedKernel(Iterator begin, Iterator end, MapFunctor _map, ReduceFunctor _reduce, ReduceOptions reduceOptions)
        : IterateKernel<Iterator, ReducedResultType>(begin, end), reducedResult(), map(_map), reduce(_reduce), reducer(reduceOptions)
    { }

    MappedReducedKernel(ReducedResultType initialValue,
                     MapFunctor _map,
                     ReduceFunctor _reduce)
        : reducedResult(initialValue), map(_map), reduce(_reduce)
    { }

    bool runIteration(Iterator it, int index, ReducedResultType *)
    {
        IntermediateResults<typename MapFunctor::result_type> results;
        results.begin = index;
        results.end = index + 1;

        results.vector.append(map(*it));
        reducer.runReduce(reduce, reducedResult, results);
        return false;
    }

    bool runIterations(Iterator sequenceBeginIterator, int begin, int end, ReducedResultType *)
    {
        IntermediateResults<typename MapFunctor::result_type> results;
        results.begin = begin;
        results.end = end;
        results.vector.reserve(end - begin);

        Iterator it = sequenceBeginIterator;
        std::advance(it, begin);
        for (int i = begin; i < end; ++i) {
            results.vector.append(map(*(it)));
            std::advance(it, 1);
        }

        reducer.runReduce(reduce, reducedResult, results);
        return false;
    }

    void finish()
    {
        reducer.finish(reduce, reducedResult);
    }

    bool shouldThrottleThread()
    {
        return IterateKernel<Iterator, ReducedResultType>::shouldThrottleThread() || reducer.shouldThrottle();
    }

    bool shouldStartThread()
    {
        return IterateKernel<Iterator, ReducedResultType>::shouldStartThread() && reducer.shouldStartThread();
    }

    typedef ReducedResultType ResultType;
    ReducedResultType *result()
    {
        return &reducedResult;
    }
};

template <typename Iterator, typename MapFunctor>
class MappedEachKernel : public IterateKernel<Iterator, typename MapFunctor::result_type>
{
    MapFunctor map;
    typedef typename MapFunctor::result_type T;
public:
    typedef T ReturnType;
    typedef T ResultType;

    MappedEachKernel(Iterator begin, Iterator end, MapFunctor _map)
        : IterateKernel<Iterator, T>(begin, end), map(_map) { }

    bool runIteration(Iterator it, int,  T *result)
    {
        *result = map(*it);
        return true;
    }

    bool runIterations(Iterator sequenceBeginIterator, int begin, int end, T *results)
    {

        Iterator it = sequenceBeginIterator;
        std::advance(it, begin);
        for (int i = begin; i < end; ++i) {
            runIteration(it, i, results + (i - begin));
            std::advance(it, 1);
        }

        return true;
    }
};

template <typename Iterator, typename Functor>
inline ThreadEngineStarter<void> startMap(Iterator begin, Iterator end, Functor functor)
{
    return startThreadEngine(new MapKernel<Iterator, Functor>(begin, end, functor));
}

template <typename T, typename Iterator, typename Functor>
inline ThreadEngineStarter<T> startMapped(Iterator begin, Iterator end, Functor functor)
{
    return startThreadEngine(new MappedEachKernel<Iterator, Functor>(begin, end, functor));
}

/*
    The SequnceHolder class is used to hold a reference to the
    sequence we are working on.
*/
template <typename Sequence, typename Base, typename Functor>
struct SequenceHolder1 : public Base
{
    SequenceHolder1(const Sequence &_sequence, Functor functor)
        : Base(_sequence.begin(), _sequence.end(), functor), sequence(_sequence)
    { }

    Sequence sequence;

    void finish()
    {
        Base::finish();
        // Clear the sequence to make sure all temporaries are destroyed
        // before finished is signaled.
        sequence = Sequence();
    }
};

template <typename T, typename Sequence, typename Functor>
inline ThreadEngineStarter<T> startMapped(const Sequence &sequence, Functor functor)
{
    typedef SequenceHolder1<Sequence,
                            MappedEachKernel<typename Sequence::const_iterator , Functor>, Functor>
                            SequenceHolderType;

    return startThreadEngine(new SequenceHolderType(sequence, functor));
}

template <typename IntermediateType, typename ResultType, typename Sequence, typename MapFunctor, typename ReduceFunctor>
inline ThreadEngineStarter<ResultType> startMappedReduced(const Sequence & sequence,
                                                           MapFunctor mapFunctor, ReduceFunctor reduceFunctor,
                                                           ReduceOptions options)
{
    typedef typename Sequence::const_iterator Iterator;
    typedef ReduceKernel<ReduceFunctor, ResultType, IntermediateType> Reducer;
    typedef MappedReducedKernel<ResultType, Iterator, MapFunctor, ReduceFunctor, Reducer> MappedReduceType;
    typedef SequenceHolder2<Sequence, MappedReduceType, MapFunctor, ReduceFunctor> SequenceHolderType;
    return startThreadEngine(new SequenceHolderType(sequence, mapFunctor, reduceFunctor, options));
}

template <typename IntermediateType, typename ResultType, typename Iterator, typename MapFunctor, typename ReduceFunctor>
inline ThreadEngineStarter<ResultType> startMappedReduced(Iterator begin, Iterator end,
                                                           MapFunctor mapFunctor, ReduceFunctor reduceFunctor,
                                                           ReduceOptions options)
{
    typedef ReduceKernel<ReduceFunctor, ResultType, IntermediateType> Reducer;
    typedef MappedReducedKernel<ResultType, Iterator, MapFunctor, ReduceFunctor, Reducer> MappedReduceType;
    return startThreadEngine(new MappedReduceType(begin, end, mapFunctor, reduceFunctor, options));
}

} // namespace QtConcurrent

#endif //Q_QDOC

QT_END_NAMESPACE

#endif // QT_NO_CONCURRENT

#endif


text:
<!-- Connection configuration for connecting to MySQL DB. -->
<?php
$servername = "localhost";
$username = "root";
$password = "admin";
?>


text:
"""Placeholder objects for hinted evolutions.

Version Added:
    2.2
"""

from __future__ import unicode_literals

from django_evolution.compat.translation import gettext as _
from django_evolution.errors import EvolutionException

class BasePlaceholder(object):
    """A placeholder object for use in generating hints.

    Placeholder objects provide stand-ins for values that must be hand-added
    to the evolution file.

    Version Added:
        2.2
    """

    #: The text used in the placeholder.
    #:
    #: Type:
    #:     unicode
    placeholder_text = None

    def __init__(self, app_label=None, model_name=None, field_name=None):
        """Initialize the object.

        Args:
            app_label (unicode, optional):
                The label of the application owning the model.

            model_name (unicode, optional):
                The name of the model owning the field.

            field_name (unicode, optional):
                The name of the field to return an initial value for.
        """
        self.app_label = app_label
        self.model_name = model_name
        self.field_name = field_name

    def __repr__(self):
        """Return a string representation of the object.

        This is used when outputting the value in a hinted evolution.

        Returns:
            unicode:
            The placeholder text.
        """
        return self.placeholder_text

    def __call__(self):
        """Handle calls on this object.

        This will raise an exception stating that the evolution cannot be
        performed.

        Raises:
            django_evolution.errors.EvolutionException:
                An error stating that an explicit initial value must be
                provided in place of this object.
        """
        raise EvolutionException(
            _('Cannot use hinted evolution: Mutation requires a '
              'user-specified value.'))

class NullFieldInitialCallback(BasePlaceholder):
    """A placeholder for an initial value for a field.

    This is used in place of an initial value in mutations for fields that
    don't allow NULL values and don't have an explicit initial value set.
    It will show up in hinted evolutions as ``<<USER VALUE REQUIRED>>`` and
    will fail to evolve.
    """

    placeholder_text = '<<USER VALUE REQUIRED>>'

    def __call__(self):
        """Handle calls on this object.

        This will raise an exception stating that the evolution cannot be
        performed.

        Raises:
            django_evolution.errors.EvolutionException:
                An error stating that an explicit initial value must be
                provided in place of this object.
        """
        raise EvolutionException(
            _('Cannot use hinted evolution: AddField or ChangeField mutation '
              'for "%s.%s" in "%s" requires user-specified initial value.')
            % (self.model_name, self.field_name, self.app_label))


text:
<?php

/**
 * opRenrakumouHelper.
 *
 * @package    OpenPNE
 * @subpackage helper
 * @author     Kaoru Nishizoe <nishizoe@tejimaya.com>
 */

function remove_assets()
{
  $response = sfContext::getInstance()->getResponse();
  $stylesheets = $response->getStylesheets();
  foreach ($stylesheets as $file => $opt)
  {
    $response->removeStylesheet($file);
  }

  $javascripts = $response->getJavascripts();
  foreach ($javascripts as $file => $opt)
  {
    $response->removeJavascript($file);
  }
}


text:
#ifndef __NGEN_BUILD_NGEN_REFLECTION_LOGIC_HPP
#define __NGEN_BUILD_NGEN_REFLECTION_LOGIC_HPP

#include "Ngen.hpp"

/** @brief Used to export or import public symbols from the framework. */
#if _tkn_Platform == _tknval_Platform_Windows
#  ifdef NGEN_REFLECTION_EXPORT
#       define ngen_reflection_api __declspec(dllexport)
#  elif defined(__MINGW32__)
#     define ngen_reflection_api
#  else
#     define ngen_reflection_api __declspec(dllimport)
#  endif
#else // other supported platforms (Linux, MacOSX and iPhone)
#	if (__GNUC__ >= 4) // && defined(NGEN_EXPORT)
#       ifdef(NGEN_EXPORT)
#		    define ngen_reflection_api __attribute__ ((visibility("default")))
#       else
#           define ngen_reflection_api
#       endif
      /** @brief Used to export or import private symbols from the framework. */
#		define ngen_api_private __attribute__ ((visibility("hidden")))
#	else
#     define ngen_reflection_api
      /** @brief Used to export or import private symbols from the framework. */
#     define ngen_reflection_api_private
#	endif
#endif

#endif


text:
package org.camunda.bpm.engine.rest.dto.batch;

import org.camunda.bpm.engine.batch.BatchStatistics;

public class BatchStatisticsDto extends BatchDto {

  protected int remainingJobs;
  protected int completedJobs;
  protected int failedJobs;

  public int getRemainingJobs() {
    return remainingJobs;
  }

  public int getCompletedJobs() {
    return completedJobs;
  }

  public int getFailedJobs() {
    return failedJobs;
  }

  public static BatchStatisticsDto fromBatchStatistics(BatchStatistics batchStatistics) {
    BatchStatisticsDto dto = new BatchStatisticsDto();
    dto.id = batchStatistics.getId();
    dto.type = batchStatistics.getType();
    dto.totalJobs = batchStatistics.getTotalJobs();
    dto.jobsCreated = batchStatistics.getJobsCreated();
    dto.batchJobsPerSeed = batchStatistics.getBatchJobsPerSeed();
    dto.invocationsPerBatchJob = batchStatistics.getInvocationsPerBatchJob();
    dto.seedJobDefinitionId = batchStatistics.getSeedJobDefinitionId();
    dto.monitorJobDefinitionId = batchStatistics.getMonitorJobDefinitionId();
    dto.batchJobDefinitionId = batchStatistics.getBatchJobDefinitionId();
    dto.tenantId = batchStatistics.getTenantId();
    dto.createUserId = batchStatistics.getCreateUserId();
    dto.suspended = batchStatistics.isSuspended();

    dto.remainingJobs = batchStatistics.getRemainingJobs();
    dto.completedJobs = batchStatistics.getCompletedJobs();
    dto.failedJobs = batchStatistics.getFailedJobs();
    return dto;
  }

}


text:
from canari.maltego.utils import debug
from canari.framework import configure
from canari.maltego.message import Label, UIMessage
from common.entities import Case, Hyperlinks, Attachments
from common.client import search_case, get_case, encode_to_utf8, ThreatCentralError

__author__ = 'Bart Otten'
__copyright__ = '(c) Copyright [2016] Hewlett Packard Enterprise Development LP'
__credits__ = []

__license__ = 'Apache 2.0'
__version__ = '1'
__maintainer__ = 'Bart Otten'
__email__ = 'tc-support@hpe.com'
__status__ = 'Development'

__all__ = [
    'dotransform'
]

@configure(
    label='Search Case in Threat Central',
    description='Searches Case in Threat Central',
    uuids=['threatcentral.v2.CaseToThreatCentral'],
    inputs=[('Threat Central', Case)],
    debug=False,
    remote=False
)
def dotransform(request, response, config):

    try:
        case = get_case(request.fields['ThreatCentral.resourceId'])
    except ThreatCentralError as err:
        response += UIMessage(err.value, type='PartialError')
        return response
    except KeyError:
        try:
            cases = search_case(request.value)
        except ThreatCentralError as err:
            response += UIMessage(err.value, type='PartialError')
            return response
        else:
            try:
                for case in cases:
                    if case.get('tcScore'):
                        weight = int(case.get('tcScore'))
                    else:
                        weight = 1

                    case = case.get('resource')
                    e = Case(encode_to_utf8(case.get('title')), weight=weight)
                    e.title = encode_to_utf8(case.get('title'))
                    e.resourceId = case.get('resourceId')

                    if case.get('importanceScore'):
                        e.importanceScore = case.get('importanceScore')
                        e += Label('Importance Score', case.get('importanceScore'))
                    if case.get('importanceLevel'):
                        e.importanceLevel = case.get('importanceLevel')
                        e += Label('Importance Level', case.get('importanceLevel'))

                    # Show comments
                    if len(case.get('comments', list())) is not 0:
                        e += Label('Comments', '
'.join(['{}
'.format(_.get('text'))
                                                             for _ in encode_to_utf8(case.get('comments'))]))
                    if case.get('description'):
                        e += Label('Description', '
'.join(encode_to_utf8(case.get('description')
                                                                              ).split('\n')))

                    response += e

            except AttributeError as err:
                response += UIMessage('Error: {}'.format(err), type='PartialError')
            except ThreatCentralError as err:
                response += UIMessage(err.value, type='PartialError')
            except TypeError:
                return response

    else:
        if case:
            try:
                # Update entity?
                e = Case(request.value)
                if case.get('title'):
                    e.case = encode_to_utf8(case.get('title'))
                    e.title = encode_to_utf8(case.get('title'))
                    e += Label('Title', encode_to_utf8(case.get('title')))
                if case.get('resourceId'):
                    e += Label('ResourceID', case.get('resourceId'))
                if case.get('description'):
                    e += Label('Description', '
'.join(encode_to_utf8(case.get('description', '')).split('\n')))
                if case.get('importanceScore'):
                    e.importanceScore = case.get('importanceScore')
                    e += Label('Importance Score', case.get('importanceScore'))
                if case.get('importanceLevel'):
                    e.importanceLevel = case.get('importanceLevel')
                    e += Label('Importance Level', case.get('importanceLevel'))

                # Show comments
                if len(case.get('comments', list())) is not 0:
                    e += Label('Comments', '
'.join(['{}
'.format(_.get('text'))
                                                         for _ in encode_to_utf8(case.get('comments'))]))

                response += e

                # Show Hyperlinks
                if len(case.get('hyperlinks', list())) is not 0:
                    for hyperlink in case.get('hyperlinks'):
                        e = Hyperlinks(encode_to_utf8(hyperlink.get('title')))
                        e.title = encode_to_utf8(hyperlink.get('title'))
                        e.resourceId = hyperlink.get('resourceId')
                        e.url = hyperlink.get('url')
                        e += Label('Title', encode_to_utf8(hyperlink.get('title')))
                        e += Label('Resource ID', hyperlink.get('resourceId'))
                        e += Label('url', hyperlink.get('url'))

                        response += e

                # Show Attachments
                if len(case.get('attachments', list())) is not 0:
                    for attachment in case.get('attachments'):
                        e = Attachments(encode_to_utf8(attachment.get('name')))
                        e.name = encode_to_utf8(attachment.get('name'))
                        e.resourceId = attachment.get('resourceId')
                        e.atype = attachment.get('type')
                        e.size = attachment.get('size')
                        e.checksum = attachment.get('checksum')
                        e.createDate = attachment.get('createDate')
                        if attachment.get('description'):
                            e += Label('Description', '
'.join(encode_to_utf8(attachment.get('description')
                                                                                ).split('\n')))
                        if len(attachment.get('links', list())) is not 0:
                            for att in attachment.get('links', list()):
                                e += Label('Links', '{}
'.format(att.get('href'), att.get('href')))

                        response += e

            except AttributeError as err:
                response += UIMessage('Error: {}'.format(err), type='PartialError')
            except ThreatCentralError as err:
                response += UIMessage(err.value, type='PartialError')
            except TypeError:
                return response

    return response


text:
package org.mifos.reports.ui;

import static org.mifos.reports.util.helpers.ReportsConstants.NA_DATE;
import static org.mifos.reports.util.helpers.ReportsConstants.NOT_APPLICABLE_DISPLAY_NAME;

import java.io.Serializable;
import java.util.Date;

import org.mifos.framework.util.helpers.DateUtils;

public class DateSelectionItem implements Serializable {

    public static final DateSelectionItem NA_MEETING_DATE = new DateSelectionItem(NA_DATE, NOT_APPLICABLE_DISPLAY_NAME);

    private Date date;
    private String displayDate;

    // For Hibernate
    public DateSelectionItem() {
        super();
    }

    public DateSelectionItem(Date date) {
        this.date = date;
    }

    public DateSelectionItem(Date date, String display) {
        this.date = date;
        this.displayDate = display;
    }

    public Date getDate() {
        return date;
    }

    public String getDisplayDate() {
        return displayDate != null ? displayDate : DateUtils.getLocalizedDateFormat().format(date);
    }

    @Override
    public int hashCode() {
        final int PRIME = 31;
        int result = 1;
        result = PRIME * result + ((date == null) ? 0 : date.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final DateSelectionItem other = (DateSelectionItem) obj;
        if (date == null) {
            if (other.date != null) {
                return false;
            }
        } else if (!date.equals(other.date)) {
            return false;
        }
        return true;
    }
}


text:
using System.Threading;
using System.Threading.Tasks;
using HelloCoreClrApp.Data.Entities;
using Microsoft.EntityFrameworkCore;

namespace HelloCoreClrApp.Data
{
    public class GreetingDbContext : DbContext
    {
        public GreetingDbContext(DbContextOptions options)
            : base(options)
        {
        }

        public DbSet<Greeting> Greetings { get; set; }

        public async Task EnsureCreated(CancellationToken token) => await Database.EnsureCreatedAsync(token);
    }
}


text:
<?php

/**
 * Generic class which will hold authentication information, including username,
 * organization, and credentials (of any type).
 *
 * @author Eugene Davis
 */
abstract class AuthenticationInformation
{
    /**
     *
     * @var String
     */
    private $userName;
    /**
     *
     * @var String
     */
    private $organization;
    /**
     * Holds the credential information - could be password, token, etc
     * @var Mixed
     */
    private $credentials;

    /**
     * Child function should check the credentials are in the right format
     * then call this constructor
     * @param String $orguser
     * @param Mixed $credentials
     * @throws BadMethodCallException
     */
    public function __construct($orguser, $credentials)
    {
         // Check that the orguser variable is a string
        if (!is_string($orguser))
        {
            // TODO: Should be a bad constructor call
            throw new BadMethodCallException("Constructor not passed a string for organization/username.");
        }

        // Break the orguser variable into its component parts (format is <Organization>/<Username>)
        $orgUserExplodedArray = explode("/", $orguser);

        // Check that this resulted in two strings in the array
        if (count($orgUserExplodedArray) != 2)
        {
            // TODO: Should be a bad constructor call
            throw new BadMethodCallException("Constructor not passed a properly formatted string for organization/user.");
        }

        $this->organization = $orgUserExplodedArray[0];
        $this->userName = $orgUserExplodedArray[1];

        // Set the credentials variable
        $this->credentials = $credentials;
    }

    /**
     * Returns the UserName
     * @return String
     */
    public function getUserName()
    {
        return $this->userName;
    }

    /**
     * Returns the organization name
     * @return String
     */
    public function getOrganization()
    {
        return $this->organization;
    }

    /**
     * Returns the credentials (maybe password, maybe token, etc)
     * @return Mixed
     */
    public function getCredentials()
    {
        return $this->credentials;
    }

    /**
     * Returns the string naming the authentication method to use
     * @return String
     */
    abstract function getAuthenticationMethod();

}


text:
<docs-demo :meta="meta" :snippet="snippet">

		state icon <input type="checkbox" v-model="stateIcon">
		size
			<select v-model="size">
				<option v-for="option in sizes" v-bind:value="option.value">
			    {{ option.text }}
			  </option>
			</select>

		state
			<select v-model="state">
				<option v-for="option in states" v-bind:value="option.value">
			    {{ option.text }}
			  </option>
			</select>

			<vs-form-input
		    :model.sync="model"
		    type="text"
		    label="Example Label"
		    placeholder="Placeholder"
		    description="We'll never share your email with anyone else."
		    :size="size"
		    :state-icon="stateIcon"
		    :state="state">
			</vs-form-input>

</docs-demo>


text:
"""
A bunch of loading functions for datasets used internally at indico for
testing and development. At some point we'll clean this up and have standard
interfaces for academic/personal datasets.
"""

import theano
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer,CountVectorizer
from sklearn.cross_validation import train_test_split
import os
import cPickle
from time import time,sleep
from sklearn.externals import joblib
from skimage.color import rgb2gray
from skimage.transform import resize
from scipy.misc import imread,imsave
from scipy.io import loadmat
from scipy.spatial.distance import cdist

from cv2 import imread as cv2_imread
from cv2 import resize as cv2_resize
from cv2 import INTER_AREA,INTER_LINEAR
from cv2 import cvtColor
from cv2 import COLOR_BGR2RGB

from skimage.transform import resize

import random
import re

# change to where datasets are kept for you
datasets_dir = '/media/datasets/'

def sort(l):
	convert = lambda text: int(text) if text.isdigit() else text
	alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
	return sorted(l, key = alphanum_key)

def one_hot(x):
	if type(x) == list:
		x = np.array(x)
	x = x.flatten()
	o_h = np.zeros((len(x),np.max(x)+1))
	o_h[np.arange(len(x)),x] = 1
	return o_h

def gimg_top_n_for_n_labels(n_imgs=125,n_labels=100,onehot=False,w=64,h=64,flatten=False):
	data_dir = os.path.join(datasets_dir,'gimg/imgs')
	random.seed(42)
	np.random.seed(42)
	fs = ['_'.join(f.split('_')[:-1]) for f in os.listdir(data_dir)]
	labels = list(set(fs))
	print 'n files %.0f n labels %0.f'%(len(fs),len(labels))
	fs = [os.path.join(data_dir,f) for f in os.listdir(data_dir)]
	label2fs = dict(zip(labels,[[] for _ in range(len(labels))]))
	for f in fs:
		label2fs['_'.join(f.split('_')[:-1]).split('/')[-1]].append(f)
	labels = random.sample(labels,n_labels)
	label2fs = dict(zip(labels,(sort(label2fs[label])[:n_imgs] for label in labels)))

	X = [[] for _ in range(n_imgs*n_labels)]
	Y = [[] for _ in range(n_imgs*n_labels)]
	n = 0
	paths = []
	for i,label in enumerate(labels):
		for f in label2fs[label]:
			img = load_imagenet_img(f,w=w,h=h,resize=True)/127.5-1.
			if flatten:
				img = img.flatten()
			paths.append(f)
			X[n] = img
			Y[n] = i
			n += 1
	if onehot:
		Y = one_hot(np.array(Y).astype(int))
	else:
		Y = np.asarray(Y,dtype=theano.config.floatX)
	X = np.asarray(X,dtype=theano.config.floatX)
	return X,Y

def center_crop(img,n_pixels):
	img = img[n_pixels:img.shape[0]-n_pixels,n_pixels:img.shape[1]-n_pixels]
	return img

def lfw(n_imgs=1000,flatten=True):
	data_dir = os.path.join(datasets_dir,'lfw/lfw-deepfunneled')
	if n_imgs == 'all':
		n_imgs = 13233
	n = 0
	imgs = []
	Y = []
	n_to_i = {}
	for root, subFolders, files in os.walk(data_dir):
		if subFolders == []:
			if len(files) >= 2:
				for f in files:
					if n < n_imgs:
						if n % 1000 == 0: print n
						path = os.path.join(root,f)
						img = imread(path)/255.
						img = resize(center_crop(img,53),(32,32,3))-0.5
						if flatten:
							img = img.flatten()
						imgs.append(img)
						n += 1
						name = root.split('/')[-1]
						if name not in n_to_i:
							n_to_i[name] = len(n_to_i)
						Y.append(n_to_i[name])
					else:
						break
	imgs = np.asarray(imgs,dtype=theano.config.floatX)
	Y = np.asarray(Y)
	i_to_n = dict(zip(n_to_i.values(),n_to_i.keys()))
	return imgs,Y,n_to_i,i_to_n

def img_load(path,w,h,resize=True):
	img = cv2_imread(path)
	if len(img.shape) == 2:
		img = np.dstack((img,img,img))
	if resize:
		img = cv2_resize(img,(w,h)).astype(np.uint8)
	img = cvtColor(img,COLOR_BGR2RGB)
	return img

def load_imagenet_img(path,w=32,h=32,resize=True):
	img = img_load(path,w,h,resize=resize)
	img = img.transpose(2,0,1)
	return img

def mnist(ntrain=60000,ntest=10000,onehot=False):
	data_dir = os.path.join(datasets_dir,'mnist')
	fd = open(os.path.join(data_dir,'train-images.idx3-ubyte'))
	loaded = np.fromfile(file=fd,dtype=np.uint8)
	trainX = loaded[16:].reshape((60000,28*28)).astype(float)

	fd = open(os.path.join(data_dir,'train-labels.idx1-ubyte'))
	loaded = np.fromfile(file=fd,dtype=np.uint8)
	trainY = loaded[8:].reshape((60000))

	fd = open(os.path.join(data_dir,'t10k-images.idx3-ubyte'))
	loaded = np.fromfile(file=fd,dtype=np.uint8)
	testX = loaded[16:].reshape((10000,28*28)).astype(float)

	fd = open(os.path.join(data_dir,'t10k-labels.idx1-ubyte'))
	loaded = np.fromfile(file=fd,dtype=np.uint8)
	testY = loaded[8:].reshape((10000))

	trainX = trainX/255.
	testX = testX/255.

	trainX = trainX[:ntrain]
	trainY = trainY[:ntrain]

	testX = testX[:ntest]
	testY = testY[:ntest]

	if onehot:
		trainY = one_hot(trainY)
		testY = one_hot(testY)

	return trainX,testX,trainY,testY


text:
// Provides control sap.ui.unified.CalendarLegend.
sap.ui.define(['jquery.sap.global', 'sap/ui/core/Control', './library'],
	function(jQuery, Control, library) {
	"use strict";

	/**
	 * Constructor for a new CalendarLegend.
	 *
	 * @param {string} [sId] id for the new control, generated automatically if no id is given
	 * @param {object} [mSettings] initial settings for the new control
	 *
	 * @class
	 * A legend for the Calendar Control. Displays special dates colors with their corresponding description. The aggregation specialDates can be set herefor.
	 * @extends sap.ui.core.Control
	 *
	 * @author SAP SE
	 * @version 1.30.4-SNAPSHOT
	 *
	 * @constructor
	 * @public
	 * @since 1.24.0
	 * @alias sap.ui.unified.CalendarLegend
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */
	var CalendarLegend = Control.extend("sap.ui.unified.CalendarLegend", /** @lends sap.ui.unified.CalendarLegend.prototype */ { metadata : {

		library : "sap.ui.unified",
		properties : {

			/**
			 * Width of the columns created in which the items are arranged.
			 */
			columnWidth : {type : "sap.ui.core.CSSSize", group : "Misc", defaultValue : '120px'}
		},
		aggregations : {

			/**
			 * Items to be displayed.
			 */
			items : {type : "sap.ui.unified.CalendarLegendItem", multiple : true, singularName : "item"},
			standardItems : {type : "sap.ui.unified.CalendarLegendItem", multiple : true, visibility : "hidden"}
		}
	}});

	CalendarLegend.prototype.init = function() {

		var rb = sap.ui.getCore().getLibraryResourceBundle("sap.ui.unified");
		var sId = this.getId();

		var oItem = new sap.ui.unified.CalendarLegendItem(sId + "-Today", {
			text: rb.getText("LEGEND_TODAY")
		});
		this.addAggregation("standardItems", oItem);

		oItem = new sap.ui.unified.CalendarLegendItem(sId + "-Selected", {
			text: rb.getText("LEGEND_SELECTED")
		});
		this.addAggregation("standardItems", oItem);

		oItem = new sap.ui.unified.CalendarLegendItem(sId + "-NormalDay", {
			text: rb.getText("LEGEND_NORMAL_DAY")
		});
		this.addAggregation("standardItems", oItem);
		oItem = new sap.ui.unified.CalendarLegendItem(sId + "-NonWorkingDay", {
			text: rb.getText("LEGEND_NON_WORKING_DAY")
		});
		this.addAggregation("standardItems", oItem);

	};

	// IE9 workaround for responsive layout of legend items
	CalendarLegend.prototype.onAfterRendering = function() {
		if (sap.ui.Device.browser.msie) {
			if (sap.ui.Device.browser.version < 10) {
				jQuery(".sapUiUnifiedLegendItem").css("width", this.getColumnWidth() + 4 + "px").css("display", "inline-block");
			}
		}
	};

	return CalendarLegend;

}, /* bExport= */ true);


text:
<?php namespace CmdZ\SpamCanner\Tests\Utilities;

use CmdZ\SpamCanner\Utilities\Utilities;
use Mockery;

class UtilitiesTest extends \PHPUnit_Framework_TestCase
{

    /** @var  Utilities */
    protected $utils;

    public function setUp()
    {
        $this->utils = new Utilities();
    }

    public function tearDown()
    {
        Mockery::close();
    }

    public function testFindLinks()
    {
        $this->utils = new Utilities();
        $urls[] = 'www.apple.com';
        $urls[] = 'http://microsoft.com';
        $doesNotContain[] = 'me.com';
        $text = 'aslfd alskjf asldfj ' . $urls[0] . ' ;lasdfjl . ' . $doesNotContain[0] . 'a;slfd ' .
            $urls[1] . ' asdflj';
        $result = $this->utils->findLinks($text);

        $this->assertContains($urls[0], $result);
        $this->assertContains($urls[1], $result);
        $this->assertNotContains($doesNotContain[0], $result);
    }

    public function testGetClassName()
    {
        $expected = 'stdClass';
        $sc = new \stdClass();
        $result = $this->utils->getClassName($sc);
        $this->assertSame($expected, $result);

        $expected = 'UtilitiesTest';
        $ut = new self();
        $result = $this->utils->getClassName($ut);
        $this->assertSame($expected, $result);
    }

    /**
     * @method arrayContainsOnlyInstancesOf()
     * @test
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage $obj not instance of $class
     */
    public function it_throws_if_not_an_instance_of_class()
    {
        $interface = 'SplSubject';
        $interfaceMock = Mockery::mock($interface);
        $class = 'stdClass';
        $classMock = Mockery::mock($class);
        $haystack = [$classMock, $interfaceMock];
        $this->utils->arrayContainsOnlyInstancesOf($class, $haystack);
    }

    /**
     * @method arrayContainsOnlyInstancesOf()
     * @test
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage Class does not exist
     */
    public function it_throws_if_class_doesnt_exits()
    {
        $exception = 'asdlfj';
        $haystack = [$exception, $exception];
        $this->utils->arrayContainsOnlyInstancesOf($exception, $haystack);
    }

    /**
     * @method arrayContainsOnlyInstancesOf()
     * @test
     */
    public function it_returns_true_if_only_instances_of_class()
    {
        $interface = 'SplSubject';
        $mock = Mockery::mock($interface);
        $haystack = [$mock, $mock];
        $result = $this->utils->arrayContainsOnlyInstancesOf($interface, $haystack);
        $this->assertSame(true, $result);

        $class = 'stdClass';
        $mock = Mockery::mock($class);
        $haystack = [$mock, $mock];
        $result = $this->utils->arrayContainsOnlyInstancesOf($class, $haystack);
        $this->assertSame(true, $result);
    }
}


text:
package com.interface21.transaction;

/**
 * Exception that gets thrown when an invalid timeout is specified,
 * i.e. the transaction manager implementation doesn't support timeouts.
 * @author Juergen Hoeller
 * @since 12.05.2003
 */
public class InvalidTimeoutException extends TransactionUsageException {

	private int timeout = TransactionDefinition.TIMEOUT_DEFAULT;

	public InvalidTimeoutException(String msg, int timeout) {
		super(msg);
		this.timeout = timeout;
	}

	public int getTimeout() {
		return timeout;
	}

}


text:
namespace star
{
	TimeManager::TimeManager()
		: Singleton<TimeManager>()
		, m_StartTime()
		, m_DeltaTime()
		, m_ElapsedTime()
		, m_CurrentTime()
	{

	}

	TimeManager::~TimeManager()
	{

	}

	const Time & TimeManager::DeltaTime()
	{
		return m_DeltaTime;
	}

	const Time & TimeManager::TimeSinceStart()
	{
		return m_ElapsedTime;
	}

	const Time & TimeManager::CurrentTime()
	{
		m_CurrentTime.m_TimeDuration =
			std::chrono::high_resolution_clock::now().time_since_epoch();
		return m_CurrentTime;
	}

	void TimeManager::StartMonitoring()
	{
		m_StartTime = std::chrono::high_resolution_clock::now();
	}

	void TimeManager::StopMonitoring()
	{
		auto endTime = std::chrono::high_resolution_clock::now();
		m_DeltaTime.m_TimeDuration = endTime - m_StartTime;
		m_ElapsedTime += m_DeltaTime;
	}

	tstring TimeManager::GetTimeStamp()
	{
		int32 totalSeconds = int32(m_ElapsedTime.GetSeconds());
		int32 seconds = totalSeconds % 60;
		int32 minutes = totalSeconds / 60;
		int32 hours = totalSeconds / 3600;

		tstringstream strstr;
		if(hours < 10)
		{
			strstr << _T("0");
		}
		strstr << hours << _T(":");
		if(minutes < 10)
		{
			strstr << _T("0");
		}
		strstr << minutes << _T(":");
		if(seconds < 10)
		{
			strstr << _T("0");
		}
		strstr << seconds;

		return strstr.str();
	}

}


text:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis quis adipiscing est. Curabitur vel dui dolor. Vestibulum molestie fermentum diam, nec interdum ante molestie ut. Integer consequat iaculis auctor. Duis vitae felis ligula, ultrices blandit dolor.

A little bit of content.

A little bit of content.


text:
package science.atlarge.graphalytics.openg;

import science.atlarge.graphalytics.configuration.GraphalyticsExecutionException;
import science.atlarge.graphalytics.domain.benchmark.BenchmarkRun;
import science.atlarge.graphalytics.domain.graph.FormattedGraph;
import science.atlarge.graphalytics.openg.OpengConfiguration;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.Executor;
import org.apache.commons.exec.PumpStreamHandler;
import org.apache.commons.exec.util.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.commons.io.output.TeeOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.nio.file.Path;

/**
 * Base class for graph loading in the platform driver.
 *
 * @author Wing Lung Ngai
 */
public class OpengLoader {

	private static final Logger LOG = LogManager.getLogger();

	protected CommandLine commandLine;
	protected FormattedGraph formattedGraph;
	protected OpengConfiguration platformConfig;

	/**
	 *	Graph loader for Openg.
	 * @param formattedGraph
	 * @param platformConfig
	 */
	public OpengLoader(FormattedGraph formattedGraph, OpengConfiguration platformConfig) {
		this.formattedGraph = formattedGraph;
		this.platformConfig = platformConfig;
	}

	public int load(String loadedInputPath) throws Exception {
		String loaderDir = platformConfig.getLoaderPath();
		commandLine = new CommandLine(Paths.get(loaderDir).toFile());

		commandLine.addArgument("--graph-name");
		commandLine.addArgument(formattedGraph.getName());
		commandLine.addArgument("--input-vertex-path");
		commandLine.addArgument(formattedGraph.getVertexFilePath());
		commandLine.addArgument("--input-edge-path");
		commandLine.addArgument(formattedGraph.getEdgeFilePath());
		commandLine.addArgument("--output-path");
		commandLine.addArgument(loadedInputPath);
		commandLine.addArgument("--directed");
		commandLine.addArgument(formattedGraph.isDirected() ? "true" : "false");
		commandLine.addArgument("--weighted");
		commandLine.addArgument(formattedGraph.hasEdgeProperties() ? "true" : "false");

		String commandString = StringUtils.toString(commandLine.toStrings(), " ");
		LOG.info(String.format("Execute graph loader with command-line: [%s]", commandString));

		Executor executor = new DefaultExecutor();
		executor.setStreamHandler(new PumpStreamHandler(System.out, System.err));
		executor.setExitValue(0);

		return executor.execute(commandLine);
	}

	public int unload(String loadedInputPath) throws Exception {
		String unloaderDir = platformConfig.getUnloaderPath();
		commandLine = new CommandLine(Paths.get(unloaderDir).toFile());

		commandLine.addArgument("--graph-name");
		commandLine.addArgument(formattedGraph.getName());

		commandLine.addArgument("--output-path");
		commandLine.addArgument(loadedInputPath);

		String commandString = StringUtils.toString(commandLine.toStrings(), " ");
		LOG.info(String.format("Execute graph unloader with command-line: [%s]", commandString));

		Executor executor = new DefaultExecutor();
		executor.setStreamHandler(new PumpStreamHandler(System.out, System.err));
		executor.setExitValue(0);

		return executor.execute(commandLine);
	}

}


text:
package com.twitter.scalding

object LineNumber {
  /**
   * depth 0 means the StackTraceElement for the caller
   * of this method (skipping getCurrent and the Thread.currentThread
   */
  def getCurrent(depth: Int): StackTraceElement =
    getCurrent(depth, Thread.currentThread().getStackTrace)

  private[this] def getCurrent(depth: Int, stack: Seq[StackTraceElement]): StackTraceElement =
    stack(depth + 2)

  def ignorePath(classPrefix: String): Option[StackTraceElement] =
    ignorePath(classPrefix, Thread.currentThread().getStackTrace)

  private[this] def ignorePath(classPrefix: String, stack: Seq[StackTraceElement]): Option[StackTraceElement] =
    stack.drop(2)
      .dropWhile(_.getClassName.startsWith(classPrefix))
      .headOption

  /*
   * If you use this method, it will try to give you the non-scalding
   * caller of the current method. It does this by ignoring all callers
   * in com.twitter.scalding.* unless the caller is a Job (to make testing
   * easier). Otherwise it just gets the most direct
   * caller for methods that have all the callers in the scalding package
   */
  def tryNonScaldingCaller: StackTraceElement = {
    /* depth = 1:
     * depth 0 => tryNonScaldingCaller
     * depth 1 => caller of this method
     */
    val stack = Thread.currentThread().getStackTrace
    val scaldingPrefix = "com.twitter.scalding."
    val nonScalding = ignorePath(scaldingPrefix, stack)
    val jobClass = classOf[com.twitter.scalding.Job]

    // there is no .headOption on Iterator. WTF?
    def headOption[T](it: Iterator[T]): Option[T] =
      if (it.hasNext) Some(it.next)
      else None

    val scaldingJobCaller = headOption(stack
      .iterator
      .filter { se => se.getClassName.startsWith(scaldingPrefix) }
      .filter { se =>
        val cls = Class.forName(se.getClassName)
        jobClass.isAssignableFrom(cls)
      })

    val directCaller = getCurrent(1, stack)

    scaldingJobCaller
      .orElse(nonScalding)
      .getOrElse(directCaller)
  }
}


text:
.PHONY: all clean cleanall
dep_files = tenth.cls thaicaptions.sty thaifont-setup.sty
en_pdfs = tenth_en_oneside.pdf tenth_en_twoside.pdf
th_pdfs = tenth_th_oneside.pdf tenth_th_twoside.pdf
pdfs = $(en_pdfs) $(th_pdfs)

all: $(en_pdfs) $(th_pdfs)

$(en_pdfs): %.pdf: %.tex shared_en.tex $(dep_files)
	latexmk -pdf -interaction=nonstopmode $<

$(th_pdfs): %.pdf: %.tex shared_th.tex $(dep_files)
	latexmk -pdf -interaction=nonstopmode $<

shared_th.tex: shared_th.pre.tex
	swath -f latex -u u,u < $< > $@

clean:
	latexmk -c
	rm -f $(th_texs) *.synctex.gz

cleanall: clean
	rm -f $(pdfs)


text:
package com.innovaee.eorder.web.action;

import com.innovaee.eorder.module.vo.RoleLinkVo;
import com.opensymphony.xwork2.ActionSupport;

import java.util.ArrayList;
import java.util.List;

/**
 * @Title: BaseAction
 * @Description: Action基类
 *
 * @version V1.0
 */
public class BaseAction extends ActionSupport {

    /** 对象序列化ID */
    private static final long serialVersionUID = 6286143366540227001L;

    /** 菜单列表 */
    protected List<RoleLinkVo> menulist = new ArrayList<RoleLinkVo>();

    /** 登录用户名 */
    private String loginName;

    /** 操作消息 */
    private String message;

    public String getLoginName() {
        return loginName;
    }

    public void setLoginName(String loginName) {
        this.loginName = loginName;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public List<RoleLinkVo> getMenulist() {
        return menulist;
    }

    public void setMenulist(List<RoleLinkVo> menulist) {
        this.menulist = menulist;
    }

}


text:
using System;
using System.Collections.Concurrent;
using System.Linq;
using BrailleIO.Interface;

namespace BrailleIO
{
    ///
    /// Basic abstract <see cref="IBrailleIOAdapterManager"/> implementation to handle all generic adapters.
    ///
    /// <seealso cref="BrailleIO.Interface.IBrailleIOAdapterManager" />
    abstract public class AbstractBrailleIOAdapterManagerBase : IBrailleIOAdapterManager, IDisposable
    {
        IBrailleIOAdapter _activeAdapter;
        /// initialize all supported devices and wait for connection.
        /// <value>The active adapter.</value>
        public IBrailleIOAdapter ActiveAdapter
        {
            get { return _activeAdapter; }
            set { AddAdapter(value); _activeAdapter = value; fire_ActiveAdapterChanged(); }
        }
        private readonly Object _adapterLock = new Object();
        private readonly ConcurrentBag<IBrailleIOAdapter> _adapters = new ConcurrentBag<IBrailleIOAdapter>();
        ///
        /// Gets the adapters.
        ///
        /// <value>
        /// The adapters.
        /// </value>
        protected ConcurrentBag<IBrailleIOAdapter> Adapters
        {
            get
            {
                lock (_adapterLock) { return _adapters; }
            }
        }

        ///
        /// The BrailleIOMediator
        ///
        protected BrailleIOMediator io;
        ///
        /// Initializes a new instance of the <see cref="AbstractBrailleIOAdapterManagerBase"/> class.
        ///
        public AbstractBrailleIOAdapterManagerBase()
        { }

        ///
        /// Initializes a new instance of the <see cref="AbstractBrailleIOAdapterManagerBase"/> class.
        ///
        /// <param name="io">The <see cref="BrailleIOMediator"/> this manager is related to.</param>
        public AbstractBrailleIOAdapterManagerBase(ref BrailleIOMediator io)
            : this()
        {
            this.io = io;
        }

        ///
        /// Adds a new adapter to the manager.
        ///
        /// <param name="adapter">The adapter.</param>
        /// <returns>True if the adapter could be added to the manager otherwise false. It also returns false if the adapter is already added.</returns>
        public virtual bool AddAdapter(IBrailleIOAdapter adapter)
        {
            if (Adapters.Contains(adapter)) return false;
            try
            {
                Adapters.Add(adapter);
                fire_NewAdapterRegistered(adapter);
            }
            catch { return false; }
            return true;
        }

        ///
        /// Removes a new adapter from the manager.
        ///
        /// <param name="adapter">The adapter.</param>
        /// <returns>True if the adapter could be removed from the manager otherwise false.</returns>
        public virtual bool RemoveAdapter(IBrailleIOAdapter adapter)
        {
            if (Adapters.Contains(adapter))
            {
                try
                {
                    Adapters.TryTake(out adapter);
                    fire_AdapterRemoved(adapter);
                    return true;
                }
                catch { }
            }
            return false;
        }

        ///
        /// Gets the adapters.
        ///
        /// <returns>array of currently registered adapters (hardware abstraction)</returns>
        public virtual IBrailleIOAdapter[] GetAdapters()
        {
            return Adapters.ToArray();
        }

        /// Synchronizes the specified matrix.
        /// <param name="matrix">The matrix.</param>
        /// <returns>
        ///   <c>true</c> if the matrix could been displayed successfully on the output device</returns>
        public bool Synchronize(bool[,] matrix)
        {
            bool success = true;
            if (ActiveAdapter != null)
            {
                System.Threading.Tasks.Task T = new System.Threading.Tasks.Task(() =>
                {
                    ActiveAdapter.Synchronize(matrix);
                });
                T.Start();
            }

            if (Adapters.Count > 0)
            {
                if (Adapters.Count > 1)
                {
                    System.Threading.Tasks.Parallel.ForEach<IBrailleIOAdapter>(Adapters, (item) =>
                    {
                        try
                        {
                            if (item != null && item != ActiveAdapter && item is AbstractBrailleIOAdapterBase && ((AbstractBrailleIOAdapterBase)item).Synch)
                                item.Synchronize(matrix);
                        }
                        catch { success = false; }
                    });
                }
                else if (ActiveAdapter == null)
                {
                    System.Threading.Tasks.Task T2 = new System.Threading.Tasks.Task(() =>
                    {
                        try
                        {
                            IBrailleIOAdapter item = null;
                            item = Adapters.ElementAt(0);

                            if (item != null && item != ActiveAdapter && item is AbstractBrailleIOAdapterBase && ((AbstractBrailleIOAdapterBase)item).Synch)
                                item.Synchronize(matrix);
                        }
                        catch { success = false; }
                    });
                    T2.Start();
                }
            }
            return success;
        }

        ///
        /// Occurs when a new adapter was registered.
        ///
        public event EventHandler<IBrailleIOAdapterEventArgs> NewAdapterRegistered;
        ///
        /// Occurs when an adapter was removed.
        ///
        public event EventHandler<IBrailleIOAdapterEventArgs> AdapterRemoved;
        ///
        /// Occurs when the active adapter changed.
        ///
        public event EventHandler<IBrailleIOAdapterEventArgs> ActiveAdapterChanged;

        ///
        /// Fires the new adapter registered event.
        ///
        /// <param name="adapter">The adapter.</param>
        protected virtual void fire_NewAdapterRegistered(IBrailleIOAdapter adapter)
        {
            if (NewAdapterRegistered != null)
            {
                try
                {
                    NewAdapterRegistered.Invoke(this, new IBrailleIOAdapterEventArgs(adapter));
                }
                catch (Exception ex) { System.Diagnostics.Debug.WriteLine("ERROR in AbstractBrailleIOAdapterManagerBase fire_NewAdapterRegistered:\r\n" + ex); }
            }
        }

        ///
        /// Fires the adapter removed event.
        ///
        /// <param name="adapter">The adapter.</param>
        protected virtual void fire_AdapterRemoved(IBrailleIOAdapter adapter)
        {
            if (AdapterRemoved != null)
            {
                try
                {
                    AdapterRemoved.Invoke(this, new IBrailleIOAdapterEventArgs(adapter));
                }
                catch (Exception ex) { System.Diagnostics.Debug.WriteLine("ERROR in AbstractBrailleIOAdapterManagerBase fire_AdapterRemoved:\r\n" + ex); }
            }
        }

        ///
        /// Fires the active adapter changed event.
        ///
        protected virtual void fire_ActiveAdapterChanged()
        {
            if (ActiveAdapterChanged != null)
            {
                try
                {
                    ActiveAdapterChanged.Invoke(this, new IBrailleIOAdapterEventArgs(ActiveAdapter));
                }
                catch (Exception ex) { System.Diagnostics.Debug.WriteLine("ERROR in AbstractBrailleIOAdapterManagerBase fire_ActiveAdapterChanged:\r\n" + ex); }
            }
        }

        #region IDisposable

        ///
        /// Disposes this element and disconnects and disposes all registered adapters.
        ///
        public void Dispose()
        {
            try
            {
                foreach (var item in Adapters)
                {
                    try
                    {
                        if (item != null)
                        {
                            item.Disconnect();
                            if (item is IDisposable) ((IDisposable)item).Dispose();
                        }
                    }
                    catch { }
                }
            }
            catch { }
        }

        #endregion
    }

    ///
    /// Basic generic adapter manager for handling hardware or software adapters as in- and output for the <see cref="BrailleIOMediator"/>
    ///
    /// <seealso cref="BrailleIO.AbstractBrailleIOAdapterManagerBase" />
    public class BasicBrailleIOAdapterManager : AbstractBrailleIOAdapterManagerBase { }
}


text:
"""Module containing utility functions for internationalization."""

from django.conf import settings

def get_available_languages():
    """Return the list of language codes defined in django settings."""
    return [code for code, name in settings.LANGUAGES]

def get_default_language():
    """Return the language code of the default language."""
    return settings.LANGUAGE_CODE


text:
<!-- Javascript Start -->

<!-- jQuery -->
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>

<!-- Plugin JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>

<!-- Custom Theme JavaScript -->
<!--* Start Bootstrap - Grayscale Bootstrap Theme (http://startbootstrap.com)
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.-->
<script>
$(document).on('click',function(){
$('.collapse').collapse('hide');
})
</script>
<script type="text/javascript">
$(document).ready(function() {
  for (i = {{site.startyear}}; i <= {{ site.time | date: "%Y" }}; i++) {
     $(document).on("click","#archive_year_"+i,function() {
         $(this).parent().children("li").toggle();
         togglePointer($(this));
     });
     $(document).on("click",".archive_month_"+i,function() {
         $(this).parent().children("li").toggle();
         togglePointer($(this));
     });
  }
  function togglePointer(elem) {
     if (elem.text().indexOf('►') != -1) {
        elem.text(elem.text().replace('►','▼'));
     } else {
        elem.text(elem.text().replace('▼','►'));
     }
  }
  if ($(window).width() < 768) {
     $('#index_leftbar').css("width", "100%");
     $('#index_right_t_bar').hide();
     $('#index_right_b_bar').hide();
  }
});
</script>
<script>
function toggleNavCollapse(){50<$(".navbar").offset().top?$(".navbar-fixed-top").addClass("top-nav-collapse"):$(".navbar-fixed-top").removeClass("top-nav-collapse");}
$(document).ready(toggleNavCollapse);
$(window).scroll(toggleNavCollapse);$(function(){$("a.page-scroll").bind("click",function(b){var a=$(this);$("html, body").stop().animate({scrollTop:$(a.attr("href")).offset().top-50},1500,"easeInOutExpo",function(){a.blur()});b.preventDefault()})});$(".navbar-collapse ul li a").click(function(){$(".navbar-toggle:visible").click()});
</script>

{% if page.section-type == "index" %}

  <!-- Collapse navbar when navbar-brand is clicked -->

  <script>
  $(function(){$(".navbar-brand").click(function(){$(".collapse.in")&&$(".collapse.in").animate({height:"1px"},500,function(){$(".collapse.in").removeClass("in")})})});
  </script>

{% endif %}

{% if site.syntax-highlight and page.section-type == "post" %}

  <!-- Syntax highlight in post pages-->

  <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.2/highlight.min.js"></script>
  <script>hljs.initHighlightingOnLoad();</script>

{% endif %}

{% if jekyll.environment == "production" %}
  {% if site.google-tracking-id %}

  <!-- Google Tracking Id Start -->

  <script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
    ga('create', '{{ site.google-tracking-id }}', 'auto');
    ga('send', 'pageview');
  </script>

  <!-- Google Tracking Id End -->

  {% endif %}
{% endif %}

{% if page.section-type == "latest-post" %}

  <!-- Disqus -->
  <script type="text/javascript">
  var disqus_shortname = 'stalkcalvin'; // required: replace example with your forum shortname
  (function() {
      var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
      dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
      (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
  })();
  </script>

  <!-- Comments Counter Start -->

  <script type="text/javascript">
  /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
  var disqus_shortname = 'stalkcalvin'; // required: replace example with your forum shortname

  /* * * DON'T EDIT BELOW THIS LINE * * */
  (function () {
  var s = document.createElement('script'); s.async = true;
  s.type = 'text/javascript';
  s.src = '//' + disqus_shortname + '.disqus.com/count.js';
  (document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
  }());
  </script>

  <!-- Comments Counter End -->

{% endif %}

{% if page.section-type == "latest-post" %}

  <!-- Share buttons Start -->

  <script src="{{site.baseurl}}/js/rrssb.min.js"></script>

  <!-- Share buttons End -->

{% endif %}

{% if site.dynamic-typing and page.section-type == "index" %}

  <!-- Dynamic Typing Start -->

  <script type="text/javascript" src="{{site.baseurl}}/js/typed.min.js"></script>
  <script type="text/javascript">

  var myQuotes =  new Array();
  {% for line in site.lines %}
    myQuotes.push("{{ line.text }}");
  {% endfor %}

  function shuffle(array) {
    var currentIndex = array.length, temporaryValue, randomIndex ;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

      // Pick a remaining element...
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;

      // And swap it with the current element.
      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
    }

    return array;
  }

  {% if site.shuffle %}
    shuffle(myQuotes)
  {% endif %}

    $(".intro-text").typed({
      strings: myQuotes,
      typeSpeed: {{ site.type-speed }},
      backDelay: {{ site.delete-delay }},
      startDelay: {{ site.start-delay }},
      loop: {{ site..loop }},
      loopCount: {{ site.loop-count }},
      cursorChar: "|"
    });
  </script>

  <!-- Dynamic Typing End  -->

{% endif %}

<script>
function addTohistory() {
  if (!window.location.host.startsWith("127.0.0.1")) {
    history.pushState({}, '{{page.title}}', '{{site.url}}{{site.baseurl}}{{page.url}}');
  }
}
</script>

<!-- Gesture Navigation / Swipe Instruction Start -->
{% if site.enable-gesture-navigation %}

  {% if page.section-type == "post" %}

    <!-- Post Gesture Navigation Start -->

    <script type="text/javascript" src="{{site.baseurl}}/js/hammer.min.js"></script>

    <script>
      var post = document.getElementById('post');

      new Hammer(post).on('swipeleft', function(event) {
        addTohistory();
        {% if site.baseurl == "" and page.previous == nil %}
          document.location.replace("/");
        {% else %}
          document.location.replace("{{site.baseurl}}{{page.previous.url}}");
        {% endif %}
      });

      new Hammer(post).on('swiperight', function(event) {
        addTohistory();
        {% if site.baseurl == "" and page.next == nil %}
          document.location.replace("/");
        {% else %}
          document.location.replace("{{site.baseurl}}{{page.next.url}}");
        {% endif %}
      });
    </script>

    <!-- Post Gesture Navigation Start -->

  {% endif %}

  {% if page.section-type == "blog" %}

    <!-- Blog Gesture Navigation Start -->

    <script type="text/javascript" src="{{site.baseurl}}/js/hammer.min.js"></script>

    <script>
      var page = document.getElementById('page');

      new Hammer(page).on('swipeleft', function(event) {
        addTohistory();
        {% if site.baseurl == "" and paginator.next_page_path == nil %}
          document.location.replace("/");
        {% else %}
          document.location.replace("{{site.baseurl}}{{paginator.next_page_path}}");
        {% endif %}
      });
      new Hammer(page).on('swiperight', function(event) {
        addTohistory();
        {% if site.baseurl == "" and paginator.previous_page_path == nil %}
          document.location.replace("/");
        {% else %}
          document.location.replace("{{site.baseurl}}{{paginator.previous_page_path}}");
        {% endif %}
      });
    </script>

    <!-- Blog Gesture Navigation Start -->

  {% endif %}

  {% if page.section-type == "blog" %}

    <!-- Swipe Instructions for Blog Start -->

    <script>
      $(document).ready(function(){
        if(!localStorage.getItem('blog-swipeshowed')){
          $("#swipe-instruction").fadeIn();
          $("#swipe-instruction .close-swipe-instruction").click(function(){
            $("#swipe-instruction").fadeOut();
          });
          localStorage.setItem('blog-swipeshowed', true);
        }
      });
    </script>

    <!-- Swipe Instructions for Blog End -->

  {% endif %}

  {% if page.section-type == "post" %}

    <!-- Swipe Instructions for Post Start -->

    <script>
      $(document).ready(function(){
        if(!localStorage.getItem('post-swipeshowed')){
          $("#swipe-instruction").fadeIn();
          $("#swipe-instruction .close-swipe-instruction").click(function(){
            $("#swipe-instruction").fadeOut();
          });
          localStorage.setItem('post-swipeshowed', true);
        }
      });
    </script>

    <!-- Swipe Instructions for Post End -->

  {% endif %}

<!-- Gesture Navigation / Swipe Instruction End -->

{% endif %}

<!-- Javascript End -->


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Sphaeria gypsophilae Lasch

### Remarks
null


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>LCOV - coverage.info - src/ssltunnel.c</title>
  <link rel="stylesheet" type="text/css" href="../gcov.css">

LCOV - code coverage report

            Current view:
            top level - src - ssltunnel.c (source / functions)

            Hit
            Total
            Coverage

            Test:
            coverage.info

            Lines:
            69
            75
            92.0 %

            Date:
            2015-12-25 11:14:27

            Functions:
            5
            5
            100.0 %

          Line data    Source code

       1             :
      20             :
      21             : /*** Setup a SSL tunnel over a HTTP proxy, according to RFC 2817. ***/
      22             :
      23             : #include <apr_pools.h>
      24             : #include <apr_strings.h>
      25             :
      26             : #include "serf.h"
      27             : #include "serf_private.h"
      28             :
      29             :
      30             : /* Structure passed around as baton for the CONNECT request and respone. */
      31             : typedef struct req_ctx_t {
      32             :     apr_pool_t *pool;
      33             :     const char *uri;
      34             : } req_ctx_t;
      35             :
      36             : /* forward declaration. */
      37             : static apr_status_t setup_request(serf_request_t *request,
      38             :                                   void *setup_baton,
      39             :                                   serf_bucket_t **req_bkt,
      40             :                                   serf_response_acceptor_t *acceptor,
      41             :                                   void **acceptor_baton,
      42             :                                   serf_response_handler_t *handler,
      43             :                                   void **handler_baton,
      44             :                                   apr_pool_t *pool);
      45             :
      46             : static serf_bucket_t* accept_response(serf_request_t *request,
      47             :                                       serf_bucket_t *stream,
      48             :                                       void *acceptor_baton,
      49             :                                       apr_pool_t *pool)
      50             : {
      51             :     serf_bucket_t *c;
      52             :     serf_bucket_alloc_t *bkt_alloc;
      53             : #if 0
      54             :     req_ctx_t *ctx = acceptor_baton;
      55             : #endif
      56             :
      57             :     /* get the per-request bucket allocator */
      58          17 :     bkt_alloc = serf_request_get_alloc(request);
      59             :
      60             :     /* Create a barrier so the response doesn't eat us! */
      61          17 :     c = serf_bucket_barrier_create(stream, bkt_alloc);
      62             :
      63          17 :     return serf_bucket_response_create(c, bkt_alloc);
      64             : }
      65             :
      66             : /* If a 200 OK was received for the CONNECT request, consider the connection
      67             :    as ready for use. */
      68             : static apr_status_t handle_response(serf_request_t *request,
      69             :                                     serf_bucket_t *response,
      70             :                                     void *handler_baton,
      71             :                                     apr_pool_t *pool)
      72             : {
      73             :     apr_status_t status;
      74             :     serf_status_line sl;
      75          10 :     req_ctx_t *ctx = handler_baton;
      76          10 :     serf_connection_t *conn = request->conn;
      77             :
      78             :     /* CONNECT request was cancelled. Assuming that this is during connection
      79             :        reset, we can safely discard the request as a new one will be created
      80             :        when setting up the next connection. */
      81          10 :     if (!response)
      82           0 :         return APR_SUCCESS;
      83             :
      84          10 :     status = serf_bucket_response_status(response, &sl);
      85          10 :     if (SERF_BUCKET_READ_ERROR(status)) {
      86           0 :         return status;
      87             :     }
      88          10 :     if (!sl.version && (APR_STATUS_IS_EOF(status) ||
      89           0 :                       APR_STATUS_IS_EAGAIN(status)))
      90             :     {
      91           0 :         return status;
      92             :     }
      93             :
      94          10 :     status = serf_bucket_response_wait_for_headers(response);
      95          10 :     if (status && !APR_STATUS_IS_EOF(status)) {
      96           0 :         return status;
      97             :     }
      98             :
      99             :     /* RFC 2817:  Any successful (2xx) response to a CONNECT request indicates
     100             :        that the proxy has established a connection to the requested host and
     101             :        port, and has switched to tunneling the current connection to that server
     102             :        connection.
     103             :     */
     104          20 :     if (sl.code >= 200 && sl.code < 300) {
     105             :         serf_bucket_t *hdrs;
     106             :         const char *val;
     107             :
     108             :
     109             :
     110             :         /* Body is supposed to be empty. */
     111           8 :         apr_pool_destroy(ctx->pool);
     112             :
     113             :         /* If there was outgoing data waiting, we can't use it
     114             :            any more. It's lifetime is limited by ostream_head
     115             :            ... (There shouldn't be any, as we disabled pipelining) */
     116           8 :         conn->pump.vec_len = 0;
     117             :
     118           8 :         conn->state = SERF_CONN_CONNECTED;
     119             :
     120             :         /* Destroy the unencrypted head */
     121           8 :         serf_bucket_destroy(conn->pump.ostream_head);
     122           8 :         conn->pump.ostream_head = NULL;
     123             :         /* And the unencrypted stream */
     124           8 :         serf_bucket_destroy(conn->pump.stream);
     125           8 :         conn->pump.stream = NULL;
     126             :
     127             :         /* New ones will be created in the normal setup code */
     128           8 :         ctx = NULL;
     129             :
     130           8 :         serf__log(LOGLVL_INFO, LOGCOMP_CONN, __FILE__, conn->config,
     131             :                   "successfully set up ssl tunnel.\n");
     132             :
     133             :         /* Fix for issue #123: ignore the "Connection: close" header here,
     134             :            leaving the header in place would make the serf's main context
     135             :            loop close this connection immediately after reading the 200 OK
     136             :            response. */
     137             :
     138           8 :         hdrs = serf_bucket_response_get_headers(response);
     139           8 :         val = serf_bucket_headers_get(hdrs, "Connection");
     140           9 :         if (val && strcasecmp("close", val) == 0) {
     141           1 :             serf__log(LOGLVL_DEBUG, LOGCOMP_CONN, __FILE__, conn->config,
     142             :                       "Ignore Connection: close header on this reponse, don't "
     143             :                       "close the connection now that the tunnel is set up.\n");
     144           1 :             serf__bucket_headers_remove(hdrs, "Connection");
     145           1 :         }
     146             :
     147           8 :         status = serf_connection__perform_setup(conn);
     148             :
     149           8 :         if (status)
     150           0 :             return SERF_BUCKET_READ_ERROR(status) ? status : APR_EGENERAL;
     151             :
     152           8 :         return APR_EOF;
     153             :     }
     154             :
     155             :     /* Authentication failure and 2xx Ok are handled at this point,
     156             :        the rest are errors. */
     157           2 :     return SERF_ERROR_SSLTUNNEL_SETUP_FAILED;
     158          10 : }
     159             :
     160             : /* Prepare the CONNECT request. */
     161             : static apr_status_t setup_request(serf_request_t *request,
     162             :                                   void *setup_baton,
     163             :                                   serf_bucket_t **req_bkt,
     164             :                                   serf_response_acceptor_t *acceptor,
     165             :                                   void **acceptor_baton,
     166             :                                   serf_response_handler_t *handler,
     167             :                                   void **handler_baton,
     168             :                                   apr_pool_t *pool)
     169             : {
     170          17 :     req_ctx_t *ctx = setup_baton;
     171             :     serf_bucket_t *hdrs_bkt;
     172             :
     173          34 :     *req_bkt = serf_bucket_request_create("CONNECT", ctx->uri, NULL,
     174          17 :                                           serf_request_get_alloc(request));
     175             :
     176          17 :     hdrs_bkt = serf_bucket_request_get_headers(*req_bkt);
     177          17 :     serf_bucket_headers_setn(hdrs_bkt, "Host", ctx->uri);
     178             :
     179             :     /* If proxy authn is required, then set it up.  */
     180          17 :     serf__auth_setup_request(PROXY, request, "CONNECT", ctx->uri, hdrs_bkt);
     181             :
     182          17 :     *acceptor = accept_response;
     183          17 :     *acceptor_baton = ctx;
     184          17 :     *handler = handle_response;
     185          17 :     *handler_baton = ctx;
     186             :
     187          17 :     return APR_SUCCESS;
     188             : }
     189             :
     190             : static apr_status_t ssltunnel_ostream_destroyed(void *baton,
     191             :                                                 apr_uint64_t bytes_read)
     192             : {
     193          12 :     serf_connection_t *conn = baton;
     194             :
     195          12 :     if (conn->state == SERF_CONN_SETUP_SSLTUNNEL) {
     196             :         /* Connection is destroyed while not connected.
     197             :            Destroy tail to avoid leaking memory */
     198           4 :         serf_bucket_destroy(conn->pump.ostream_tail);
     199           4 :         conn->pump.ostream_tail = NULL;
     200           4 :     }
     201          12 :     return APR_SUCCESS;
     202             : }
     203             :
     204             : /* SSL tunnel is needed, push a CONNECT request on the connection. */
     205             : apr_status_t serf__ssltunnel_connect(serf_connection_t *conn)
     206             : {
     207             :     req_ctx_t *ctx;
     208             :     apr_pool_t *ssltunnel_pool;
     209             :     serf_bucket_t *stream, *ostream;
     210             :
     211          12 :     apr_pool_create(&ssltunnel_pool, conn->pool);
     212             :
     213          12 :     ctx = apr_palloc(ssltunnel_pool, sizeof(*ctx));
     214          12 :     ctx->pool = ssltunnel_pool;
     215          24 :     ctx->uri = apr_psprintf(ctx->pool, "%s:%d", conn->host_info.hostname,
     216          12 :                             conn->host_info.port);
     217             :
     218             :     /* We want to setup a plain http request to be sent before the
     219             :        actual streams are connected... */
     220          12 :     serf_pump__prepare_setup(&conn->pump);
     221             :
     222             :     /* Ok, we now have a head and a tail bucket. The tail has pump
     223             :        events attached to it so we don't want to destroy that one
     224             :        later. Let's create a barrier around it and manage the lifetime
     225             :        ourself. */
     226             :
     227          24 :     ostream = serf_bucket_barrier_create(conn->pump.ostream_tail,
     228          12 :                                          conn->allocator);
     229             :
     230          24 :     ostream = serf__bucket_event_create(ostream,
     231          12 :                                         conn, NULL, NULL,
     232             :                                         ssltunnel_ostream_destroyed,
     233          12 :                                         conn->allocator);
     234             :
     235          24 :     stream = serf_context_bucket_socket_create(conn->ctx,
     236          12 :                                                conn->skt,
     237          12 :                                                conn->allocator);
     238             :
     239          12 :     serf_pump__complete_setup(&conn->pump, stream, ostream);
     240             :
     241             :
     242          24 :     serf__ssltunnel_request_create(conn,
     243             :                                    setup_request,
     244          12 :                                    ctx);
     245             :
     246          12 :     conn->state = SERF_CONN_SETUP_SSLTUNNEL;
     247          12 :     serf__log(LOGLVL_DEBUG, LOGCOMP_CONN, __FILE__, conn->config,
     248             :               "setting up ssl tunnel on connection.\n");
     249             :
     250          12 :     return APR_SUCCESS;
     251             : }

Generated by: LCOV version 1.12


text:
namespace chromeos {

namespace {
// List of pages, which along with their subpages are considered whitelisted in
// kiosk mode.
KioskSettingsNavigationThrottle::SettingsPage kSettingsPages[] = {
    {"chrome://os-settings/manageAccessibility", true},
    {"chrome-extension://mndnfokpggljbaajbnioimlmbfngpief/chromevox/background/"
     "options.html",
     false},
    {"chrome-extension://klbcgckkldhdhonijdbnhhaiedfkllef/", true},
    {"chrome-extension://gjjabgpgjpampikjhjpfhneeoapjbjaf/", true},
    {"chrome-extension://dakbfdmgjiabojdgbiljlhgjbokobjpg/", true}};

// This list is used in tests to replace default |kSettingsPages| items.
std::vector<KioskSettingsNavigationThrottle::SettingsPage>*
    g_test_settings_pages = nullptr;

// WebContents that are marked with this UserData key should be restricted.
const void* const kRestrictedSettingsWindowKey = &kRestrictedSettingsWindowKey;

bool CheckUrlMatchSettingsPage(
    const KioskSettingsNavigationThrottle::SettingsPage& page,
    const std::string& url) {
  return (page.allow_subpages &&
          base::StartsWith(url,
                           page.url ? std::string(page.url) : std::string(),
                           base::CompareCase::SENSITIVE)) ||
         (!page.allow_subpages && url == page.url);
}

}  // namespace

// static
bool KioskSettingsNavigationThrottle::IsSettingsPage(const std::string& url) {
  if (g_test_settings_pages) {
    for (auto& page : *g_test_settings_pages) {
      if (CheckUrlMatchSettingsPage(page, url))
        return true;
    }
    return false;
  }
  for (auto& page : kSettingsPages) {
    if (CheckUrlMatchSettingsPage(page, url))
      return true;
  }
  return false;
}

// static
void KioskSettingsNavigationThrottle::SetSettingPagesForTesting(
    std::vector<SettingsPage>* pages) {
  g_test_settings_pages = pages;
}

// static
std::unique_ptr<content::NavigationThrottle>
KioskSettingsNavigationThrottle::MaybeCreateThrottleFor(
    content::NavigationHandle* handle) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  // Kiosk check.
  if (!chrome::IsRunningInForcedAppMode())
    return nullptr;
  // If the web contents were previously marked as restricted, attach a throttle
  // to it.
  if (handle->GetWebContents()->GetUserData(kRestrictedSettingsWindowKey))
    return std::make_unique<KioskSettingsNavigationThrottle>(handle);
  // Otherwise, check whether the navigated to url is a settings page, and if
  // so, mark it.
  if (IsSettingsPage(handle->GetURL().spec())) {
    handle->GetWebContents()->SetUserData(
        kRestrictedSettingsWindowKey,
        std::make_unique<content::WebContents::Data>());
    return std::make_unique<KioskSettingsNavigationThrottle>(handle);
  }
  return nullptr;
}

KioskSettingsNavigationThrottle::KioskSettingsNavigationThrottle(
    content::NavigationHandle* handle)
    : content::NavigationThrottle(handle) {}

KioskSettingsNavigationThrottle::ThrottleCheckResult
KioskSettingsNavigationThrottle::WillStartRequest() {
  return WillStartOrRedirectRequest();
}

KioskSettingsNavigationThrottle::ThrottleCheckResult
KioskSettingsNavigationThrottle::WillRedirectRequest() {
  return WillStartOrRedirectRequest();
}

const char* KioskSettingsNavigationThrottle::GetNameForLogging() {
  return "KioskSettingsNavigationThrottle";
}

KioskSettingsNavigationThrottle::ThrottleCheckResult
KioskSettingsNavigationThrottle::WillStartOrRedirectRequest() {
  return IsSettingsPage(navigation_handle()->GetURL().spec()) ? PROCEED
                                                              : CANCEL;
}

}  // namespace chromeos


text:
<form name="editForm" role="form" novalidate (ngSubmit)="save()" #editForm="ngForm">

Create or edit a Testeur

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true"
                (click)="clear()">×</button>

        <jhi-alert-error></jhi-alert-error>

            Identifiant
            <input type="text" class="form-control" name="identifiant" id="field_identifiant"
                [(ngModel)]="testeur.identifiant" required />

                   This field is required.

            Nom
            <input type="text" class="form-control" name="nom" id="field_nom"
                [(ngModel)]="testeur.nom" required />

                   This field is required.

            Prenom
            <input type="text" class="form-control" name="prenom" id="field_prenom"
                [(ngModel)]="testeur.prenom" required />

                   This field is required.

            Typetest
            <select class="form-control" id="field_typetest" name="typetest" [(ngModel)]="testeur.typetest"  required>
                <option [ngValue]="typeTestOption.id === testeur.typetest?.id ? testeur.typetest : typeTestOption" *ngFor="let typeTestOption of typetests; trackBy: trackTypeTestById">{{typeTestOption.code}}</option>
            </select>

                This field is required.

        <button type="button" id="testeur-dialog-component-cancel" class="btn btn-default" data-dismiss="modal" (click)="clear()">
             Cancel
        </button>
        <button type="submit" id="testeur-dialog-component-save" [disabled]="editForm.form.invalid || isSaving" class="btn btn-primary">
             Save
        </button>

</form>