text:
import java.util.Scanner;

public class App {

	public static void main(String[] args) {
        System.out.println("Type a phrase: ");
        Scanner scanner=new Scanner(System.in);
        String phrase=scanner.nextLine();
        int wordCount = countWords(phrase);
        System.out.println("This phrase has " + wordCount + " words");
        scanner.close();
	}

    private static String removeStrangeChars(String phrase)
    {
        String newStr = phrase.replace('¿', ' ');
        newStr = newStr.replace('?', ' ');
        newStr = newStr.replace('!', ' ');
        newStr = newStr.replace('¡', ' ');
        newStr = newStr.replace('.', ' ');
        newStr = newStr.replace(',', ' ');
        newStr = newStr.replace(':', ' ');
        newStr = newStr.replace(';', ' ');
        newStr = newStr.replace('(', ' ');
        newStr = newStr.replace(')', ' ');
        newStr = newStr.replace('[', ' ');
        newStr = newStr.replace(']', ' ');
        newStr = newStr.replace('{', ' ');
        newStr = newStr.replace('}', ' ');
        newStr = newStr.replace('"', ' ');
        newStr = newStr.replace('\'', ' ');
        newStr = newStr.replace('-', ' ');
        newStr = newStr.replace('=', ' ');
        newStr = newStr.replace('\\', ' ');
        return newStr;
    }

    private static String removeExtraSpaces(String phrase)
    {
        while (phrase.indexOf("  ") != -1)
        {
            phrase = phrase.replace("  ", " ");
        }
        phrase = phrase.trim();
        phrase = phrase + " ";
        return phrase;
    }

    private static int countSpaces(String phrase)
    {
        int wordCount = 0;
        for (int i = 0; i < phrase.length(); i++)
        {
            if (phrase.charAt(i) == ' ')
            {
                wordCount++;
            }
        }
        return wordCount;
    }

    private static int countWords(String phrase)
    {
        phrase = removeStrangeChars(phrase);
        phrase = removeExtraSpaces(phrase);
        int wordCount = countSpaces(phrase);
        return wordCount;
    }

}

redpajama_set_name: RedPajamaGithub


text:
local _M = {}
_M.__index = _M

-- patter that match all utf8 character(use the first character and utf8-tail define in RFC3629)
local pattern = '[%z\1-\127\194-\244][\128-\191]*'

function _M.new(txt)
    local self = {
	wrds = {}
    }

    for wrd in txt:gmatch('(' .. pattern .. ')') do
	table.insert(self.wrds, wrd)
    end

    return setmetatable(self, _M)
end

--! get the number of words in utf8 string
function _M:length()
    return #self.wrds
end

--! get sub-string from utf8 string
function _M:sub(i, j)
    i = (i>0 and i) or 0
    j = (j and j<=#self.wrds and j) or #self.wrds

    local res = {}
    for idx=i,j do
	table.insert(res, self.wrds[idx])
    end

    return table.concat(res, '')
end

--! get word in given position
function _M:at(i)
    return self.wrds[i]
end

--! word iterator
function _M:word_iter(filter)
    local idx = 0
    return function()
	idx = idx+1
	if idx<=#self.wrds then
	    return self.wrds[idx]
	else
	    return nil
	end
    end
end

return _M


text: module.exports = require('./lib/evcheck');


text:
<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Pagination Class
 *
 * @package		CodeIgniter
 * @link		http://codeigniter.com/user_guide/libraries/pagination.html
 *
 * Modified by CodexWorld.com
 * @Ajax pagination functionality has added with this library.
 * @It will helps to integrate Ajax pagination with loading image in CodeIgniter application.
 * @TutorialLink http://www.codexworld.com/ajax-pagination-in-codeigniter-framework/
 */
class Ajax_pagination{

	var $page           = '';
	var $base_url           = ''; // The page we are linking to
	var $total_rows  		= ''; // Total number of items (database results)
	var $per_page	 		= 10; // Max number of items you want shown per page
	var $num_links			=  2; // Number of "digit" links to show before/after the currently viewed page
	var $cur_page	 		=  0; // The current page being viewed
	var $first_link   		= 'First';
	var $next_link			= '»';
	var $prev_link			= '«';
	var $last_link			= 'Last';
	var $uri_segment		= 3;
	var $full_tag_open		= '
';
	var $full_tag_close		= '
';
	var $first_tag_open		= '';
	var $first_tag_close	= ' ';
	var $last_tag_open		= ' ';
	var $last_tag_close		= '';
	var $cur_tag_open		= ' ';
	var $cur_tag_close		= '';
	var $next_tag_open		= ' ';
	var $next_tag_close		= ' ';
	var $prev_tag_open		= ' ';
	var $prev_tag_close		= '';
	var $num_tag_open		= ' ';
	var $num_tag_close		= '';
	var $target             = '';
    var $anchor_class		= '';
    var $show_count         = true;
    var $link_func          = 'getData';
    var $loading            = '.loading';

	/**
	 * Constructor
	 * @access	public
	 * @param	array	initialization parameters
	 */
	function CI_Pagination($params = array()){
		if (count($params) > 0){
			$this->initialize($params);
		}
		log_message('debug', "Pagination Class Initialized");
	}

	/**
	 * Initialize Preferences
	 * @access	public
	 * @param	array	initialization parameters
	 * @return	void
	 */
	function initialize($params = array()){
		if (count($params) > 0){
			foreach ($params as $key => $val){
				if (isset($this->$key)){
					$this->$key = $val;
				}
			}
		}

		// Apply class tag using anchor_class variable, if set.
		if ($this->anchor_class != ''){
			$this->anchor_class = 'class="' . $this->anchor_class . '" ';
		}
	}

	/**
	 * Generate the pagination links
	 * @access	public
	 * @return	string
	 */
	function create_links(){
		// If our item count or per-page total is zero there is no need to continue.
		if ($this->total_rows == 0 OR $this->per_page == 0){
		   return '';
		}

		// Calculate the total number of pages
		$num_pages = ceil($this->total_rows / $this->per_page);

		// Is there only one page? Hm... nothing more to do here then.
		if ($num_pages == 1){
            $info = 'Showing : ' . $this->total_rows;
			return $info;
		}

		// Determine the current page number.
		$CI =& get_instance();
		if ($this->page != 0){
			$this->cur_page = $this->page;

			// Prep the current page - no funny business!
			$this->cur_page = (int) $this->cur_page;
		}

		$this->num_links = (int)$this->num_links;

		if ($this->num_links < 1){
			show_error('Your number of links must be a positive number.');
		}

		if ( ! is_numeric($this->cur_page)){
			$this->cur_page = 0;
		}

		// Is the page number beyond the result range?
		// If so we show the last page
		if ($this->cur_page > $this->total_rows){
			$this->cur_page = ($num_pages - 1) * $this->per_page;
		}

		$uri_page_number = $this->cur_page;
		$this->cur_page = floor(($this->cur_page/$this->per_page) + 1);

		// Calculate the start and end numbers. These determine
		// which number to start and end the digit links with
		$start = (($this->cur_page - $this->num_links) > 0) ? $this->cur_page - ($this->num_links - 1) : 1;
		$end   = (($this->cur_page + $this->num_links) < $num_pages) ? $this->cur_page + $this->num_links : $num_pages;

		// Add a trailing slash to the base URL if needed
		$this->base_url = rtrim($this->base_url, '/') .'/';

  		// And here we go...
		$output = '';

		// SHOWING LINKS
		if ($this->show_count){
			$curr_offset = $this->page;
			$info = 'Showing ' . ( $curr_offset + 1 ) . ' to ' ;

			if( ( $curr_offset + $this->per_page ) < ( $this->total_rows -1 ) )
			$info .= $curr_offset + $this->per_page;
			else
			$info .= $this->total_rows;

			$info .= ' of ' . $this->total_rows . ' | ';

			$output .= $info;
		}

		// Render the "First" link
		if  ($this->cur_page > $this->num_links){
			$output .= $this->first_tag_open
					. $this->getAJAXlink( '' , $this->first_link)
					. $this->first_tag_close;
		}

		// Render the "previous" link
		if  ($this->cur_page != 1){
			$i = $uri_page_number - $this->per_page;
			if ($i == 0) $i = '';
			$output .= $this->prev_tag_open
					. $this->getAJAXlink( $i, $this->prev_link )
					. $this->prev_tag_close;
		}

		// Write the digit links
		for ($loop = $start -1; $loop <= $end; $loop++){
			$i = ($loop * $this->per_page) - $this->per_page;
			if ($i >= 0){
				if ($this->cur_page == $loop){
					$output .= $this->cur_tag_open.$loop.$this->cur_tag_close; // Current page
				}else{
					$n = ($i == 0) ? '' : $i;
					$output .= $this->num_tag_open
						. $this->getAJAXlink( $n, $loop )
						. $this->num_tag_close;
				}
			}
		}

		// Render the "next" link
		if ($this->cur_page < $num_pages){
			$output .= $this->next_tag_open
				. $this->getAJAXlink( $this->cur_page * $this->per_page , $this->next_link )
				. $this->next_tag_close;
		}

		// Render the "Last" link
		if (($this->cur_page + $this->num_links) < $num_pages){
			$i = (($num_pages * $this->per_page) - $this->per_page);
			$output .= $this->last_tag_open . $this->getAJAXlink( $i, $this->last_link ) . $this->last_tag_close;
		}

		// Kill double slashes.  Note: Sometimes we can end up with a double slash
		// in the penultimate link so we'll kill all double slashes.
		$output = preg_replace("#([^:])//+#", "\\1/", $output);

		// Add the wrapper HTML if exists
		$output = $this->full_tag_open.$output.$this->full_tag_close;
		?>

        <?php
		return $output;
	}

	function getAJAXlink($count, $text) {
        $pageCount = $count?$count:0;
		return 'anchor_class . ' onclick="'.$this->link_func.'('.$pageCount.')">'. $text .'';
	}

}
// END Pagination Class


text:
// @flow
import * as React from "react";

import Keys from "../../data/key-configs.js";

import {
    KeypadPageContainer,
    SecondaryKeypadButton,
    KeypadActionButton,
} from "./keypad-page-items.js";

type Props = {|
    onClickKey: (keyConfig: string) => void,
|};

export default class TrigonometryInputPage extends React.Component<Props> {
    render(): React.Node {
        const {onClickKey} = this.props;
        return (
            <KeypadPageContainer>
                {/* Row 1 */}
                <SecondaryKeypadButton
                    keyConfig={Keys.SIN}
                    onClickKey={onClickKey}
                />
                <SecondaryKeypadButton
                    keyConfig={Keys.COS}
                    onClickKey={onClickKey}
                />
                <SecondaryKeypadButton
                    keyConfig={Keys.TAN}
                    onClickKey={onClickKey}
                />

                <SecondaryKeypadButton
                    keyConfig={Keys.LEFT_PAREN}
                    onClickKey={onClickKey}
                    style={{
                        gridColumn: 5,
                    }}
                />
                <SecondaryKeypadButton
                    keyConfig={Keys.RIGHT_PAREN}
                    onClickKey={onClickKey}
                    style={{
                        gridColumn: 6,
                    }}
                />
                {/* Row 2 */}
                <SecondaryKeypadButton
                    keyConfig={Keys.X}
                    onClickKey={onClickKey}
                    style={{
                        gridColumn: 5,
                    }}
                />
                <SecondaryKeypadButton
                    keyConfig={Keys.FRAC_INCLUSIVE}
                    onClickKey={onClickKey}
                    style={{
                        gridColumn: 6,
                    }}
                />
                {/* Row 3 */}
                <SecondaryKeypadButton
                    keyConfig={Keys.PI}
                    onClickKey={onClickKey}
                    style={{
                        gridColumn: 5,
                    }}
                />
                <KeypadActionButton
                    keyConfig={Keys.BACKSPACE}
                    style={{
                        gridColumn: "6",
                    }}
                    onClickKey={onClickKey}
                />
                {/* Row 4 */}
                <KeypadActionButton
                    keyConfig={Keys.DISMISS}
                    style={{
                        gridColumn: "6",
                    }}
                    onClickKey={onClickKey}
                />
            </KeypadPageContainer>
        );
    }
}


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

namespace AF.TextMiner
{
    public class TextCorpus
    {
        static string punctuation = @",.:;!?&^-%$/()=¿\";
        private List<NGram> _ngrams;

        public string  Identifier { get; set; }
        public List<NGram> NGrams { get { return _ngrams; } }

        public double TotalWords { get { return NGrams.Sum(x => (double) (x.Count ?? 0)); } }

        public TextCorpus(string identifier)
        {
            Identifier = identifier;
            _ngrams = new List<NGram>();
        }

        public static TextCorpus GenerateNewCorpus(string corpusIdentifier, string textToProcess)
        {
            TextCorpus corpus = new TextCorpus(corpusIdentifier);
            //List<NGram> ngrams = new List<NGram>();
            for(byte i = 2; i <= 4; i++)
            {
                foreach (string gram in GetWords(textToProcess, i))
                {
                    var tmpNgram = corpus.NGrams.Find(x => x.GramSize == i &&  x.Text == gram);
                    if(tmpNgram != null)
                    {
                        tmpNgram.Count++;
                    }
                    else
                    {
                        corpus.NGrams.Add(new NGram() { Count = 1, GramSize = i, Text = gram });
                    }
                }
            }
            return corpus;
        }

        private static List<string> GetWords(string text, byte gramSize)
        {
            List<NGram> ngrams = new List<NGram>();
            List<string> words = new List<string>();
            text = text.Trim();
            string tmpContent = string.Empty;
            byte spaceCount = 0;
            int lastSpaceFound = 0;
            for (int i = 0; i < text.Length; i++)
            {
                char current = text[i];
                if (punctuation.Contains(current)) // puntuation
                {
                    if (spaceCount == gramSize)
                    {
                        words.Add(tmpContent);

                        //i = lastSpaceFound != 0 ? lastSpaceFound : i;
                        lastSpaceFound = 0;

                    }
                    spaceCount = 0;
                    tmpContent = string.Empty;
                }
                else if (current == ' ')   // blank space
                {
                    if (!string.IsNullOrWhiteSpace(tmpContent))
                    {
                        if (++spaceCount == gramSize)
                        {
                            spaceCount = 0;
                            words.Add(tmpContent);
                            tmpContent = string.Empty;
                            i = lastSpaceFound != 0 ? lastSpaceFound : i;
                            lastSpaceFound = 0;
                        }
                        else
                        {
                            tmpContent += ' ';
                            lastSpaceFound = lastSpaceFound <= 0 ? i : lastSpaceFound;
                        }
                    }
                }
                else if( i == text.Length - 1) // end of text
                {
                    words.Add(tmpContent + current);
                }
                else
                    tmpContent += current;
            }
            return words;
        }

        public void CalculatePercentagesAndSort()
        {
            CalculatePercentages();
            Sort();
        }

        private void CalculatePercentages()
        {
            foreach(var element in _ngrams)
            {
                element.Percentaje = (double) element.Count / _ngrams.Where(x => x.GramSize == element.GramSize).Sum(x => x.Count);
            }
        }

        private void Sort()
        {
            this._ngrams = this._ngrams.OrderBy(x => x.GramSize).ThenByDescending(x => x.Percentaje).ToList();
        }
    }
}


text: .. automodule:: irc3.plugins.core


text:
<?php
namespace Concrete\Core\Entity\Attribute\Key;

use Concrete\Core\Attribute\AttributeKeyInterface;
use Concrete\Core\Attribute\Key\SearchIndexer\StandardSearchIndexer;
use Concrete\Core\Attribute\Type;
use Concrete\Core\Entity\Attribute\Category;
use Concrete\Core\Entity\Attribute\Set;
use Concrete\Core\Entity\PackageTrait;
use Concrete\Core\Export\ExportableInterface;
use Concrete\Core\Export\Item\AttributeKey;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="akCategory", type="string")
 * @ORM\Table(
 *     name="AttributeKeys",
 *     indexes={
 *     @ORM\Index(name="pkgID", columns={"pkgID"})
 *     }
 * )
 */
class Key implements AttributeKeyInterface, ExportableInterface
{
    use PackageTrait;

    /**
     * @ORM\Id @ORM\Column(type="integer", options={"unsigned":true})
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $akID;

    /**
     * @ORM\Column(type="string")
     */
    protected $akHandle;

    /**
     * @ORM\Column(type="string")
     */
    protected $akName;

    /**
     * @ORM\Column(type="boolean")
     */
    protected $akIsSearchable = true;

    /**
     * @ORM\Column(type="boolean")
     */
    protected $akIsInternal = false;

    /**
     * @ORM\Column(type="boolean")
     */
    protected $akIsSearchableIndexed = false;

    /**
     * @ORM\OneToOne(targetEntity="\Concrete\Core\Entity\Attribute\Key\Type\Type", mappedBy="key", cascade={"persist", "remove"})
     */
    protected $key_type;

    /**
     * @ORM\OneToMany(targetEntity="\Concrete\Core\Entity\Attribute\SetKey", mappedBy="attribute_key", cascade={"remove"}),
     * @ORM\JoinColumn(name="akID", referencedColumnName="akID")
     */
    protected $set_keys;

    /**
     * @ORM\OneToMany(targetEntity="\Concrete\Core\Entity\Attribute\Value\Value", mappedBy="attribute_key", cascade={"remove"})
     * @ORM\JoinColumn(name="avID", referencedColumnName="avID")
     **/
    protected $attribute_values;

    /**
     * @ORM\ManyToOne(targetEntity="\Concrete\Core\Entity\Attribute\Category")
     * @ORM\JoinColumn(name="akCategoryID", referencedColumnName="akCategoryID")
     **/
    protected $category;

    public function setAttributeKeyID($akID)
    {
        $this->akID = $akID;
    }

    /**
     * @return mixed
     */
    public function getAttributeKeyID()
    {
        return $this->akID;
    }

    /**
     * @return mixed
     */
    public function getAttributeKeyHandle()
    {
        return $this->akHandle;
    }

    /**
     * @param mixed $handle
     */
    public function setAttributeKeyHandle($akHandle)
    {
        $this->akHandle = $akHandle;
    }

    /**
     * @return mixed
     */
    public function isAttributeKeyInternal()
    {
        return $this->akIsInternal;
    }

    /**
     * @param mixed $is_internal
     */
    public function setIsAttributeKeyInternal($akIsInternal)
    {
        $this->akIsInternal = $akIsInternal;
    }

    /**
     * @return mixed
     */
    public function getAttributeKeyName()
    {
        return $this->akName;
    }

    /**
     * @param mixed $name
     */
    public function setAttributeKeyName($akName)
    {
        $this->akName = $akName;
    }

    /**
     * @return mixed
     */
    public function isAttributeKeySearchable()
    {
        return $this->akIsSearchable;
    }

    /**
     * @param mixed $is_searchable
     */
    public function setIsAttributeKeySearchable($akIsSearchable)
    {
        $this->akIsSearchable = $akIsSearchable;
    }

    /**
     * @return mixed
     */
    public function isAttributeKeyContentIndexed()
    {
        return $this->akIsSearchableIndexed;
    }

    /**
     * @param mixed $is_indexed
     */
    public function setIsAttributeKeyContentIndexed($akIsSearchableIndexed)
    {
        $this->akIsSearchableIndexed = $akIsSearchableIndexed;
    }

    /**
     * @return mixed
     */
    public function getAttributeKeyType()
    {
        return $this->key_type;
    }

    /**
     * @param mixed $type
     */
    public function setAttributeKeyType($key_type)
    {
        $this->key_type = $key_type;
    }

    public function getAttributeType()
    {
        return $this->getAttributeKeyType()->getAttributeType();
    }

    public function getAttributeTypeHandle()
    {
        return $this->getAttributeKeyType()->getAttributeType()->getAttributeTypeHandle();
    }

    public function getController()
    {
        $type = $this->getAttributeKeyType();
        if ($type) {
            $controller = $type->getAttributeType()->getController();
            $controller->setAttributeKey($this);
            return $controller;
        }
    }

    public function getAttributeKeyCategoryHandle()
    {
        return false;
    }

    /**
     * This is redundant given we already have the handle but we're actually adding this
     * for backward compatibility so we have an akCategoryID association column.
     * @return Category
     */
    public function getAttributeCategory()
    {
        return $this->category;
    }

    /**
     * @param mixed $category
     */
    public function setAttributeCategory($category)
    {
        $this->category = $category;
    }

    public function getExporter()
    {
        return new AttributeKey();
    }

    /**
     * @deprecated
     */
    public function saveAttributeForm($mixed)
    {
        $controller = $this->getController();
        $value = $controller->getAttributeValueFromRequest();
        $mixed->setAttribute($this, $value);

        return $value;
    }

    /**
     * @deprecated
     */
    public function render($view = 'view', $value = false, $return = false)
    {
        $resp = $this->getAttributeType()->render($view, $this, $value, $return);
        if ($return) {
            return $resp;
        } else {
            echo $resp;
        }
    }

    public function getAttributeKeyDisplayName($format = 'html')
    {
        $value = tc('AttributeKeyName', $this->getAttributeKeyName());
        switch ($format) {
            case 'html':
                return h($value);
            case 'text':
            default:
                return $value;
        }
    }

    public function getAttributeSets()
    {
        return \Concrete\Core\Attribute\Set::getByAttributeKey($this);
    }

    public function inAttributeSet(Set $set)
    {
        $sets = $this->getAttributeSets();

        return in_array($set, $sets);
    }

    public function getSearchIndexer()
    {
        return \Core::make('Concrete\Core\Attribute\Key\SearchIndexer\StandardSearchIndexer');
    }

    /**
     * Doctrine requires this for certain queries.
     *
     * @return mixed
     */
    public function __toString()
    {
        return (string) $this->getAttributeKeyID();
    }

    /**
     * @deprecated
     */
    public function setAttributeSet($set)
    {
        if (!is_object($set)) {
            $set = Set::getByHandle($set);
        }
        $set->addKey($this);
    }

}


text:
package br.ufsc.core.trajectory;

import java.time.Instant;
import java.time.LocalTime;
import java.time.ZoneId;

import org.joda.time.Interval;

public class OverlapTemporalSemantic extends TemporalSemantic<TemporalDuration, Number> {
	public OverlapTemporalSemantic(int index) {
		super(index);
	}

	@Override
	public boolean match(SemanticTrajectory a, int i, SemanticTrajectory b, int j, Number threshlod) {
		return distance(a, i, b, j) <= threshlod.doubleValue();
	}

	@Override
	public boolean match(TemporalDuration d1, TemporalDuration d2, Number threshlod) {
		return distance(d1, d2) <= threshlod.doubleValue();
	}

	@Override
	public Double distance(SemanticTrajectory a, int i, SemanticTrajectory b, int j) {
		TemporalDuration a1 = (TemporalDuration) a.getDimensionData(index, i);
		TemporalDuration b1 = (TemporalDuration) b.getDimensionData(index, j);
		return (double) distance(a1, b1);
	}

	public double distance(TemporalDuration d1, TemporalDuration d2) {
		long aStart = LocalTime.from(d1.getStart().atZone(ZoneId.of("GMT"))).toSecondOfDay();
		long aEnd = LocalTime.from(d1.getEnd().atZone(ZoneId.of("GMT"))).toSecondOfDay();
		aEnd = aEnd < aStart ? aEnd + (24 * 60 * 60) : aEnd;
		long bStart = LocalTime.from(d2.getStart().atZone(ZoneId.of("GMT"))).toSecondOfDay();
		long bEnd = LocalTime.from(d2.getEnd().atZone(ZoneId.of("GMT"))).toSecondOfDay();
		bEnd = bEnd < bStart ? bEnd + (24 * 60 * 60) : bEnd;
		Interval intervalA = new Interval(aStart * 1000, aEnd * 1000);
		Interval intervalB = new Interval(bStart * 1000, bEnd * 1000);
		Interval overlapAtoB = intervalA.overlap(intervalB);
		if(overlapAtoB == null) {
			if(intervalA.equals(intervalB)) {
				return 0;
			}
			return 1;
		}
		double overlap = overlapAtoB.toDurationMillis();
		Instant lastEnd = Instant.ofEpochSecond(aEnd > bEnd ? aEnd: bEnd);
		Instant firstStart = Instant.ofEpochSecond(aStart < bStart ? aStart: bStart);
		double maxDuration = new Interval(firstStart.toEpochMilli(), lastEnd.toEpochMilli()).toDurationMillis();
		return (1 - overlap / maxDuration);
	}
}


text:
package org.opensmartgridplatform.adapter.domain.publiclighting.application.services;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.opensmartgridplatform.domain.core.entities.Device;
import org.opensmartgridplatform.domain.core.entities.Ssld;
import org.opensmartgridplatform.domain.core.valueobjects.Schedule;
import org.opensmartgridplatform.dto.valueobjects.ScheduleDto;
import org.opensmartgridplatform.shared.infra.jms.CorrelationIds;
import org.opensmartgridplatform.shared.exceptionhandling.FunctionalException;
import org.opensmartgridplatform.shared.infra.jms.RequestMessage;

@Service(value = "domainPublicLightingScheduleManagementService")
@Transactional(value = "transactionManager")
public class ScheduleManagementService extends AbstractService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ScheduleManagementService.class);

    /**
     * Constructor
     */
    public ScheduleManagementService() {
        // Parameterless constructor required for transactions...
    }

    // === SET LIGHT SCHEDULE ===

    /**
     * Set a light schedule.
     */
    public void setLightSchedule(final CorrelationIds ids, final Schedule schedule, final Long scheduleTime,
            final String messageType, final int messagePriority) throws FunctionalException {

        LOGGER.info("setSchedule called with organisation {} and device {}.", ids.getOrganisationIdentification(),
                ids.getDeviceIdentification());

        this.findOrganisation(ids.getOrganisationIdentification());
        final Device device = this.findActiveDevice(ids.getDeviceIdentification());

        final ScheduleDto scheduleDto = this.domainCoreMapper.map(schedule, ScheduleDto.class);

        this.osgpCoreRequestMessageSender.send(new RequestMessage(ids, scheduleDto), messageType, messagePriority,
                device.getIpAddress(), scheduleTime);
    }

    // === SET HAS SCHEDULE ===

    /**
     * Method for setting the 'hasSchedule' boolean for a device.
     *
     * @throws FunctionalException
     */
    public void setHasSchedule(final String deviceIdentification, final Boolean hasSchedule)
            throws FunctionalException {

        LOGGER.info("setHasSchedule called for device {} with hasSchedule: {}.", deviceIdentification, hasSchedule);

        final Device device = this.findActiveDevice(deviceIdentification);
        final Ssld ssld = this.findSsldForDevice(device);
        ssld.setHasSchedule(hasSchedule);
        this.ssldRepository.save(ssld);
    }
}


text:
require 'test_helper'

class RubygemsControllerTest < ActionController::TestCase
  should_forbid_access_when("pushing a gem") { post :create }

  context "When logged in" do
    setup do
      @user = Factory(:email_confirmed_user)
      sign_in_as(@user)
    end

    context "On GET to show for another user's gem" do
      setup do
        @rubygem = Factory(:rubygem)
        get :show, :id => @rubygem.to_param
      end

      should_respond_with :success
      should_render_template :show
      should_assign_to :rubygem
      should "not render edit link" do
        assert_have_no_selector "a[href='#{edit_rubygem_path(@rubygem)}']"
      end
    end

    context "On GET to show for a gem that's hosted" do
      setup do
        @rubygem = Factory(:rubygem)
        Factory(:version, :rubygem => @rubygem)
        get :show, :id => @rubygem.to_param, :format => "json"
      end

      should_assign_to(:rubygem) { @rubygem }
      should_respond_with :success
      should "return a json hash" do
        assert_not_nil JSON.parse(@response.body)
      end
    end

    context "On GET to show for a gem that doesn't match the slug" do
      setup do
        @rubygem = Factory(:rubygem, :name => "ZenTest", :slug => "zentest")
        Factory(:version, :rubygem => @rubygem)
        get :show, :id => "ZenTest", :format => "json"
      end

      should_assign_to(:rubygem) { @rubygem }
      should_respond_with :success
      should "return a json hash" do
        assert_not_nil JSON.parse(@response.body)
      end
    end

    context "On GET to show for a gem that not hosted" do
      setup do
        @rubygem = Factory(:rubygem)
        assert 0, @rubygem.versions.count
        get :show, :id => @rubygem.to_param, :format => "json"
      end

      should_assign_to(:rubygem) { @rubygem }
      should_respond_with :not_found
    end

    context "On GET to show for a gem that doesn't exist" do
      setup do
        @name = Factory.next(:name)
        assert ! Rubygem.exists?(:name => @name)
        get :show, :id => @name, :format => "json"
      end

      should_respond_with :not_found
      should "say the rubygem was not found" do
        assert_match /not be found/, @response.body
      end
    end

    context "On GET to show for this user's gem" do
      setup do
        create_gem(@user)
        get :show, :id => @rubygem.to_param
      end

      should_respond_with :success
      should_render_template :show
      should_assign_to :rubygem
      should "render edit link" do
        assert_have_selector "a[href='#{edit_rubygem_path(@rubygem)}']"
      end
    end

    context "On GET to show for a gem that the user is subscribed to" do
      setup do
        @rubygem = Factory(:rubygem)
        Factory(:version, :rubygem => @rubygem)
        Factory(:subscription, :rubygem => @rubygem, :user => @user)
        get :show, :id => @rubygem.to_param
      end

      should_assign_to(:rubygem) { @rubygem }
      should_respond_with :success
      should "have an invisible subscribe link" do
        assert_have_selector "a[style='display:none']", :content => 'Subscribe'
      end
      should "have a visible unsubscribe link" do
        assert_have_selector "a[style='display:block']", :content => 'Unsubscribe'
      end
    end

    context "On GET to show for a gem that the user is not subscribed to" do
      setup do
        @rubygem = Factory(:rubygem)
        Factory(:version, :rubygem => @rubygem)
        get :show, :id => @rubygem.to_param
      end

      should_assign_to(:rubygem) { @rubygem }
      should_respond_with :success
      should "have a visible subscribe link" do
        assert_have_selector "a[style='display:block']", :content => 'Subscribe'
      end
      should "have an invisible unsubscribe link" do
        assert_have_selector "a[style='display:none']", :content => 'Unsubscribe'
      end
    end

    context "On GET to edit for this user's gem" do
      setup do
        create_gem(@user)
        get :edit, :id => @rubygem.to_param
      end

      should_respond_with :success
      should_render_template :edit
      should_assign_to :rubygem
      should "render form" do
        assert_have_selector "form"
        assert_have_selector "input#linkset_code"
        assert_have_selector "input#linkset_docs"
        assert_have_selector "input#linkset_wiki"
        assert_have_selector "input#linkset_mail"
        assert_have_selector "input#linkset_bugs"
        assert_have_selector "input[type='submit']"
      end
    end

    context "On GET to edit for another user's gem" do
      setup do
        @other_user = Factory(:email_confirmed_user)
        create_gem(@other_user)
        get :edit, :id => @rubygem.to_param
      end
      should_respond_with :redirect
      should_assign_to(:linkset) { @linkset }
      should_redirect_to('the homepage') { root_url }
      should_set_the_flash_to "You do not have permission to edit this gem."
    end

    context "On PUT to update for this user's gem that is successful" do
      setup do
        @url = "http://github.com/qrush/gemcutter"
        create_gem(@user)
        put :update, :id => @rubygem.to_param, :linkset => {:code => @url}
      end
      should_respond_with :redirect
      should_redirect_to('the gem') { rubygem_path(@rubygem) }
      should_set_the_flash_to "Gem links updated."
      should_assign_to(:linkset) { @linkset }
      should "update linkset" do
        assert_equal @url, Rubygem.last.linkset.code
      end
    end

    context "On PUT to update for this user's gem that fails" do
      setup do
        create_gem(@user)
        @url = "totally not a url"
        put :update, :id => @rubygem.to_param, :linkset => {:code => @url}
      end
      should_respond_with :success
      should_render_template :edit
      should_assign_to(:linkset) { @linkset }
      should "not update linkset" do
        assert_not_equal @url, Rubygem.last.linkset.code
      end
      should "render error messages" do
        assert_contain /error(s)? prohibited/m
      end
    end
  end

  context "On GET to edit without being signed in" do
    setup do
      @rubygem = Factory(:rubygem)
      get :edit, :id => @rubygem.to_param
    end
    should_respond_with :redirect
    should_redirect_to('the homepage') { root_url }
  end

  context "On PUT to update without being signed in" do
    setup do
      @rubygem = Factory(:rubygem)
      put :update, :id => @rubygem.to_param, :linkset => {}
    end
    should_respond_with :redirect
    should_redirect_to('the homepage') { root_url }
  end

  context "On GET to index with no parameters" do
    setup do
      @gems = (1..3).map do |n|
        gem = Factory(:rubygem, :name => "agem#{n}")
        Factory(:version, :rubygem => gem)
        gem
      end
      Factory(:rubygem, :name => "zeta")
      get :index
    end

    should_respond_with :success
    should_render_template :index
    should_assign_to(:gems) { @gems }
    should "render links" do
      @gems.each do |g|
        assert_contain g.name
        assert_have_selector "a[href='#{rubygem_path(g)}']"
      end
    end
    should "display uppercase A" do
      assert_contain "starting with A"
    end
  end

  context "On GET to index as an atom feed" do
    setup do
      @versions = (1..3).map { |n| Factory(:version, :created_at => n.hours.ago) }
      get :index, :format => "atom"
    end

    should_respond_with :success
    should_assign_to(:versions) { @versions }
    should "render posts with titles and links" do
      @versions.each do |v|
        assert_contain v.to_title
        assert_have_selector "link[href='#{rubygem_url(v.rubygem)}']"
      end
    end
  end

  context "On GET to index with a letter" do
    setup do
      @gems = (1..3).map { |n| Factory(:rubygem, :name => "agem#{n}") }
      @zgem = Factory(:rubygem, :name => "zeta")
      Factory(:version, :rubygem => @zgem)
      get :index, :letter => "z"
    end
    should_respond_with :success
    should_render_template :index
    should_assign_to(:gems) { [@zgem] }
    should "render links" do
      assert_contain @zgem.name
      assert_have_selector "a[href='#{rubygem_path(@zgem)}']"
    end
    should "display uppercase letter" do
      assert_contain "starting with Z"
    end
  end

  context "On GET to show" do
    setup do
      @latest_version = Factory(:version)
      @rubygem = @latest_version.rubygem
      get :show, :id => @rubygem.to_param
    end

    should_respond_with :success
    should_render_template :show
    should_assign_to :rubygem
    should_assign_to(:latest_version) { @latest_version }
    should "render info about the gem" do
      assert_contain @rubygem.name
      assert_contain @latest_version.number
      assert_contain @latest_version.built_at.to_date.to_formatted_s(:long)
    end
  end

  context "On GET to show with a gem that has multiple versions" do
    setup do
      @rubygem = Factory(:rubygem)
      @older_version = Factory(:version, :number => "1.0.0", :rubygem => @rubygem)
      @latest_version = Factory(:version, :number => "2.0.0", :rubygem => @rubygem)
      get :show, :id => @rubygem.to_param
    end

    should_respond_with :success
    should_render_template :show
    should_assign_to :rubygem
    should "render info about the gem" do
      assert_contain @rubygem.name
      assert_contain @latest_version.number
      assert_contain @latest_version.built_at.to_date.to_formatted_s(:long)

      assert_contain "Versions"
      assert_contain @rubygem.versions.last.number
      assert_contain @rubygem.versions.last.built_at.to_date.to_formatted_s(:long)
    end
  end

  context "On GET to show for a gem with no versions" do
    setup do
      @rubygem = Factory(:rubygem)
      get :show, :id => @rubygem.to_param
    end
    should_respond_with :success
    should_render_template :show
    should_assign_to :rubygem
    should "render info about the gem" do
      assert_contain "This gem is not currently hosted on Gemcutter."
    end
  end

  context "On GET to show for a gem with both runtime and development dependencies" do
    setup do
      @version = Factory(:version)

      @development = Factory(:development_dependency, :version => @version)
      @runtime     = Factory(:runtime_dependency,     :version => @version)

      get :show, :id => @version.rubygem.to_param
    end

    should_respond_with :success
    should_render_template :show
    should_assign_to(:latest_version) { @version }
    should "show runtime dependencies and development dependencies" do
      assert_contain @runtime.rubygem.name
      assert_contain @development.rubygem.name
    end
  end

  context "with a confirmed user authenticated" do
    setup do
      @user = Factory(:email_confirmed_user)
      @request.env["HTTP_AUTHORIZATION"] = @user.api_key
    end

    context "On POST to create for new gem" do
      setup do
        @request.env["RAW_POST_DATA"] = gem_file.read
        post :create
      end
      should_respond_with :success
      should_assign_to(:_current_user) { @user }
      should_change("the rubygem count") { Rubygem.count }
      should "register new gem" do
        assert_equal @user, Rubygem.last.ownerships.first.user
        assert_equal "Successfully registered gem: test (0.0.0)", @response.body
      end
    end

    context "On POST to create for existing gem" do
      setup do
        rubygem = Factory(:rubygem, :name => "test")
        rubygem.ownerships.create(:user => @user, :approved => true)
        rubygem.versions.create(:number => "0.0.0", :updated_at => 1.year.ago, :created_at => 1.year.ago)
        @request.env["RAW_POST_DATA"] = gem_file("test-1.0.0.gem").read
        post :create
      end
      should_respond_with :success
      should_assign_to(:_current_user) { @user }
      should "register new version" do
        assert_equal @user, Rubygem.last.ownerships.first.user
        assert_equal 1, Rubygem.last.ownerships.size
        assert_equal 2, Rubygem.last.versions.size
        assert_equal "Successfully registered gem: test (1.0.0)", @response.body
      end
    end

    context "On POST to create with bad gem" do
      setup do
        @request.env["RAW_POST_DATA"] = "really bad gem"
        post :create
      end
      should_respond_with :unprocessable_entity
      should_not_change("the rubygem count") { Rubygem.count }
      should "not register gem" do
        assert_match /Gemcutter cannot process this gem/, @response.body
      end
    end

    context "On POST to create for someone else's gem" do
      setup do
        @other_user = Factory(:email_confirmed_user)
        create_gem(@other_user, :name => "test")
        @rubygem.reload

        @request.env["RAW_POST_DATA"] = gem_file("test-1.0.0.gem").read
        post :create
      end
      should_respond_with 403
      should_assign_to(:_current_user) { @user }
      should "not allow new version to be saved" do
        assert_equal 1, @rubygem.ownerships.size
        assert_equal @other_user, @rubygem.ownerships.first.user
        assert_equal 1, @rubygem.versions.size
        assert_equal "You do not have permission to push to this gem.", @response.body
      end
    end
  end

  context "When not logged in" do
    context "On GET to show for a gem" do
      setup do
        @rubygem = Factory(:rubygem)
        Factory(:version, :rubygem => @rubygem)
        get :show, :id => @rubygem.to_param
      end

      should_assign_to(:rubygem) { @rubygem }
      should_respond_with :success
      should "have an subscribe link that goes to the sign in page" do
        assert_have_selector "a[href='#{sign_in_path}']"
      end
    end
  end
end


text:
<?php

namespace Tequila\MongoDBBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Tequila\MongoDB\ODM\Proxy\Factory\GeneratorFactory;
use Tequila\MongoDBBundle\DocumentManagerFactory;
use Tequila\MongoDBBundle\ProxiesGenerator;

class GenerateProxiesCommand extends ContainerAwareCommand
{
    /**
     * @var DocumentManagerFactory
     */
    private $dmFactory;

    /**
     * @param DocumentManagerFactory $dmFactory
     */
    public function __construct(DocumentManagerFactory $dmFactory)
    {
        $this->dmFactory = $dmFactory;

        parent::__construct();
    }

    public function configure()
    {
        $this
            ->setName('tequila_mongodb:generate:proxies')
            ->setDescription('Generates proxy classes using class metadata.')
            ->addArgument(
                'path',
                InputArgument::REQUIRED,
                'Path to directory where document classes are located'
            )
            ->addOption(
                'dm',
                null,
                InputOption::VALUE_REQUIRED,
                'Document manager alias that you want to use to get document class metadata.',
                'default'
            );
    }

    public function execute(InputInterface $input, OutputInterface $output)
    {
        $dmAlias = $input->getOption('dm');
        $dmId = $this->dmFactory->getManagerServiceId($dmAlias);
        $path = $input->getArgument('path');
        $dm = $this->dmFactory->getManager($dmAlias);
        $generatorFactoryId = $dmId.'.proxy.generator_factory';
        /** @var GeneratorFactory $generatorFactory */
        $generatorFactory = $this->getContainer()->get($generatorFactoryId);
        $proxiesGenerator = new ProxiesGenerator($generatorFactory);
        $documentClasses = $proxiesGenerator->generateProxies($dm, $path);

        $style = new SymfonyStyle($input, $output);

        if ($numberOfClasses = count($documentClasses)) {
            $out = sprintf(
                'Proxies successfully generated for %d document classes:',
                $numberOfClasses
            );
            $out .= PHP_EOL;
            foreach ($documentClasses as $class) {
                $out .= '    - '.$class.PHP_EOL;
            }

            $style->success($out);
        } else {
            $style->warning(
                sprintf('There is no document classes at location %s.', $path)
            );
        }
    }
}


text:
<?php

namespace CrEOF\Spatial\ORM\Query\AST\Functions\MySql;

use CrEOF\Spatial\ORM\Query\AST\Functions\AbstractSpatialDQLFunction;

/**
 * Envelope DQL function
 *
 * @author  Derek J. Lambert <dlambert@dereklambert.com>
 * @license http://dlambert.mit-license.org MIT
 */
class Envelope extends AbstractSpatialDQLFunction
{
    protected $platforms = array('mysql');

    protected $functionName = 'Envelope';

    protected $minGeomExpr = 1;

    protected $maxGeomExpr = 1;
}


text:
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='SessionBackup',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('data', models.TextField()),
                ('user', models.OneToOneField(related_name='user_session_data', to=settings.AUTH_USER_MODEL)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]


text:
Camera::Camera(const glm::vec3& position, const glm::vec3& look_at, const glm::vec3& up,
               std::unique_ptr<ImageBuffer> image_buffer, Type type)
    : type_(type),
      position_(position),
      look_at_(look_at),
      up_(up),
      direction_(glm::normalize(look_at - position)),
      camera_onb_(glm::normalize(glm::cross(up_, -direction_)), -direction_),
      image_buffer_(std::move(image_buffer)) {}


text:
// ROS includes
#include "ros/ros.h"
#include "ros/assert.h"
#include "dynamic_reconfigure/server.h"
#include "create_driver/vicon_driver.h"
#include "geometry_msgs/Twist.h"

// Library includes
#include <string>
#include <vector>
#include <map>
#include <Eigen/Core>
#include <Eigen/LU>

using namespace std;
using namespace Eigen;

// Constants
const double PI = 3.1415926535;

int main(int argc, char **argv)
{
	// ROS Initalization
	ros::init(argc, argv, "control");

	ros::NodeHandle n;
	ros::NodeHandle private_n("~");

	// ROS Parameters

	// List of robot names
	vector<string> robot_names;
	XmlRpc::XmlRpcValue robot_list;
	private_n.getParam("robot_list", robot_list);
	ROS_ASSERT(robot_list.getType() == XmlRpc::XmlRpcValue::TypeArray);

	for (int i = 0; i < robot_list.size(); i++)
	{
		ROS_ASSERT(robot_list[i].getType() == XmlRpc::XmlRpcValue::TypeString);
		robot_names.push_back(static_cast<string>(robot_list[i]));
	}

	// Number of robots
	const int num_robots = robot_names.size();

	// Robot name
	string robot_name;
	private_n.param<std::string>("robotname", robot_name, "defaultname");

	int index = find(robot_names.begin(), robot_names.end(), robot_name) - robot_names.begin();

	// ROS Subscribers
	map<string, create_driver::ViconStream> vicon;
	vector<string>::iterator name_it;
	vector<ros::Subscriber> sub;
	for (name_it = robot_names.begin(); name_it != robot_names.end(); name_it++)
	{
		vicon.insert(pair<string, create_driver::ViconStream>(*name_it, create_driver::ViconStream()));
		sub.push_back(n.subscribe("/" + *name_it + "/tf", 10, &create_driver::ViconStream::callback, &vicon[*name_it]));
	}

	// ROS Publishers
	ros::Publisher vel = n.advertise<geometry_msgs::Twist>("cmd_vel", 10);

	// ROS loop
	ros::Rate loop_rate(250); // 250 Hz

	while (ros::ok())
	{
		// Retrieve Vicon Data
		ros::spinOnce();

		/* An instance of this code is run on each robot in the formation.
		 *
		 * You can access each robot's position and oreintation through the following statements:
		 * vicon[robot_names[i]].x() // meters
		 * vicon[robot_names[i]].y() // meters
		 * vicon[robot_names[i]].theta()
		 *
		 * The index of the robot running the instance of the code is contain in the "index"
		 * variable. For example, if you wanted to get the distance of this robot from all of its
		 * neighbors you could run the following:
		 * double dist[num_robots];
		 * for (int i = 0; i < num_robots; i++) {
		 * 		dist[i] = sqrt(pow(vicon[robot_names[i]].x() - vicon[robot_names[index]].x(),2)
		 * 				     + pow(vicon[robot_names[i]].y() - vicon[robot_names[index]].y(),2));
		 * }
		 */

		double v = 5.0; //linear velocity output should be in millimeters per second
		double w = 0.1; // angular velocity output

		// Send wheel velocities to driver
		geometry_msgs::Twist msg;
		msg.linear.x = v;
		msg.linear.y = 0;
		msg.linear.z = 0;
		msg.angular.x = 0;
		msg.angular.y = 0;
		msg.angular.z = w;
		vel.publish(msg);

		loop_rate.sleep();
	}

	return 0;
}


text:
<?php

namespace lithium\tests\cases\template\helper;

use lithium\net\http\Router;
use lithium\template\helper\Html;
use lithium\action\Request;
use lithium\action\Response;
use lithium\tests\mocks\template\MockRenderer;

class HtmlTest extends \lithium\test\Unit {

	/**
	 * Test object instance
	 *
	 * @var object
	 */
	public $html = null;

	protected $_routes = [];

	/**
	 * Initialize test by creating a new object instance with a default context.
	 */
	public function setUp() {
		$this->_routes = Router::get();
		Router::reset();
		Router::connect('/{:controller}/{:action}/{:id}.{:type}');
		Router::connect('/{:controller}/{:action}.{:type}');

		$this->context = new MockRenderer([
			'request' => new Request([
				'base' => '', 'env' => ['HTTP_HOST' => 'foo.local']
			]),
			'response' => new Response()
		]);
		$this->html = new Html(['context' => &$this->context]);
	}

	/**
	 * Clean up after the test.
	 */
	public function tearDown() {
		Router::reset();
		foreach ($this->_routes as $scope => $routes) {
			Router::scope($scope, function() use ($routes) {
				foreach ($routes as $route) {
					Router::connect($route);
				}
			});
		}
		unset($this->html);
	}

	/**
	 * Tests that character set declarations render the
	 * correct character set and short meta tag.
	 */
	public function testCharset() {
		$result = $this->html->charset();
		$this->assertTags($result, ['meta' => [
			'charset' => 'UTF-8'
		]]);

		$result = $this->html->charset('utf-8');
		$this->assertTags($result, ['meta' => [
			'charset' => 'utf-8'
		]]);

		$result = $this->html->charset('UTF-7');
		$this->assertTags($result, ['meta' => [
			'charset' => 'UTF-7'
		]]);
	}

	/**
	 * Tests meta linking.
	 */
	public function testMetaLink() {
		$result = $this->html->link(
			'RSS Feed',
			['controller' => 'posts', 'type' => 'rss'],
			['type' => 'rss']
		);
		$this->assertTags($result, ['link' => [
			'href' => 'regex:/.*\/posts\/index\.rss/',
			'type' => 'application/rss+xml',
			'rel' => 'alternate',
			'title' => 'RSS Feed'
		]]);

		$result = $this->html->link(
			'Atom Feed', ['controller' => 'posts', 'type' => 'xml'], ['type' => 'atom']
		);
		$this->assertTags($result, ['link' => [
			'href' => 'regex:/.*\/posts\/index\.xml/',
			'type' => 'application/atom+xml',
			'title' => 'Atom Feed',
			'rel' => 'alternate'
		]]);

		$result = $this->html->link('No-existy', '/posts.xmp', ['type' => 'rong']);
		$this->assertTags($result, ['link' => [
			'href' => 'regex:/.*\/posts\.xmp/',
			'title' => 'No-existy'
		]]);

		$result = $this->html->link('No-existy', '/posts.xpp', ['type' => 'atom']);
		$this->assertTags($result, ['link' => [
			'href' => 'regex:/.*\/posts\.xpp/',
			'type' => 'application/atom+xml',
			'title' => 'No-existy',
			'rel' => 'alternate'
		]]);

		$result = $this->html->link('Favicon', [], ['type' => 'icon']);
		$expected = [
			'link' => [
				'href' => 'regex:/.*favicon\.ico/',
				'type' => 'image/x-icon',
				'rel' => 'icon',
				'title' => 'Favicon'
			],
			['link' => [
				'href' => 'regex:/.*favicon\.ico/',
				'type' => 'image/x-icon',
				'rel' => 'shortcut icon',
				'title' => 'Favicon'
			]]
		];
		$this->assertTags($result, $expected);
	}

	/**
	 * Tests <a /> elements generated by `HtmlHelper::link()`
	 */
	public function testLink() {
		$result = $this->html->link('/home');
		$expected = ['a' => ['href' => '/home'], 'regex:/\/home/', '/a'];
		$this->assertTags($result, $expected);

		$result = $this->html->link('Next >', '#');
		$expected = ['a' => ['href' => '#'], 'Next >', '/a'];
		$this->assertTags($result, $expected);

		$result = $this->html->link('Next >', '#', ['escape' => true]);
		$expected = [
			'a' => ['href' => '#'],
			'Next >',
			'/a'
		];
		$this->assertTags($result, $expected);

		$result = $this->html->link('Next >', '#', ['escape' => 'utf-8']);
		$expected = [
			'a' => ['href' => '#'],
			'Next >',
			'/a'
		];
		$this->assertTags($result, $expected);

		$result = $this->html->link('Next >', '#', ['escape' => false]);
		$expected = ['a' => ['href' => '#'], 'Next >', '/a'];
		$this->assertTags($result, $expected);

		$result = $this->html->link('Next >', '#', [
			'title' => 'to escape … or not escape?',
			'escape' => false
		]);
		$expected = [
			'a' => ['href' => '#', 'title' => 'to escape … or not escape?'],
			'Next >',
			'/a'
		];
		$this->assertTags($result, $expected);

		$result = $this->html->link('Next >', '#', [
			'title' => 'to escape … or not escape?', 'escape' => true
		]);
		$expected = [
			'a' => ['href' => '#', 'title' => 'to escape &#8230; or not escape?'],
			'Next >',
			'/a'
		];
		$this->assertTags($result, $expected);
	}

	/**
	 * Tests basic JavaScript linking using the <script /> tag
	 */
	public function testScriptLinking() {
		$result = $this->html->script('script.js');
		$expected = '<script src="/js/script.js"></script>';
		$this->assertEqual($expected, $result);

		$result = $this->html->script('script');
		$expected = '<script src="/js/script.js"></script>';
		$this->assertEqual($expected, $result);

		$result = $this->html->script('scriptaculous.js?load=effects');
		$expected = '<script src="/js/scriptaculous.js?load=effects"></script>';
		$this->assertEqual($expected, $result);

		$result = $this->html->script('jquery-1.1.2');
		$expected = '<script src="/js/jquery-1.1.2.js"></script>';
		$this->assertEqual($result, $expected);

		$result = $this->html->script('jquery-1.1.2');
		$expected = '<script src="/js/jquery-1.1.2.js"></script>';
		$this->assertEqual($result, $expected);

		$result = $this->html->script('/plugin/js/jquery-1.1.2');
		$expected = '<script src="/plugin/js/jquery-1.1.2.js"></script>';
		$this->assertEqual($result, $expected);

		$result = $this->html->script('/some_other_path/myfile.1.2.2.min.js');
		$expected = '<script src="/some_other_path/myfile.1.2.2.min.js"></script>';
		$this->assertEqual($result, $expected);

		$result = $this->html->script('some_other_path/myfile.1.2.2.min.js');
		$expected = '<script src="/js/some_other_path/myfile.1.2.2.min.js"></script>';
		$this->assertEqual($result, $expected);

		$result = $this->html->script('some_other_path/myfile.1.2.2.min');
		$expected = '<script src="/js/some_other_path/myfile.1.2.2.min.js"></script>';
		$this->assertEqual($result, $expected);

		$result = $this->html->script('http://example.com/jquery.js');
		$expected = '<script src="http://example.com/jquery.js"></script>';
		$this->assertEqual($result, $expected);

		$result = $this->html->script('//example.com/jquery.js');
		$expected = '<script src="//example.com/jquery.js"></script>';
		$this->assertEqual($result, $expected);

		$result = $this->html->script(['prototype', 'scriptaculous']);
		$this->assertPattern(
			'/^\s*<script\s+src=".*js\/prototype\.js"[^<>]*><\/script>/',
			$result
		);
		$this->assertPattern('/<\/script>\s*<script[^<>]+>/', $result);
		$this->assertPattern(
			'/<script\s+src=".*js\/scriptaculous\.js"[^<>]*>' .
			'<\/script>\s*$/',
			$result
		);

		$result = $this->html->script("foo", [
			'async' => true, 'defer' => true, 'onload' => 'init()'
		]);

		$this->assertTags($result, ['script' => [
			'src' => '/js/foo.js',
			'async' => 'async',
			'defer' => 'defer',
			'onload' => 'init()'
		]]);
	}

	/**
	 * Tests generating image tags
	 */
	public function testImage() {
		$result = $this->html->image('test.gif');
		$this->assertTags($result, ['img' => ['src' => '/img/test.gif', 'alt' => '']]);

		$result = $this->html->image('http://example.com/logo.gif');
		$this->assertTags($result, ['img' => [
			'src' => 'http://example.com/logo.gif', 'alt' => ''
		]]);

		$result = $this->html->image([
			'controller' => 'test', 'action' => 'view', 'id' => '1', 'type' => 'gif'
		]);
		$this->assertTags($result, ['img' => ['src' => '/test/view/1.gif', 'alt' => '']]);

		$result = $this->html->image('/test/view/1.gif');
		$this->assertTags($result, ['img' => ['src' => '/test/view/1.gif', 'alt' => '']]);
	}

	/**
	 * Tests inline style linking with <link /> tags
	 */
	public function testStyleLink() {
		$result = $this->html->style('screen');
		$expected = ['link' => [
			'rel' => 'stylesheet', 'href' => 'regex:/.*css\/screen\.css/'
		]];
		$this->assertTags($result, $expected);

		$result = $this->html->style('screen.css');
		$this->assertTags($result, $expected);

		$result = $this->html->style('screen.css?1234');
		$expected['link']['href'] = 'regex:/.*css\/screen\.css\?1234/';
		$this->assertTags($result, $expected);

		$result = $this->html->style('http://whatever.com/screen.css?1234');
		$expected['link']['href'] = 'regex:/http:\/\/.*\/screen\.css\?1234/';
		$this->assertTags($result, $expected);
	}
	/**
	 * Tests generating random tags for the <head> section
	 */
	public function testHead() {
		$result = $this->html->head('meta', ['options' => ['author' => 'foo']]);
		$expected = ['meta' => ['author' => 'foo']];
		$this->assertTags($result, $expected);

		$result = $this->html->head('unexisting-name', [
			'options' => ['author' => 'foo']
		]);
		$this->assertNull($result);
	}

	/**
	 * Tests generating multiple <link /> or <style /> tags in a single call with an array
	 */
	public function testStyleMulti() {
		$result = $this->html->style(['base', 'layout']);
		$expected = [
			'link' => [
				'rel' => 'stylesheet', 'href' => 'regex:/.*css\/base\.css/'
			],
			[
				'link' => [
					'rel' => 'stylesheet',
					'href' => 'regex:/.*css\/layout\.css/'
				]
			]
		];
		$this->assertTags($result, $expected);
	}

	/**
	 * Tests that script and style tags with `'inline'` set to `false` are written to the rendering
	 * context instead of being returned directly.
	 */
	public function testNonInlineScriptsAndStyles() {
		$result = trim($this->context->scripts());
		$this->assertEmpty($result);

		$result = $this->html->script('application', ['inline' => false]);
		$this->assertEmpty($result);

		$result = $this->context->scripts();
		$this->assertTags($result, ['script' => [
			'src' => 'regex:/.*js\/application\.js/'
		]]);

		$result = trim($this->context->styles());
		$this->assertEmpty($result);

		$result = $this->html->style('base', ['inline' => false]);
		$this->assertEmpty($result);

		$result = $this->context->styles();
		$this->assertTags($result, ['link' => [
			'rel' => 'stylesheet', 'href' => 'regex:/.*css\/base\.css/'
		]]);
	}

	/**
	 * Tests that scripts and styles are correctly written to the rendering context even when
	 * passing multiple scripts or styles to a single method call.
	 */
	public function testMultiNonInlineScriptsAndStyles() {
		$result = $this->html->script(['foo', 'bar']);
		$expected = [
			['script' => ['src' => 'regex:/.*\/foo\.js/']],
			'/script',
			['script' => ['src' => 'regex:/.*\/bar\.js/']],
			'/script'
		];
		$this->assertTags($result, $expected);

		$this->assertNull($this->html->script(['foo', 'bar'], ['inline' => false]));
		$result = $this->context->scripts();
		$this->assertTags($result, $expected);
	}

	public function testScopeOption() {
		$result = [];

		$this->context = new MockRenderer([
			'request' => new Request([
				'base' => '', 'host' => 'foo.local'
			]),
			'response' => new Response(),
			'handlers' => [
				'url' => function($url, $ref, array $options = []) use (&$result) {
					$result = compact('options');
				},
				'path' => function($path, $ref, array $options = []) use (&$result) {
					$result = compact('options');
				}
			]
		]);
		$this->html = new Html(['context' => &$this->context]);

		$this->html->link('home', '/home');
		$this->assertFalse(isset($result['options']['scope']));
		$this->html->link('home', '/home', ['scope' => 'app']);
		$this->assertEqual('app', $result['options']['scope']);

		$this->html->link(
			'RSS Feed',
			['controller' => 'posts', 'type' => 'rss'],
			['type' => 'rss']
		);
		$this->assertFalse(isset($result['options']['scope']));
		$this->html->link(
			'RSS Feed',
			['controller' => 'posts', 'type' => 'rss'],
			['type' => 'rss', 'scope' => 'app']
		);
		$this->assertEqual('app', $result['options']['scope']);

		$this->html->script('script.js');
		$this->assertFalse(isset($result['options']['scope']));
		$this->html->script('script.js', ['scope' => 'app']);
		$this->assertEqual('app', $result['options']['scope']);

		$this->html->image('test.gif');
		$this->assertFalse(isset($result['options']['scope']));
		$this->html->image('test.gif', ['scope' => 'app']);
		$this->assertEqual('app', $result['options']['scope']);

		$this->html->style('screen');
		$this->assertFalse(isset($result['options']['scope']));
		$this->html->style('screen', ['scope' => 'app']);
		$this->assertEqual('app', $result['options']['scope']);

		$this->html->link('home', '/home');
		$this->assertFalse(isset($result['options']['scope']));

		$expected = ['app' => ['domain' => 'bob']];
		$this->html->link('home', '/home', ['scope' => $expected]);
		$this->assertEqual($expected, $result['options']['scope']);
	}
}

?>


text:
typedef struct _wasm_instr {
    uint8_t opcode;
    void (*free)(struct _wasm_instr* instr);
    void (*clean)(struct _wasm_instr* instr);
} WasmInstr;

void clean_WasmInstr(WasmInstr* instr);
void free_WasmInstr(WasmInstr* instr);

#endif


text:
Sincere thanks to all the people who have helped make Nitrogen great, including:

+ Rusty Klophaus (@rustyio)
+ Chris Williams (@voodootikigod)
+ Joel Reymont (@wagerlabs)
+ Tom McNulty
+ Martin Scholl (@zeit\_geist)
+ Dave Peticolas
+ Jon Gretar Borgthorsson (@jongretar)
+ Dan Bravender (@dbravender)
+ Taavi Talvik
+ Torbjorn Tornkvist (@kruskakli)
+ Marius A. Eriksen (@marius)
+ Michael Mullis
+ John Dragos
+ Benjamin Nortier (@bjnortier)
+ Jay Doane
+ Robert Schonberger
+ Yurii Rashkovskii (@yrashk)
+ Mrinal Wadha
+ Ville Koivula
+ Manuel Durán Aguete
+ Jesse Gumm (@jessegumm)
+ Jan-Felix Wittmann
+ Martin Sivak
+ Markus Flambard
+ Jonas Ådahl
+ Boris Faure
+ Rajiv M. Ranganath
+ Gregory Haskins
+ Andy Skelton
+ Tino Breddin
+ Dave Peticolas
+ Susan Potter (@susanpotter)
+ Rado Kozmer
+ Ward Bekkar
+ Gleb Peregud
+ Lorant Kurthy
+ Andreas Hasselberg
+ Mattias Holmlund
+ Justin Kirby
+ Tuncer Ayaz
+ Loïc Hoguin (@lhoguin)
+ Sergei Lebedev
+ Stephen Panning
+ James Pharaoh
+ Milan Svoboda
+ Jenő I. Hajdu
+ Maxim Sokhatsky (@5HT)
+ Dmitriy Kargapolov
+ Witeman Zheng
+ Chan Sisowath
+ Florent Gallaire
+ Andrii Zadorozhnii
+ Evan Miller (@evmill)
+ Alice Blitter Copper
+ Roman Shestakov (@rshestakov)
+ Petr Kozorezov
+ Nikolay Garanko
+ Paul Khusainov
+ David N. Welton
+ Tobias Herre
+ Josh Pyle
+ Niclas Axelsson
+ Evgeny M.
+ Boris Resnick
+ Piotr Nosek
+ Stefan Zegenhagen
+ Mehmet Emin Tok
+ Stuart Thackray
+ Amos Oviedo (@fooflare)
+ Alex Popov (@seidlitz)
+ Aaron Frantisak
+ Lloyd R. Prentice.
+ Cameron Frederick (@cammcad)
+ Xue Hongwei
+ Steve Vinoski (@stevevinoski)

Roughly sorted by date of contribution. Send your twitter handles to
[@jessegumm](http://twitter.com/jessegumm)


text:
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifndef BITCOIN_WARNINGS_H
#define BITCOIN_WARNINGS_H

#include <string>

void SetMiscWarning(const std::string& strWarning);
void SetfLargeWorkForkFound(bool flag);
bool GetfLargeWorkForkFound();
void SetfLargeWorkInvalidChainFound(bool flag);
/** Format a string that describes several potential problems detected by the core.
 * @param[in] verbose bool
 * - if true, get all warnings, translated (where possible), separated by <hr />
 * - if false, get the most important warning
 * @returns the warning string
 */
std::string GetWarnings(bool verbose);

extern std::string strMintWarning;
#endif //  BITCOIN_WARNINGS_H


text:
<?php

return array(
'controllers' => array(
		'invokables' => array(
				'Micrositio\Controller\Html' => 'Micrositio\Controller\HtmlController',
                'Facebook\Controller\Facebook' => 'Facebook\Controller\FacebookController',
                'Facebook\Controller\BaseFacebook' => 'Facebook\Controller\BaseFacebookController',
                'Micrositio\Controller\Usuario' => 'Micrositio\Controller\UsuarioController',
                'Micrositio\Controller\Newpyme' => 'Micrositio\Controller\NewpymeController'
		),
),
    'router' => array(
        'routes' => array(
            // The following is a route to simplify getting started creating
            // new controllers and actions without needing to create a new
            // module. Simply drop new controllers in, and you can access them
            // using the path /application/:controller/:action
            'micrositio' => array(
                'type'    => 'Literal',
                'options' => array(
                    'route'    => '/',
                    'defaults' => array(
                        '__NAMESPACE__' => 'Micrositio\Controller',
                        'controller'    => 'Html',
                        'action'        => 'index',
                    ),
                ),
                'may_terminate' => true,
                'child_routes' => array(
                    'default' => array(
                        'type'    => 'Segment',
                        'options' => array(
                            'route'    => '[:pagina][_:action][.:controller][_:id]',
                            'constraints' => array(
                                'controller' => '[a-zA-Z][a-zA-Z0-9-]*',
                                'action'     => '[a-zA-Z][a-zA-Z0-9-]*',
                                'pagina'     => '[a-zA-Z][a-zA-Z0-9-]*'
                            ),
                            'defaults' => array(
                            /*
                            '__NAMESPACE__' => 'Application\Controller',
                            'controller'    => 'Empresa',
                            'action'        => 'index',
                           */
                            ),
                        ),
                    ),
                ),
            ),
        ),
    ),

    'service_manager' => array(
        'factories' => array(
            'translator' => 'Zend\I18n\Translator\TranslatorServiceFactory',
        ),
    ),
    'translator' => array(
        'locale' => 'es_ES',
        'translation_file_patterns' => array(
            array(
                'type'     => 'gettext',
                'base_dir' => __DIR__ . '/../language',
                'pattern'  => '%s.mo',
            ),
        ),
    ),

    'view_manager' => array(
        'display_not_found_reason' => true,
        'display_exceptions'       => true,
        'doctype'                  => 'HTML5',
        'not_found_template'       => 'error/404',
        'exception_template'       => 'error/index',
        'template_map' => array(
            'layout/layout'           => __DIR__ . '/../view/layout/layout.phtml',
            'layout/index'           => __DIR__ . '/../view/layout/index.phtml',
            'micrositio/index/index' => __DIR__ . '/../view/micrositio/index/index.phtml',
            'error/404'               => __DIR__ . '/../view/error/404.phtml',
            'error/index'             => __DIR__ . '/../view/error/index.phtml',
        ),
        'template_path_stack' => array(
            'micrositio'=>__DIR__ . '/../view',
        ),
        'strategies' => array(
            'ViewJsonStrategy',
        ),
    ),
);


text:
"""
Asynchronous Art-Net sender and receiver using Twisted
To do
"""


text:
using System;
using System.Xml;

namespace DbGhost.Build.Extensions
{
    public static class XmlDocumentExtensions
    {
        public static T GetValue<T>(this XmlDocument document, string xpath)
        {
            var value = GetValue(document, xpath);
            if (value == null) return default(T);
            return (T)Convert.ChangeType(value, typeof(T));
        }

        public static string GetValue(this XmlDocument document, string xpath)
        {
            var node = document.SelectSingleNode(xpath);
            if (node != null && node.FirstChild != null) return node.FirstChild.Value;
            return null;
        }

        public static void SetValue<T>(this XmlDocument document, string xpath, T value)
        {
            SetValue(document, xpath, value.ToString());
        }

        public static void SetValue(this XmlDocument document, string xpath, string value)
        {
            if (!value.IsNullOrEmpty(true))
            {
                var node = document.SelectSingleNode(xpath);
                if (node != null)
                    if (node.FirstChild != null)
                        node.FirstChild.Value = value;
                    else
                        node.AppendChild(document.CreateTextNode(value));
            }
        }
    }
}


text:
FindMeFood
==========

Android App that recommends restaurants.


text:
class CCrywolfScoreSort    // Completed
{

public:

    bool operator()(struct OBJECTSTRUCT *const lpObj1, struct OBJECTSTRUCT *const lpObj2) {
        if (lpObj1->Type != OBJ_USER || lpObj2->Type != OBJ_USER) {
            return 0;
        }

        bool bResult = (lpObj1->m_iCrywolfMVPScore >= lpObj2->m_iCrywolfMVPScore) ? TRUE : FALSE;

        if (lpObj1->m_iCrywolfMVPScore == lpObj2->m_iCrywolfMVPScore)
            bResult = (lpObj1->m_PlayerData->Experience < lpObj2->m_PlayerData->Experience) ? TRUE : FALSE;

        return bResult;
    }
};

class CCrywolfUtil {

public:

    CCrywolfUtil();

    virtual ~CCrywolfUtil();

    void __cdecl SendMapServerGroupMsg(LPSTR lpszMsg, ...);

    void SendAllUserAnyData(LPBYTE lpMsg, int iSize);

    void __cdecl SendAllUserAnyMsg(int iType, LPSTR lpszMsg, ...);

    void SendCrywolfUserAnyData(LPBYTE lpMsg, int iSize);

    void __cdecl SendCrywolfUserAnyMsg(int iType, LPSTR lpszMsg, ...);

    void __cdecl SendCrywolfChattingMsg(int iObjIndex, LPSTR lpszMsg, ...);

    int CrywolfMVPLevelUp(int iUserIndex, int iAddExp);

};

extern CCrywolfUtil UTIL;
#endif // !defined(AFX_CRYWOLFUTIL_H__8D1A179E_3D04_4578_A15B_3DAD0E55783B__INCLUDED_)


text:
package org.pentaho.di.concurrency;

import com.google.common.base.Throwables;
import org.junit.Assert;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * This class is aimed to be a general runner for concurrency tests. You need to follow a convention while using it. By
 * it, there are two types of actors in multithreaded environment: monitored and background. The formers are active and
 * are considered to do some mutations of class undergoing testing. The latter group is all about accessors, that
 * normally should not change the state, but just ask for some information, e.g. invoke getters.
 *

 * There is a special condition flag, shared among all actors. Each of them must stop when it has found out the flag has
 * been cleared. Also, in most cases it makes sense to clear the flag after any exception has raised (see {@linkplain
 * StopOnErrorCallable}, because any actor can face with it in concurrency environment.
 *

 * The runner stores results of all actors, though in most cases this information is needless - what is important that
 * is the fact the execution has completed with no errors.
 *
 * @author Andrey Khayrutdinov
 */
class ConcurrencyTestRunner<M, B> {

  /**
   * Runs all tasks and simply checks no exceptions were thrown during the execution. The timeout is 5 minutes.
   *
   * @param monitoredTasks  active actors
   * @param backgroundTasks background actors
   * @param condition       stop condition
   * @throws Exception exception
   */
  @SuppressWarnings( "unchecked" )
  static void runAndCheckNoExceptionRaised( List<? extends Callable<?>> monitoredTasks,
                                            List<? extends Callable<?>> backgroundTasks,
                                            AtomicBoolean condition ) throws Exception {
    ConcurrencyTestRunner<?, ?> runner = new ConcurrencyTestRunner( monitoredTasks, backgroundTasks, condition );
    runner.runConcurrentTest();
    runner.checkNoExceptionRaised();
  }

  private final List<? extends Callable<? extends M>> monitoredTasks;
  private final List<? extends Callable<? extends B>> backgroundTasks;
  private final AtomicBoolean condition;

  private final long timeout;

  private final Map<Callable<? extends M>, ExecutionResult<M>> monitoredResults;
  private final Map<Callable<? extends B>, ExecutionResult> backgroundResults;

  private Exception exception;

  ConcurrencyTestRunner( List<? extends Callable<? extends M>> monitoredTasks,
                         List<? extends Callable<? extends B>> backgroundTasks,
                         AtomicBoolean condition ) {
    this( monitoredTasks, backgroundTasks, condition, TimeUnit.MINUTES.toMillis( 5 ) );
  }

  ConcurrencyTestRunner( List<? extends Callable<? extends M>> monitoredTasks,
                         List<? extends Callable<? extends B>> backgroundTasks,
                         AtomicBoolean condition,
                         long timeout ) {
    this.monitoredTasks = monitoredTasks;
    this.backgroundTasks = backgroundTasks;
    this.condition = condition;
    this.timeout = timeout;

    this.monitoredResults = new HashMap<Callable<? extends M>, ExecutionResult<M>>( monitoredTasks.size() );
    this.backgroundResults = new HashMap<Callable<? extends B>, ExecutionResult>( backgroundTasks.size() );
  }

  void runConcurrentTest() throws Exception {
    this.exception = null;

    final int tasksAmount = monitoredTasks.size() + backgroundTasks.size();
    final ExecutorService executors = Executors.newFixedThreadPool( tasksAmount );
    try {
      List<Future<? extends B>> background = new ArrayList<Future<? extends B>>( backgroundTasks.size() );
      for ( Callable<? extends B> task : backgroundTasks ) {
        background.add( executors.submit( task ) );
      }

      List<Future<? extends M>> monitored = new ArrayList<Future<? extends M>>( monitoredTasks.size() );
      for ( Callable<? extends M> task : monitoredTasks ) {
        monitored.add( executors.submit( task ) );
      }

      try {
        final long start = System.currentTimeMillis();
        while ( condition.get() && !isDone( monitored ) && checkTimeout( start ) ) {
          Thread.sleep( 200 );
        }
      } catch ( Exception e ) {
        exception = e;
      }
      condition.set( false );

      for ( int i = 0; i < monitored.size(); i++ ) {
        Future<? extends M> future = monitored.get( i );
        monitoredResults.put( monitoredTasks.get( i ), ExecutionResult.from( future ) );
      }

      for ( int i = 0; i < background.size(); i++ ) {
        Future<? extends B> future = background.get( i );
        while ( !future.isDone() ) {
          // wait: condition flag is cleared, thus background tasks must complete by convention
        }
        backgroundResults.put( backgroundTasks.get( i ), ExecutionResult.from( future ) );
      }

    } finally {
      executors.shutdown();
    }
  }

  private boolean isDone( List<? extends Future<?>> futures ) {
    for ( Future<?> future : futures ) {
      if ( !future.isDone() ) {
        return false;
      }
    }
    return true;
  }

  private boolean checkTimeout( long start ) throws TimeoutException {
    if ( this.timeout > 0 ) {
      if ( System.currentTimeMillis() - start > timeout ) {
        throw new TimeoutException( "Execution time limit is exceeded: " + timeout + " ms." );
      }
    }
    return true;
  }

  Exception getException() {
    return exception;
  }

  List<Throwable> getTasksErrors() {
    List<Throwable> errors = new ArrayList<Throwable>();
    errors.addAll( pickupErrors( monitoredResults.values() ) );
    errors.addAll( pickupErrors( backgroundResults.values() ) );
    return errors;
  }

  private List<Throwable> pickupErrors( Collection<? extends ExecutionResult<?>> collection ) {
    List<Throwable> errors = new ArrayList<Throwable>( collection.size() );
    for ( ExecutionResult<?> result : collection ) {
      if ( result.isError() ) {
        errors.add( result.getThrowable() );
      }
    }
    return errors;
  }

  void checkNoExceptionRaised() {
    List<Throwable> errors = getTasksErrors();
    if ( !errors.isEmpty() ) {
      StringBuilder message = new StringBuilder( 1024 );
      message.append( "There are expected no exceptions during the test, but " )
        .append( errors.size() ).append( " raised:" );

      for ( Throwable throwable : errors ) {
        String stacktrace = Throwables.getStackTraceAsString( throwable );
        message.append( '\n' ).append( stacktrace );
      }
      Assert.fail( message.toString() );
    }
  }

  List<M> getMonitoredTasksResults() {
    return pickupResults( monitoredResults.values() );
  }

  private <T> List<T> pickupResults( Collection<? extends ExecutionResult<T>> collection ) {
    List<T> errors = new ArrayList<T>( collection.size() );
    for ( ExecutionResult<T> result : collection ) {
      if ( !result.isError() ) {
        errors.add( result.getResult() );
      }
    }
    return errors;
  }

  Map<Callable<? extends M>, ExecutionResult<M>> getMonitoredResults() {
    return Collections.unmodifiableMap( monitoredResults );
  }
}


text:
Applications package
====================

.. automodule:: conkit.applications
   :members:
   :undoc-members:
   :show-inheritance:

.. toctree::
   :glob:

   generated/conkit.applications.*


text:
using System.Reflection;

namespace AspectCore.Extensions.Reflection
{
    public partial class CustomAttributeReflector
    {
        internal static CustomAttributeReflector Create(CustomAttributeData customAttributeData)
        {
            return ReflectorCacheUtils<CustomAttributeData, CustomAttributeReflector>.GetOrAdd(customAttributeData, data => new CustomAttributeReflector(data));
        }
    }
}


text:
package org.apache.ignite.internal.processors.cache.persistence.defragmentation;

import java.nio.ByteBuffer;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.processors.cache.persistence.pagemem.PageMemoryEx;
import org.apache.ignite.internal.processors.cache.persistence.tree.BPlusTree;
import org.apache.ignite.internal.processors.cache.persistence.tree.io.BPlusIO;
import org.apache.ignite.internal.processors.cache.persistence.tree.io.BPlusLeafIO;
import org.apache.ignite.internal.processors.cache.persistence.tree.io.BPlusMetaIO;
import org.apache.ignite.internal.processors.cache.persistence.tree.io.PageIO;
import org.apache.ignite.internal.util.GridUnsafe;

/** */
public class TreeIterator {
    /** Direct memory buffer with a size of one page. */
    private final ByteBuffer pageBuf;

    /** Offheap page size. */
    private final int pageSize;

    /** */
    public TreeIterator(int size) {
        pageSize = size;

        pageBuf = ByteBuffer.allocateDirect(pageSize);
    }

    /** */
    public <L, T extends L> void iterate(
        BPlusTree<L, T> tree,
        PageMemoryEx pageMemory,
        BPlusTree.TreeRowClosure<L, T> c
    ) throws IgniteCheckedException {
        int grpId = tree.groupId();

        long leafId = findFirstLeafId(grpId, tree.getMetaPageId(), pageMemory);

        long bufAddr = GridUnsafe.bufferAddress(pageBuf);

        while (leafId != 0L) {
            long leafPage = pageMemory.acquirePage(grpId, leafId);

            BPlusIO<L> io;

            try {
                long leafPageAddr = pageMemory.readLock(grpId, leafId, leafPage);

                try {
                    io = PageIO.getBPlusIO(leafPageAddr);

                    assert io instanceof BPlusLeafIO : io;

                    GridUnsafe.copyMemory(leafPageAddr, bufAddr, pageSize);
                }
                finally {
                    pageMemory.readUnlock(grpId, leafId, leafPage);
                }
            }
            finally {
                pageMemory.releasePage(grpId, leafId, leafPage);
            }

            int cnt = io.getCount(bufAddr);

            for (int idx = 0; idx < cnt; idx++)
                c.apply(tree, io, bufAddr, idx);

            leafId = io.getForward(bufAddr);
        }
    }

    /** */
    private long findFirstLeafId(int grpId, long metaPageId, PageMemoryEx partPageMemory) throws IgniteCheckedException {
        long metaPage = partPageMemory.acquirePage(grpId, metaPageId);

        try {
            long metaPageAddr = partPageMemory.readLock(grpId, metaPageId, metaPage);

            try {
                BPlusMetaIO metaIO = PageIO.getPageIO(metaPageAddr);

                return metaIO.getFirstPageId(metaPageAddr, 0);
            }
            finally {
                partPageMemory.readUnlock(grpId, metaPageId, metaPage);
            }
        }
        finally {
            partPageMemory.releasePage(grpId, metaPageId, metaPage);
        }
    }
}


text:
package com.hazelcast.jet.sql.impl.connector.file;

import com.google.common.collect.ImmutableSet;
import com.hazelcast.jet.sql.impl.schema.MappingField;
import com.hazelcast.sql.impl.type.QueryDataType;
import org.junit.Test;

import java.util.List;
import java.util.Set;

import static org.assertj.core.api.Assertions.assertThat;

public class CsvResolverTest {

    @Test
    public void test_resolveFields() {
        // given
        Set<String> headers = ImmutableSet.of("field1", "field2");

        // when
        List<MappingField> fields = CsvResolver.resolveFields(headers);

        // then
        assertThat(fields).hasSize(2);
        assertThat(fields.get(0)).isEqualTo(new MappingField("field1", QueryDataType.VARCHAR));
        assertThat(fields.get(1)).isEqualTo(new MappingField("field2", QueryDataType.VARCHAR));
    }
}


text: XML Pretty Printer for plain Text and HTML


text:
"""
===============
=== Purpose ===
===============

Downloads wiki access logs and stores unprocessed article counts

See also: wiki.py
Note: for maximum portability, this program is compatible with both Python2 and
 Python3 and has no external dependencies (e.g. running on AWS)

=================
=== Changelog ===
=================

2017-02-24 v10
  + compute hmac over returned data
2016-08-14: v9
  * use pageviews instead of pagecounts-raw
2015-08-12: v8
  * Corrected `Influenzalike_illness` to `Influenza-like_illness`
2015-05-21: v7
  * Updated for Python3 and to be directly callable by wiki.py
2015-05-??: v1-v6
  * Original versions
"""

# python 2 and 3
from __future__ import print_function
import sys
if sys.version_info.major == 2:
  # python 2 libraries
  from urllib import urlencode
  from urllib2 import urlopen
else:
  # python 3 libraries
  from urllib.parse import urlencode
  from urllib.request import urlopen

# common libraries
import argparse
import datetime
import hashlib
import hmac
import json
import subprocess
import time
import os
from sys import platform

from . import wiki_util

VERSION = 10
MASTER_URL = 'https://delphi.midas.cs.cmu.edu/~automation/public/wiki/master.php'

def text(data_string):
  return str(data_string.decode('utf-8'))

def data(text_string):
  if sys.version_info.major == 2:
    return text_string
  else:
    return bytes(text_string, 'utf-8')

def get_hmac_sha256(key, msg):
  key_bytes, msg_bytes = key.encode('utf-8'), msg.encode('utf-8')
  return hmac.new(key_bytes, msg_bytes, hashlib.sha256).hexdigest()

def extract_article_counts(filename, language, articles, debug_mode):
  """
  Support multiple languages ('en' | 'es' | 'pt')
  Running time optimized to O(M), which means only need to scan the whole file once
  :param filename:
  :param language: Different languages such as 'en', 'es', and 'pt'
  :param articles:
  :param debug_mode:
  :return:
  """
  counts = {}
  articles_set = set(map(lambda x: x.lower(), articles))
  total = 0
  with open(filename, "r", encoding="utf8") as f:
    for line in f:
      content = line.strip().split()
      if len(content) != 4:
        print('unexpected article format: {0}'.format(line))
        continue
      article_title = content[1].lower()
      article_count = int(content[2])
      if content[0] == language:
        total += article_count
      if content[0] == language and article_title in articles_set:
        if(debug_mode):
          print("Find article {0}: {1}".format(article_title, line))
        counts[article_title] = article_count
  if debug_mode:
    print("Total number of counts for language {0} is {1}".format(language, total))
  counts['total'] = total
  return counts

def extract_article_counts_orig(articles, debug_mode):
  """
  The original method which extracts article counts by shell command grep (only support en articles).
  As it is difficult to deal with other languages (utf-8 encoding), we choose to use python read files.
  Another things is that it is slower to go over the whole file once and once again, the time complexity is O(NM),
  where N is the number of articles and M is the lines in the file
  In our new implementation extract_article_counts(), the time complexity is O(M), and it can cope with utf8 encoding
  :param articles:
  :param debug_mode:
  :return:
  """
  counts = {}
  for article in articles:
    if debug_mode:
      print(' %s' % (article))
    out = text(
      subprocess.check_output('LC_ALL=C grep -a -i "^en %s " raw2 | cat' % (article.lower()), shell=True)).strip()
    count = 0
    if len(out) > 0:
      for line in out.split('\n'):
        fields = line.split()
        if len(fields) != 4:
          print('unexpected article format: [%s]' % (line))
        else:
          count += int(fields[2])
    # print ' %4d %s'%(count, article)
    counts[article.lower()] = count
    if debug_mode:
      print('  %d' % (count))
  print('getting total count...')
  out = text(subprocess.check_output(
    'cat raw2 | LC_ALL=C grep -a -i "^en " | cut -d" " -f 3 | awk \'{s+=$1} END {printf "%.0f", s}\'', shell=True))
  total = int(out)
  if debug_mode:
    print(total)
  counts['total'] = total
  return counts

def run(secret, download_limit=None, job_limit=None, sleep_time=1, job_type=0, debug_mode=False):

  worker = text(subprocess.check_output("echo `whoami`@`hostname`", shell=True)).strip()
  print('this is [%s]'%(worker))
  if debug_mode:
    print('*** running in debug mode ***')

  total_download = 0
  passed_jobs = 0
  failed_jobs = 0
  while (download_limit is None or total_download < download_limit) and (job_limit is None or (passed_jobs + failed_jobs) < job_limit):
    try:
      time_start = datetime.datetime.now()
      req = urlopen(MASTER_URL + '?get=x&type=%s'%(job_type))
      code = req.getcode()
      if code != 200:
        if code == 201:
          print('no jobs available')
          if download_limit is None and job_limit is None:
            time.sleep(60)
            continue
          else:
            print('nothing to do, exiting')
            return
        else:
          raise Exception('server response code (get) was %d'%(code))
      # Make the code compatible with mac os system
      if platform == "darwin":
        job_content = text(req.readlines()[1])
      else:
        job_content = text(req.readlines()[0])
      if job_content == 'no jobs':
        print('no jobs available')
        if download_limit is None and job_limit is None:
          time.sleep(60)
          continue
        else:
          print('nothing to do, exiting')
          return
      job = json.loads(job_content)
      print('received job [%d|%s]'%(job['id'], job['name']))
      # updated parsing for pageviews - maybe use a regex in the future
      #year, month = int(job['name'][11:15]), int(job['name'][15:17])
      year, month = int(job['name'][10:14]), int(job['name'][14:16])
      #print 'year=%d | month=%d'%(year, month)
      url = 'https://dumps.wikimedia.org/other/pageviews/%d/%d-%02d/%s'%(year, year, month, job['name'])
      print('downloading file [%s]...'%(url))
      subprocess.check_call('curl -s %s > raw.gz'%(url), shell=True)
      print('checking file size...')
      # Make the code cross-platfrom, so use python to get the size of the file
      # size = int(text(subprocess.check_output('ls -l raw.gz | cut -d" " -f 5', shell=True)))
      size = os.stat("raw.gz").st_size
      if debug_mode:
        print(size)
      total_download += size
      if job['hash'] != '00000000000000000000000000000000':
        print('checking hash...')
        out = text(subprocess.check_output('md5sum raw.gz', shell=True))
        result = out[0:32]
        if result != job['hash']:
          raise Exception('wrong hash [expected %s, got %s]'%(job['hash'], result))
        if debug_mode:
          print(result)
      print('decompressing...')
      subprocess.check_call('gunzip -f raw.gz', shell=True)
      #print 'converting case...'
      #subprocess.check_call('cat raw | tr "[:upper:]" "[:lower:]" > raw2', shell=True)
      #subprocess.check_call('rm raw', shell=True)
      subprocess.check_call('mv raw raw2', shell=True)
      print('extracting article counts...')

      # Use python to read the file and extract counts, if you want to use the original shell method, please use
      counts = {}
      for language in wiki_util.Articles.available_languages:
        lang2articles = {'en': wiki_util.Articles.en_articles, 'es': wiki_util.Articles.es_articles, 'pt': wiki_util.Articles.pt_articles}
        articles = lang2articles[language]
        articles = sorted(articles)
        if debug_mode:
          print("Language is {0} and target articles are {1}".format(language, articles))
        temp_counts = extract_article_counts("raw2", language, articles, debug_mode)
        counts[language] = temp_counts

      if not debug_mode:
        print('deleting files...')
        subprocess.check_call('rm raw2', shell=True)
      print('saving results...')
      time_stop = datetime.datetime.now()
      result = {
        'id': job['id'],
        'size': size,
        'data': json.dumps(counts),
        'worker': worker,
        'elapsed': (time_stop - time_start).total_seconds(),
      }
      payload = json.dumps(result)
      hmac_str = get_hmac_sha256(secret, payload)
      if debug_mode:
        print(' hmac: %s' % hmac_str)
      post_data = urlencode({'put': payload, 'hmac': hmac_str})
      req = urlopen(MASTER_URL, data=data(post_data))
      code = req.getcode()
      if code != 200:
        raise Exception('server response code (put) was %d'%(code))
      print('done! (dl=%d)'%(total_download))
      passed_jobs += 1
    except Exception as ex:
      print('***** Caught Exception: %s *****'%(str(ex)))
      failed_jobs += 1
      time.sleep(30)
    print('passed=%d | failed=%d | total=%d'%(passed_jobs, failed_jobs, passed_jobs + failed_jobs))
    time.sleep(sleep_time)

  if download_limit is not None and total_download >= download_limit:
    print('download limit has been reached [%d >= %d]'%(total_download, download_limit))
  if job_limit is not None and (passed_jobs + failed_jobs) >= job_limit:
    print('job limit has been reached [%d >= %d]'%(passed_jobs + failed_jobs, job_limit))

def main():
  # version info
  print('version', VERSION)

  # args and usage
  parser = argparse.ArgumentParser()
  parser.add_argument('secret', type=str, help='hmac secret key')
  parser.add_argument('-b', '--blimit', action='store', type=int, default=None, help='download limit, in bytes')
  parser.add_argument('-j', '--jlimit', action='store', type=int, default=None, help='job limit')
  parser.add_argument('-s', '--sleep', action='store', type=int, default=1, help='seconds to sleep between each job')
  parser.add_argument('-t', '--type', action='store', type=int, default=0, help='type of job')
  parser.add_argument('-d', '--debug', action='store_const', const=True, default=False, help='enable debug mode')
  args = parser.parse_args()

  # runtime options
  secret, download_limit, job_limit, sleep_time, job_type, debug_mode = args.secret, args.blimit, args.jlimit, args.sleep, args.type, args.debug

  # run
  run(secret, download_limit, job_limit, sleep_time, job_type, debug_mode)

if __name__ == '__main__':
  main()


text:
#include "function.h"
#include <math.h>

class fcnPurelin : public Function
{
public:
    double evaluate(double input);
    double evalDeriv(double input);
};