text:
<?php

namespace OAuth2\ResponseType;

use OAuth2\Encryption\EncryptionInterface;
use OAuth2\Encryption\Jwt;
use OAuth2\Storage\AccessTokenInterface as AccessTokenStorageInterface;
use OAuth2\Storage\RefreshTokenInterface;
use OAuth2\Storage\PublicKeyInterface;
use OAuth2\Storage\Memory;

/**
 * @author Brent Shaffer <bshafs at gmail dot com>
 */
class JwtAccessToken extends AccessToken
{
    protected $publicKeyStorage;
    protected $encryptionUtil;

    /**
     * @param PublicKeyInterface          $publicKeyStorage -
     * @param AccessTokenStorageInterface $tokenStorage     -
     * @param RefreshTokenInterface       $refreshStorage   -
     * @param array                       $config           - array with key store_encrypted_token_string (bool true)
     *                                                        whether the entire encrypted string is stored,
     *                                                        or just the token ID is stored
     * @param EncryptionInterface         $encryptionUtil   -
     */
    public function __construct(PublicKeyInterface $publicKeyStorage = null, AccessTokenStorageInterface $tokenStorage = null, RefreshTokenInterface $refreshStorage = null, array $config = array(), EncryptionInterface $encryptionUtil = null)
    {
        $this->publicKeyStorage = $publicKeyStorage;
        $config = array_merge(array(
            'store_encrypted_token_string' => true,
            'issuer' => ''
        ), $config);
        if (is_null($tokenStorage)) {
            // a pass-thru, so we can call the parent constructor
            $tokenStorage = new Memory();
        }
        if (is_null($encryptionUtil)) {
            $encryptionUtil = new Jwt();
        }
        $this->encryptionUtil = $encryptionUtil;
        parent::__construct($tokenStorage, $refreshStorage, $config);
    }

    /**
     * Handle the creation of access token, also issue refresh token if supported / desirable.
     *
     * @param mixed  $client_id           - Client identifier related to the access token.
     * @param mixed  $user_id             - User ID associated with the access token
     * @param string $scope               - (optional) Scopes to be stored in space-separated string.
     * @param bool   $includeRefreshToken - If true, a new refresh_token will be added to the response
     * @return array                      - The access token
     *
     * @see http://tools.ietf.org/html/rfc6749#section-5
     * @ingroup oauth2_section_5
     */
    public function createAccessToken($client_id, $user_id, $scope = null, $includeRefreshToken = true)
    {
        // payload to encrypt
        $payload = $this->createPayload($client_id, $user_id, $scope);

        /*
         * Encode the payload data into a single JWT access_token string
         */
        $access_token = $this->encodeToken($payload, $client_id);

        /*
         * Save the token to a secondary storage.  This is implemented on the
         * OAuth2\Storage\JwtAccessToken side, and will not actually store anything,
         * if no secondary storage has been supplied
         */
        $token_to_store = $this->config['store_encrypted_token_string'] ? $access_token : $payload['id'];
        $this->tokenStorage->setAccessToken($token_to_store, $client_id, $user_id, $this->config['access_lifetime'] ? time() + $this->config['access_lifetime'] : null, $scope);

        // token to return to the client
        $token = array(
            'access_token' => $access_token,
            'expires_in' => $this->config['access_lifetime'],
            'token_type' => $this->config['token_type'],
            'scope' => $scope
        );

        /*
         * Issue a refresh token also, if we support them
         *
         * Refresh Tokens are considered supported if an instance of OAuth2\Storage\RefreshTokenInterface
         * is supplied in the constructor
         */
        if ($includeRefreshToken && $this->refreshStorage) {
            $refresh_token = $this->generateRefreshToken();
            $expires = 0;
            if ($this->config['refresh_token_lifetime'] > 0) {
                $expires = time() + $this->config['refresh_token_lifetime'];
            }
            $this->refreshStorage->setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope);
            $token['refresh_token'] = $refresh_token;
        }

        return $token;
    }

    /**
     * @param array $token
     * @param mixed $client_id
     * @return mixed
     */
    protected function encodeToken(array $token, $client_id = null)
    {
        $private_key = $this->publicKeyStorage->getPrivateKey($client_id);
        $algorithm   = $this->publicKeyStorage->getEncryptionAlgorithm($client_id);

        return $this->encryptionUtil->encode($token, $private_key, $algorithm);
    }

    /**
     * This function can be used to create custom JWT payloads
     *
     * @param mixed  $client_id           - Client identifier related to the access token.
     * @param mixed  $user_id             - User ID associated with the access token
     * @param string $scope               - (optional) Scopes to be stored in space-separated string.
     * @return array                      - The access token
     */
    protected function createPayload($client_id, $user_id, $scope = null)
    {
        // token to encrypt
        $expires = time() + $this->config['access_lifetime'];
        $id = $this->generateAccessToken();

        $payload = array(
            'id'         => $id, // for BC (see #591)
            'jti'        => $id,
            'iss'        => $this->config['issuer'],
            'aud'        => $client_id,
            'sub'        => $user_id,
            'exp'        => $expires,
            'iat'        => time(),
            'token_type' => $this->config['token_type'],
            'scope'      => $scope
        );

        if (isset($this->config['jwt_extra_payload_callable'])) {
            if (!is_callable($this->config['jwt_extra_payload_callable'])) {
                throw new \InvalidArgumentException('jwt_extra_payload_callable is not callable');
            }

            $extra = call_user_func($this->config['jwt_extra_payload_callable'], $client_id, $user_id, $scope);

            if (!is_array($extra)) {
                throw new \InvalidArgumentException('jwt_extra_payload_callable must return array');
            }

            $payload = array_merge($extra, $payload);
        }

        return $payload;
    }
}


text:
package com.artemis.generator.strategy.e;

/**
 * @author Daan van Yperen
 */
public interface ProofInterface<T> {

    T pancake(T t);
}

redpajama_set_name: RedPajamaGithub


text:
import React from 'react'
import Retweet from './retweet'
import Tweet from './tweet'

export default class Tweets extends React.Component {
  render() {
    return(
      <div className="tweets">
        {this.renderTweets()}
      </div>
    );
  }

  renderTweets() {
    return this.props.tweets.map((tweet) => {
      if (tweet.retweeted_status) {
        return <Retweet key={tweet.id_str} onAnchorClicked={this.props.onAnchorClicked} tweet={tweet} />
      } else {
        return <Tweet key={tweet.id_str} onAnchorClicked={this.props.onAnchorClicked} tweet={tweet} />
      }
    });
  }
}


text:
using System.Web;
using System.Web.Optimization;

namespace Contoso.Events.Web
{
    public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/scripts/jquery").Include(
                        "~/Scripts/jquery-{version}.js",
                        "~/Scripts/jquery.moreLink.js"));

            bundles.Add(new ScriptBundle("~/scripts/bootstrap").Include(
                      "~/Scripts/bootstrap.js"));

            bundles.Add(new StyleBundle("~/styles/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));
        }
    }
}


text:
package sleep;

public class RandomNumberThread extends Thread{

	@Override
	public void run(){
		for(int x = 0; x< 10; x++){
			int number = (int)(Math.random()*10);
			System.out.println(Thread.currentThread().getName()+" -> "+number);
			try{

				Thread.sleep(number*100);
			}catch(Exception e){
				System.out.println("Interrupted Exception "+e.getMessage());
			}
		}
	}
}


text:
using System.Collections.Generic;
using System.Security.Claims;

namespace SsoClient.ViewModels
{
    public class UserViewModel
    {
        public string UserName { get; set; }
        public IEnumerable<Claim> Claims { get; set; }
    }
}


text:
"""Soccerway scraping module.

Note: on soccerway, a competition is divided in multiple phases, which
itself contains multiple games.

TODO Explain the following types of pages:

- person
- player (needless - person is more refined)
- team
- match
- competition (needless - season is more refined)
- season
- round
- group (needless - just a filter on `round`)
"""

import itertools
import json
import re

from datetime import datetime
from lxml import etree
from ._utils import BasePage, int_or_none

class SoccerwayPage(BasePage):

    @classmethod
    def make_url(cls, swid):
        return cls.URL_TEMPLATE.format(swid=swid)

class MatchPage(SoccerwayPage):

    URL_TEMPLATE = "https://int.soccerway.com/matches/0000/00/00/-/-/-/-/{swid}/"

    def __init__(self, data):
        # Getting rid of annoying non-breaking spaces.
        data = data.replace(' ', " ")
        self.tree = etree.HTML(data)
        super().__init__(data)

    @property
    def swid(self):
        elem = self.tree.xpath('//link[@rel="canonical"]')[0]
        match = re.match(r'.*/(?P<swid>\d+)/', elem.get("href"))
        return int(match.group('swid'))

    @property
    def competition_swid(self):
        elem = self.tree.xpath('//ul[@class="left-tree"]'
                '/li[contains(@class, "expanded")]/a')[0]
        match = re.match(r'.*/c(?P<swid>\d+)/', elem.get("href"))
        return int(match.group('swid'))

    @property
    def info(self):
        attr = dict()
        div = self.tree.xpath('//div[contains(@class, "details")]')[0]
        elems = div.xpath('./a//text()')
        # Date.
        attr['date'] = datetime.strptime(elems[0], '%d/%m/%Y').date()
        # Competition.
        attr['competition'] = elems[1]
        # Kick-off time.
        elems = div.xpath('./span[text()="KO"]')
        if len(elems) > 0:
            span = elems[0].getnext().getchildren()[0]
            attr["timestamp"] = int(span.get('data-value'))
        else:
            # Back to the "details" div.
            span = div.xpath('//span[@class="timestamp"]')[0]
            attr["timestamp"] = int(span.get('data-value'))
        # Venue.
        elems = div.xpath('./span[text()="Venue"]')
        if len(elems) > 0:
            attr["venue"] = "".join(elems[0].getnext().itertext())
        # Teams.
        for i, elem in zip((1, 2), self.tree.xpath('//a[@class="team-title"]')):
            attr['team{}_name'.format(i)] = elem.text
            match = re.match(r'.*/(?P<swid>\d+)/', elem.get('href'))
            attr['team{}_swid'.format(i)] = int(match.group('swid'))
        return attr

    @property
    def scores(self):
        elems = self.tree.xpath('//h3[contains(@class,"scoretime")]')
        if len(elems) == 0:
            return {}  # No score information (e.g., match cancelled).
        text = etree.tostring(elems[0], method='text').decode()
        text = text.replace("&nbsp", "")  # Get rid of invalid HTML.
        text = re.sub(r'\s+', ' ', text).strip()  # Collapse multiple white space.
        # Examples:
        #
        #     AET E 2 - 1 E (FT 1 - 1)
        #     FT 1 - 1
        #     AET P 1 - 1 P (FT 1 - 1) (PEN 6 - 5)
        #     FT 2 - 1 (HT 1 - 0)
        match = re.match(
            r'(?P<t1>FT|AET) (?:(?:E|P) )?'  #  Score 1: FT or ET
            r'(?P<s1a>\d+) - (?P<s1b>\d+)(?: (?:E|P))?'  # Actual score 1.
            r'(?: \((?P<t2>HT|FT) (?P<s2a>\d+) - (?P<s2b>\d+)\))?'  # Score 2.
            r'(?: \(PEN (?P<s3a>\d+) - (?P<s3b>\d+)\))?',  # Score 3.
            text)
        attr = dict()
        # Score 1
        if match.group('t1') == 'FT':
            attr['score_ft_team1'] = int(match.group('s1a'))
            attr['score_ft_team2'] = int(match.group('s1b'))
        else:  # match.group('t1') == "AET":
            attr['score_et_team1'] = int(match.group('s1a'))
            attr['score_et_team2'] = int(match.group('s1b'))
        # Score 2
        if match.group('t2') == 'FT':
            attr['score_ft_team1'] = int(match.group('s2a'))
            attr['score_ft_team2'] = int(match.group('s2b'))
        elif match.group('t2') == 'HT':
            attr['score_ht_team1'] = int(match.group('s2a'))
            attr['score_ht_team2'] = int(match.group('s2b'))
        # Score 3
        if match.group('s3a') is not None:
            attr['score_kfpm_team1'] = int(match.group('s3a'))
            attr['score_kfpm_team2'] = int(match.group('s3b'))
        return attr

    def _parse_player_item(self, tr):
        attr = dict()
        # Shirt number.
        elems = tr.xpath('./td[@class="shirtnumber"]')
        if len(elems) > 0 and elems[0].text is not None and elems[0].text != " ":
            attr['shirt_number'] = int(elems[0].text)
        # Display name and Soccerway ID.
        elems = tr.xpath('./td[contains(@class,"player")]//a')
        if len(elems) > 0:
            attr['display_name'] = elems[0].text
            match = re.match(r'.*/(?P<swid>\d+)/', elems[0].get('href'))
            attr['swid'] = int(match.group('swid'))
        else:
            # Not a player (maybe a coach, an empty row, ...)
            return None
        # Substitution.
        elems = tr.xpath(
            './td[contains(@class,"player")]//img[@title="Substituted"]')
        if len(elems) > 0:
            match = re.match(r'.*/(?P<what>S[IO]).png', elems[0].get('src'))
            if match.group("what") == "SO":
                # Substitute out.
                attr['subst_out'] = -1  # For legacy reasons (used to be minute).
            elif match.group("what") == "SI":
                # Substitute in.
                attr['subst_in'] = -1  # For legacy reasons (used to be minute).
        # Game events (goals, cards, etc.).
        attr['events'] = list()
        mapping = {
            'G': 'Goal',
            'OG': 'Own goal',
            'PG': 'Penalty goal',
            'PM': 'Penalty missed',
            'YC': 'Yellow card',
            'Y2C': 'Yellow 2nd/RC',
            'RC': 'Red card',
        }
        elems = tr.xpath('./td[@class="bookings"]/span/img')
        for elem in elems:
            match = re.match(r'.*events/(?P<what>.+).png', elem.get('src'))
            event = {'type': mapping[match.group('what')]}
            match = re.match(r'(?P<when>\d+).+', elem.tail.strip())
            if match is not None:
                event['minute'] = int(match.group('when'))
            attr['events'].append(event)
        return attr

    @property
    def starters(self):
        starters = {'team1': list(), 'team2': list()}
        for team, cls in (("team1", "left"), ("team2", "right")):
            for tr in self.tree.xpath(
                    '//div[@class="container {}"]'
                    '/table[@class="playerstats lineups table"]'
                    '/tbody/tr'.format(cls)):
                attr = self._parse_player_item(tr)
                if attr is not None:
                    starters[team].append(attr)
        return starters

    @property
    def substitutes(self):
        substitutes = {'team1': list(), 'team2': list()}
        for team, cls in (("team1", "left"), ("team2", "right")):
            for tr in self.tree.xpath(
                    '//div[@class="container {}"]'
                    '/table[contains(@class, "substitutions")]'
                    '/tbody/tr'.format(cls)):
                attr = self._parse_player_item(tr)
                substitutes[team].append(attr)
        return substitutes

    @property
    def coaches(self):
        coaches = {'team1': list(), 'team2': list()}
        for team, cls in (("team1", "left"), ("team2", "right")):
            for elem in self.tree.xpath(
                    '//div[@class="container {}"]'
                    '/table[@class="playerstats lineups table"]'
                    '/tbody/tr/td/strong[text()="Coach:"]'.format(cls)):
                a = elem.getnext()
                match = re.match(r'.*/(?P<swid>\d+)/', a.get('href'))
                coaches[team].append({
                    'display_name': a.text,
                    'swid': int(match.group('swid'))
                })
        return coaches

class PersonPage(SoccerwayPage):

    URL_TEMPLATE = "https://int.soccerway.com/players/-/{swid}/"

    def __init__(self, data):
        # Getting rid of annoying non-breaking spaces.
        data = data.replace(' ', " ")
        self.tree = etree.HTML(data)
        super().__init__(data)

    @property
    def swid(self):
        elem = self.tree.xpath('//table[@data-people_id]')[0]
        return int(elem.get("data-people_id"))

    @property
    def passport(self):
        attr = dict()
        elem = self.tree.xpath('//h1')[0]
        attr['display_name'] = elem.text
        mapping = { # Maps description string to dict key.
            'First name': 'first_name',
            'Last name': 'last_name',
            'Nationality': 'nationality',
            'Date of birth': 'birthdate',
            'Age': 'age',
            'Country of birth': 'birthcountry',
            'Place of birth': 'birthplace',
            'Position': 'position',
            'Height': 'height',
            'Weight': 'weight',
            'Foot': 'foot',
        }
        for elem in self.tree.xpath('//dt'):
            if elem.text in mapping:
                key = mapping[elem.text]
                val = elem.getnext().text
                if key in ('height', 'weight'):
                    val = int(val.split(" ")[0])
                elif key == 'age':
                    val = int(val)
                elif key == 'birthdate':
                    val = datetime.strptime(val, "%d %B %Y").date()
                attr[key] = val
        return attr

class TeamPage(SoccerwayPage):

    URL_TEMPLATE = "https://int.soccerway.com/teams/-/-/{swid}/"

    def __init__(self, data):
        # Getting rid of annoying non-breaking spaces.
        data = data.replace(' ', " ")
        self.tree = etree.HTML(data)
        super().__init__(data)

    @property
    def swid(self):
        elem = self.tree.xpath('//link[@rel="canonical"]')[0]
        match = re.match(r'.*/(?P<swid>\d+)/', elem.get("href"))
        return int(match.group('swid'))

    @property
    def country(self):
        # Pattern: `<dt>Country</dt><dd>Chile</dd>`.
        elem = self.tree.xpath('//dt[text()="Country"]')[0]
        return elem.getnext().text

    @property
    def name(self):
        attr = self.tree.xpath('//div[@class="logo"]/img/@alt')[0]
        return str(attr)

class MatchListPage(SoccerwayPage):

    def __init__(self, data):
        data = data.replace(' ', " ")
        self.tree = etree.HTML(data)
        super().__init__(data)

    @property
    def matches(self):
        table = self.tree.xpath('//table[contains(@class, "matches")]')[0]
        return MatchesBlock.parse_matches(table)

    @property
    def rounds(self):
        for option in self.tree.xpath('//select[@name="round_id"]/option'):
            match = re.match(r'.*/r(?P<swid>\d+)/',
                             option.get("value"))
            yield {
                'name': option.text,
                'swid': int(match.group('swid')),
            }

    @property
    def seasons(self):
        for option in self.tree.xpath('//select[@name="season_id"]/option'):
            match = re.match(r'.*/s(?P<swid>\d+)/',
                             option.get("value"))
            yield {
                'name': option.text,
                'swid': int(match.group('swid')),
            }

    @property
    def is_paginated(self):
        elems = self.tree.xpath('//div[@class="page-dropdown-container"]')
        return len(elems) > 0

    @property
    def competition_swid(self):
        elem = self.tree.xpath('//div[@data-competitionids]')[0]
        return int(elem.get("data-competitionids"))

    @property
    def season_swid(self):
        attr = self.tree.xpath('//select[@name="season_id"]'
                               '/option[@selected]/@value')[0]
        match = re.match(r'.*/s(?P<swid>\d+)/', attr)
        return int(match.group('swid'))

    @property
    def round_swid(self):
        elems = self.tree.xpath(
            '//select[@name="round_id"]/option[@selected]/@value')
        if len(elems) > 0:
            # This approach seems more robust.
            match = re.match(r'.*/r(?P<swid>\d+)/', elems[0])
            return int(match.group('swid'))
        else:
            # Fallback when there is no selected round.
            elems = self.tree.xpath(
                '//div[@id="submenu"]/ul/li/a[text()="Summary"]/@href')
            match = re.match(r'.*/r(?P<swid>\d+)/', elems[0])
            return int(match.group('swid'))

class CompetitionPage(MatchListPage):

    URL_TEMPLATE = "https://int.soccerway.com/national/-/-/c{swid}/"

    @property
    def swid(self):
        return self.competition_swid

class SeasonPage(MatchListPage):

    URL_TEMPLATE = "https://int.soccerway.com/national/-/-/-/s{swid}/"

    @property
    def swid(self):
        return self.season_swid

class RoundPage(MatchListPage):

    URL_TEMPLATE = "https://int.soccerway.com/national/-/-/-/-/r{swid}/"

    @property
    def swid(self):
        return self.round_swid

class MatchesBlock(BasePage):

    URL_TEMPLATE = (
        'https://int.soccerway.com/a/block_competition_matches_summary?block_id='
        '&callback_params={{'
            '"page":0,'
            '"block_service_id":"competition_summary_block_competitionmatchessummary",'
            '"round_id":{swid},'
            '"outgroup":false,'
            '"view":0,'
            '"competition_id":0'
        '}}&action=changePage&params={{"page":{page}}}'
    )

    def __init__(self, data):
        self.json = json.loads(data)
        super().__init__(data)

    @property
    def matches(self):
        content = self.json["commands"][0]["parameters"]["content"]
        table = etree.HTML(content)
        return MatchesBlock.parse_matches(table)

    @property
    def round_swid(self):
        params = self.json["commands"][2]["parameters"]["params"]
        return int(params["round_id"])

    @property
    def page(self):
        params = self.json["commands"][2]["parameters"]["params"]
        return int(params["page"])

    @property
    def has_previous(self):
        attr = self.json["commands"][1]["parameters"]["attributes"]
        return attr["has_previous_page"] == "1"

    @property
    def has_next(self):
        attr = self.json["commands"][1]["parameters"]["attributes"]
        return attr["has_next_page"] == "1"

    @staticmethod
    def parse_matches(table):
        for tr in table.xpath('//tbody/tr[contains(@class, "match")]'):
            match_info = dict()
            # Get the timestamp.
            match_info['timestamp'] = int(tr.get("data-timestamp"))
            # Get the Soccerway ID.
            elem = tr.xpath('./td[contains(@class, "score-time")]/a')[0]
            match = re.match(r'.*/(?P<swid>\d+)/', elem.get("href"))
            if match is None:
                continue
            match_info['swid'] = int(match.group('swid'))
            # Try to get the score.
            elems = tr.xpath('./td//span[@class="extra_time_score"]')
            if len(elems) > 0:
                scores = list(map(int, elems[0].text.split(" - ")))
            else:
                scores = None
            # Process each team.
            for team, cls in (('team1', 'team-a'), ('team2', 'team-b')):
                elem = tr.xpath('./td[contains(@class, "{}")]/a'.format(cls))[0]
                match = re.match(r'.*/(?P<swid>\d+)/', elem.get("href"))
                match_info[team] = {
                    'name': elem.text.strip(),
                    'swid': int(match.group('swid')),
                }
            if scores is not None:
                match_info['team1']['goals'] = scores[0]
                match_info['team2']['goals'] = scores[1]
            yield match_info

    @classmethod
    def for_round(cls, swid):
        for i in itertools.count(0, -1):
            yield cls.URL_TEMPLATE.format(swid=swid, page=i)


text:
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace Pocal.Converter
{
    public class OverviewFirstLineX : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return App.ViewModel.IsInOverviewModus() ? Application.Current.Resources["OverviewStartTimeX"] : 0;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }

    public class OverviewStartTimeOpacity : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return App.ViewModel.IsInOverviewModus() ? 0.7 : 1;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }

    public class OverviewStartTimeScale : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return App.ViewModel.IsInOverviewModus() ? 1.6 : 1;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }

    public class OverviewSecondLineOpacity : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return App.ViewModel.IsInOverviewModus() ? 0 : 1;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }

    public class OverviewSecondLineSale : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return App.ViewModel.IsInOverviewModus() ? 1.6 : 1;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }
}


text:
package me.spyboat.core;

import java.util.ArrayList;

public class Unit {
  public ArrayList<Affect> affects;
  public int baseMoveRate, baseMaxSize;
  public String name, description;

  public Unit(ArrayList<Affect> affects, int baseMoveRate, int baseMaxSize,
      String name, String description) {
    this.affects = affects;
    this.baseMoveRate = baseMoveRate;
    this.baseMaxSize = baseMaxSize;
    this.name = name;
    this.description = description;
  }
}


text:
module Kobol::Requests
  class Issues < Kobol::Requests::Base
    PERMITTED = [ :language, :label, :repo ]

    def search(properties, page)
      updated_after_date = Date.today << 3

      set_response(client.search_issues("#{search_params(properties)} type:issue archived:false state:open updated:>#{updated_after_date}", page: page, per_page: 100))
    end

    def total
      @total ||= response[:total_count]
    end

    def issues
      @issues ||= response[:items].map {|issue| parse_issue(issue) }
    end

    private

    def parse_issue issue
      Kobol::Presenters::Issue.new(title: issue.title,
                                   labels: issue.labels,
                                   body: issue.body,
                                   comments: issue.comments,
                                   updated_at: issue.updated_at,
                                   url: issue._rels[:html].href)
    end

    def search_params(search_params)
      raise Exception, "Pick a label to get started" if search_params[:label].empty?
      response = search_params.map {|key,values| values.map {|value| %{#{key}:"#{value.strip}"} }}.join(" ").strip
      response
    end
  end
end


text:
module ResasHelper
end


text:
package org.apache.flume.channel.file;

import java.util.concurrent.atomic.AtomicLong;

public final class WriteOrderOracle {

  private WriteOrderOracle() {
  }

  private static final AtomicLong WRITER_ORDERER =
      new AtomicLong(System.currentTimeMillis());

  public static void setSeed(long highest) {
    long previous;
    while (highest > (previous = WRITER_ORDERER.get())) {
      WRITER_ORDERER.compareAndSet(previous, highest);
    }
  }

  public static long next() {
    return WRITER_ORDERER.incrementAndGet();
  }
}


text:
import { Runner } from 'lsk-build'
import config from './config'
import webpackConfig from './webpack.config'

const ctx = config
ctx.webpackConfig = webpackConfig
const app = new Runner(ctx)
if (process.argv.length > 2) {
  const method = process.argv[2]
  app[method]().catch(err => console.error(err.stack));
}


text:
//
//  YKYouTubeVideo.h
//  YKMediaHelper
//
//  Created by Yas Kuraishi on 3/13/14.
//  Copyright (c) 2014 Yas Kuraishi. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "YKVideo.h"

@interface YKYouTubeVideo : NSObject<YKVideo>

/**
 Vimeo video url
 */
@property (nonatomic, strong) NSURL *contentURL;

/**
 Videos found for above mentioned content url.
 Available after parseWithCompletion is executed.
 */
@property (nonatomic, strong) NSDictionary *videos;

@end


text:
package org.vaadin.netbeans.editor.hints;

import org.netbeans.spi.editor.hints.ErrorDescription;
import org.netbeans.spi.editor.hints.Severity;
import org.netbeans.spi.java.hints.Hint;
import org.netbeans.spi.java.hints.Hint.Options;
import org.netbeans.spi.java.hints.HintContext;
import org.netbeans.spi.java.hints.TriggerTreeKind;
import org.vaadin.netbeans.editor.analyzer.WebServletAnalyzer;

import com.sun.source.tree.Tree.Kind;

/**
 * @author denis
 */
public class WebServlet {

    @Hint(displayName = "#DN_WebParamUI", description = "#DESC_WebParamUI",
            category = "vaadin", options = Options.QUERY,
            severity = Severity.WARNING)
    @TriggerTreeKind(Kind.CLASS)
    public static ErrorDescription noUiVaadinServlet( HintContext context ) {
        WebServletAnalyzer analyzer = new WebServletAnalyzer(context);
        analyzer.analyze();
        return analyzer.getNoUiVaadinServlet();
    }

    @Hint(displayName = "#DN_WebServletHasNoWidgetset",
            description = "#DESC_WebServletHasNoWidgetset",
            category = "vaadin", options = Options.QUERY,
            severity = Severity.HINT)
    @TriggerTreeKind(Kind.CLASS)
    public static ErrorDescription noWidgetsetVaadinServlet( HintContext context )
    {
        WebServletAnalyzer analyzer = new WebServletAnalyzer(context);
        analyzer.analyze();
        return analyzer.getNoWidgetsetVaadinServlet();
    }

    @Hint(displayName = "#DN_WebServletWidgetsetError",
            description = "#DESC_WebServletWidgetsetError",
            category = "vaadin", options = Options.QUERY,
            severity = Severity.ERROR)
    @TriggerTreeKind(Kind.CLASS)
    public static ErrorDescription checkWidgetset( HintContext context ) {
        WebServletAnalyzer analyzer = new WebServletAnalyzer(context);
        analyzer.analyze();
        return analyzer.getNoGwtModule();
    }

    @Hint(displayName = "#DN_WebServletIsNotVaadin",
            description = "#DESC_WebServletIsNotVaadin", category = "vaadin",
            options = Options.QUERY, severity = Severity.WARNING)
    @TriggerTreeKind(Kind.CLASS)
    public static ErrorDescription requireVaadinServlet( HintContext context ) {
        WebServletAnalyzer analyzer = new WebServletAnalyzer(context);
        analyzer.analyze();
        return analyzer.getRequireVaadinServlet();
    }

}


text:
require "test_helper"
require "minitest/spec"

class Fixturator::GeneratorTest < ActiveSupport::TestCase
  extend Minitest::Spec::DSL

  subject { Fixturator::Generator.new(model) }
  let(:model) { ::User }
  let(:tempfile) { @tempfile.path }

  before do
    @tempfile = Tempfile.new("fixtures.yml")
    subject.stubs(fixture_path: @tempfile.path)
    User.destroy_all
    3.times do |i|
      User.create!(name: "Foo#{i + 1}")
    end
  end

  after do
    @tempfile.unlink
  end

  let(:fixture_hash) { YAML.load_file(tempfile) }
  let(:fixture_name) { "user_3" }

  it "writes the attributes" do
    subject.call
    assert_equal fixture_name, fixture_hash.keys.last
    assert_equal "Foo3", fixture_hash[fixture_name]["name"]
  end
end


text:
define(['module'], function(module) {

    'use strict';

    var buildMap = {};
    var fileExtension = '.tag';
    var riotloader = {
        version: '0.0.1',

        getUrlContents: function GET(url, cb) {
            var req = new XMLHttpRequest();

            req.onreadystatechange = function() {
                if (req.readyState === 4 &&
                    (req.status === 200 || !req.status && req.responseText.length)) {
                    cb(req.responseText, url);
                }
            };
            req.open('GET', url, true);
            req.send('');
        },

        load: function(name, parentRequire, onLoad, config) {

            var name_with_extension = (name.indexOf(fileExtension) === -1) ? name.fileExtension : name,
                fileUrl = parentRequire.toUrl(name_with_extension),
                compiledTag;

            if (config.isBuild && require.nodeRequire) {
                try {

                    var noderiot = require.nodeRequire('riot'),
                        fs = require.nodeRequire('fs'),
                        tagtext = fs.readFileSync(fileUrl, 'utf8');

                    compiledTag = noderiot.compile(tagtext);

                    buildMap[name] = compiledTag;
                } catch (e) {
                    console.log('Riot not installed. Use "sudo npm install riot -g" to enable.');
                    console.log('Exception! ', e);
                }
                onLoad();

            } else {
                riotloader.getUrlContents(fileUrl, function(rawTag) {
                    parentRequire(['riot'], function(riot) {
                        compiledTag = riot.compile(rawTag, true);
                        var text = "require(['riot'],function(riot) {\n" + compiledTag + " });";
                        onLoad.fromText(text);

                    });
                });

            }
            return;

        },

        write: function(pluginName, moduleName, write) {
            console.log('write', moduleName);
            if (buildMap.hasOwnProperty(moduleName)) {
                var content = buildMap[moduleName];
                write("define('" + pluginName + "!" + moduleName + "',['riot'], function(riot){ return " + content + "});\n");
            }
        }
    };

    return riotloader;
});


text:
package info.ipeanut.googletrainingcoursedemos.threadsample;

import org.xml.sax.helpers.DefaultHandler;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.content.ContentValues;
import android.net.Uri;

import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

/**
 * RSSPullParser reads an RSS feed from the Picasa featured pictures site. It uses
 * several packages from the widely-known XMLPull API.
 *
 */
public class RSSPullParser extends DefaultHandler {
    // Global constants

    // An attribute value indicating that the element contains media content
    private static final String CONTENT = "media:content";

    // An attribute value indicating that the element contains a thumbnail
    private static final String THUMBNAIL = "media:thumbnail";

    // An attribute value indicating that the element contains an item
    private static final String ITEM = "item";

    // Sets the initial size of the vector that stores data.
    private static final int VECTOR_INITIAL_SIZE = 500;

    // Storage for a single ContentValues for image data
    private static ContentValues mImage;

    // A vector that will contain all of the images
    private Vector<ContentValues> mImages;

    /**
     * A getter that returns the image data Vector
     * @return A Vector containing all of the image data retrieved by the parser
     */
    public Vector<ContentValues> getImages() {
        return mImages;
    }
    /**
     * This method parses XML in an input stream and stores parts of the data in memory
     *
     * @param inputStream a stream of data containing XML elements, usually a RSS feed
     * @param progressNotifier a helper class for sending status and logs
     * @throws XmlPullParserException defined by XMLPullParser; thrown if the thread is cancelled.
     * @throws IOException thrown if an IO error occurs during parsing
     */
    public void parseXml(InputStream inputStream,
            BroadcastNotifier progressNotifier)
            throws XmlPullParserException, IOException {

        // Instantiates a parser factory
        XmlPullParserFactory localXmlPullParserFactory = XmlPullParserFactory
                .newInstance();

        // Turns off namespace handling for the XML input
        localXmlPullParserFactory.setNamespaceAware(false);

        // Instantiates a new pull parser
        XmlPullParser localXmlPullParser = localXmlPullParserFactory
                .newPullParser();

        // Sets the parser's input stream
        localXmlPullParser.setInput(inputStream, null);

        // Gets the first event in the input sream
        int eventType = localXmlPullParser.getEventType();

        // Sets the number of images read to 1
        int imageCount = 1;

        // Returns if the current event (state) is not START_DOCUMENT
        if (eventType != XmlPullParser.START_DOCUMENT) {

            throw new XmlPullParserException("Invalid RSS");

        }

        // Creates a new store for image URL data
        mImages = new Vector<ContentValues>(VECTOR_INITIAL_SIZE);

        // Loops indefinitely. The exit occurs if there are no more URLs to process
        while (true) {

            // Gets the next event in the input stream
            int nextEvent = localXmlPullParser.next();

            // If the current thread is interrupted, throws an exception and returns
            if (Thread.currentThread().isInterrupted()) {

                throw new XmlPullParserException("Cancelled");

            // At the end of the feed, exits the loop
            } else if (nextEvent == XmlPullParser.END_DOCUMENT) {
                break;

            // At the beginning of the feed, skips the event and continues
            } else if (nextEvent == XmlPullParser.START_DOCUMENT) {
                continue;

            // At the start of a tag, gets the tag's name
            } else if (nextEvent == XmlPullParser.START_TAG) {
                String eventName = localXmlPullParser.getName();

                /*
                 * If this is the start of an individual item, logs it and creates a new
                 * ContentValues
                 */
                if (eventName.equalsIgnoreCase(ITEM)) {

                    mImage = new ContentValues();

                // If this isn't an item, then checks for other options
                } else {

                    // Defines keys to store the column names
                    String imageUrlKey;
                    String imageNameKey;

                    // Defines a place to store the filename of a URL,
                    String fileName;

                    // If it's CONTENT
                    if (eventName.equalsIgnoreCase(CONTENT)) {

                        // Stores the image URL and image name column names as keys
                        imageUrlKey = DataProviderContract.IMAGE_URL_COLUMN;
                        imageNameKey = DataProviderContract.IMAGE_PICTURENAME_COLUMN;

                    // If it's a THUMBNAIL
                    } else if (eventName.equalsIgnoreCase(THUMBNAIL)) {

                        // Stores the thumbnail URL and thumbnail name column names as keys
                        imageUrlKey = DataProviderContract.IMAGE_THUMBURL_COLUMN;
                        imageNameKey = DataProviderContract.IMAGE_THUMBNAME_COLUMN;

                    // Otherwise it's some other event that isn't important
                    } else {
                        continue;
                    }

                    // It's not an ITEM. Gets the URL attribute from the event
                    String urlValue = localXmlPullParser.getAttributeValue(null, "url");

                    // If the value is null, exits
                    if (urlValue == null)
                        break;

                    // Puts the URL and the key into the ContentValues
                    mImage.put(imageUrlKey, urlValue);

                    // Gets the filename of the URL and puts it into the ContentValues
                    fileName = Uri.parse(urlValue).getLastPathSegment();
                    mImage.put(imageNameKey, fileName);
                }
            }
            /*
             * If it's not an ITEM, and it is an END_TAG, and the current event is an ITEM, and
             * there is data in the current ContentValues
             */
            else if ((nextEvent == XmlPullParser.END_TAG)
                    && (localXmlPullParser.getName().equalsIgnoreCase(ITEM))
                    && (mImage != null)) {

                // Adds the current ContentValues to the ContentValues storage
                mImages.add(mImage);

                // Logs progress
                progressNotifier.notifyProgress("Parsed Image[" + imageCount + "]:"
                        + mImage.getAsString(DataProviderContract.IMAGE_URL_COLUMN));

                // Clears out the current ContentValues
                mImage = null;

                // Increments the count of the number of images stored.
                imageCount++;
            }
        }
    }
}


text:
dojo.provide("dijit.form.ValidationTextBox");

dojo.require("dojo.i18n");

dojo.require("dijit.form.TextBox");
dojo.require("dijit.Tooltip");

dojo.requireLocalization("dijit.form", "validate");

/*=====
	dijit.form.ValidationTextBox.__Constraints = function(){
		// locale: String
		//		locale used for validation, picks up value from this widget's lang attribute
		// _flags_: anything
		//		various flags passed to regExpGen function
		this.locale = "";
		this._flags_ = "";
	}
=====*/

dojo.declare(
	"dijit.form.ValidationTextBox",
	dijit.form.TextBox,
	{
		// summary:
		//		A TextBox subclass with the ability to validate content of various types and provide user feedback.

		templatePath: dojo.moduleUrl("dijit.form", "templates/ValidationTextBox.html"),
		baseClass: "dijitTextBox",

		// default values for new subclass properties
		// required: Boolean
		//		Can be true or false, default is false.
		required: false,

		// promptMessage: String
		//		Hint string
		promptMessage: "",

		// invalidMessage: String
		// 		The message to display if value is invalid.
		invalidMessage: "$_unset_$", // read from the message file if not overridden

		// constraints: dijit.form.ValidationTextBox.__Constraints
		//		user-defined object needed to pass parameters to the validator functions
		constraints: {},

		// regExp: String
		//		regular expression string used to validate the input
		//		Do not specify both regExp and regExpGen
		regExp: ".*",

		// regExpGen: Function
		//		user replaceable function used to generate regExp when dependent on constraints
		//		Do not specify both regExp and regExpGen
		regExpGen: function(/*dijit.form.ValidationTextBox.__Constraints*/constraints){ return this.regExp; },

		// state: String
		//		Shows current state (ie, validation result) of input (Normal, Warning, or Error)
		state: "",

		//	tooltipPosition: String[]
		//		See description of dijit.Tooltip.defaultPosition for details on this parameter.
		tooltipPosition: [],

		_setValueAttr: function(){
			// summary:
			//		Hook so attr('value', ...) works.
			this.inherited(arguments);
			this.validate(this._focused);
		},

		validator: function(/*anything*/value, /*dijit.form.ValidationTextBox.__Constraints*/constraints){
			// summary: user replaceable function used to validate the text input against the regular expression.
			return (new RegExp("^(?:" + this.regExpGen(constraints) + ")"+(this.required?"":"?")+"$")).test(value) &&
				(!this.required || !this._isEmpty(value)) &&
				(this._isEmpty(value) || this.parse(value, constraints) !== undefined); // Boolean
		},

		_isValidSubset: function(){
			// summary:
			//	Returns true if the value is either already valid or could be made valid by appending characters.
			return this.textbox.value.search(this._partialre) == 0;
		},

		isValid: function(/*Boolean*/ isFocused){
			// summary: Need to over-ride with your own validation code in subclasses
			return this.validator(this.textbox.value, this.constraints);
		},

		_isEmpty: function(value){
			// summary: Checks for whitespace
			return /^\s*$/.test(value); // Boolean
		},

		getErrorMessage: function(/*Boolean*/ isFocused){
			// summary: return an error message to show if appropriate
			return this.invalidMessage; // String
		},

		getPromptMessage: function(/*Boolean*/ isFocused){
			// summary: return a hint to show if appropriate
			return this.promptMessage; // String
		},

		_maskValidSubsetError: true,
		validate: function(/*Boolean*/ isFocused){
			// summary:
			//		Called by oninit, onblur, and onkeypress.
			// description:
			//		Show missing or invalid messages if appropriate, and highlight textbox field.
			var message = "";
			var isValid = this.disabled || this.isValid(isFocused);
			if(isValid){ this._maskValidSubsetError = true; }
			var isValidSubset = !isValid && isFocused && this._isValidSubset();
			var isEmpty = this._isEmpty(this.textbox.value);
			this.state = (isValid || (!this._hasBeenBlurred && isEmpty) || isValidSubset) ? "" : "Error";
			if(this.state == "Error"){ this._maskValidSubsetError = false; }
			this._setStateClass();
			dijit.setWaiState(this.focusNode, "invalid", isValid ? "false" : "true");
			if(isFocused){
				if(isEmpty){
					message = this.getPromptMessage(true);
				}
				if(!message && (this.state == "Error" || (isValidSubset && !this._maskValidSubsetError))){
					message = this.getErrorMessage(true);
				}
			}
			this.displayMessage(message);
			return isValid;
		},

		// currently displayed message
		_message: "",

		displayMessage: function(/*String*/ message){
			// summary:
			//		User overridable method to display validation errors/hints.
			//		By default uses a tooltip.
			if(this._message == message){ return; }
			this._message = message;
			dijit.hideTooltip(this.domNode);
			if(message){
				dijit.showTooltip(message, this.domNode, this.tooltipPosition);
			}
		},

		_refreshState: function(){
			this.validate(this._focused);
		},

		_update: function(/*Event*/e){
			this._refreshState();
			this._onMouse(e);	// update CSS classes
		},

		//////////// INITIALIZATION METHODS ///////////////////////////////////////

		constructor: function(){
			this.constraints = {};
		},

		postMixInProperties: function(){
			this.inherited(arguments);
			this.constraints.locale = this.lang;
			this.messages = dojo.i18n.getLocalization("dijit.form", "validate", this.lang);
			if(this.invalidMessage == "$_unset_$"){ this.invalidMessage = this.messages.invalidMessage; }
			var p = this.regExpGen(this.constraints);
			this.regExp = p;
			var partialre = "";
			// parse the regexp and produce a new regexp that matches valid subsets
			// if the regexp is .* then there's no use in matching subsets since everything is valid
			if(p != ".*"){ this.regExp.replace(/\\.|\[\]|\[.*?[^\\]{1}\]|\{.*?\}|\(\?[=:!]|./g,
				function (re){
					switch(re.charAt(0)){
						case '{':
						case '+':
						case '?':
						case '*':
						case '^':
						case '$':
						case '|':
						case '(': partialre += re; break;
						case ")": partialre += "|$)"; break;
						 default: partialre += "(?:"+re+"|$)"; break;
					}
				}
			);}
			try{ // this is needed for now since the above regexp parsing needs more test verification
				"".search(partialre);
			}catch(e){ // should never be here unless the original RE is bad or the parsing is bad
				partialre = this.regExp;
				console.debug('RegExp error in ' + this.declaredClass + ': ' + this.regExp);
			} // should never be here unless the original RE is bad or the parsing is bad
			this._partialre = "^(?:" + partialre + ")$";
		},

		_setDisabledAttr: function(/*Boolean*/ value){
			this.inherited(arguments);	// call FormValueWidget._setDisabledAttr()
					if(this.valueNode){
				this.valueNode.disabled = value;
					}
					this._refreshState();
		},

		_setRequiredAttr: function(/*Boolean*/ value){
			this.required = value;
			dijit.setWaiState(this.focusNode,"required", value);
					this._refreshState();
		},

		postCreate: function(){
			if(dojo.isIE){ // IE INPUT tag fontFamily has to be set directly using STYLE
				var s = dojo.getComputedStyle(this.focusNode);
				if(s){
					var ff = s.fontFamily;
					if(ff){
						this.focusNode.style.fontFamily = ff;
					}
				}
			}
			this.inherited(arguments);
		}
	}
);

dojo.declare(
	"dijit.form.MappedTextBox",
	dijit.form.ValidationTextBox,
	{
		// summary:
		//		A dijit.form.ValidationTextBox subclass which provides a visible formatted display and a serializable
		//		value in a hidden input field which is actually sent to the server.  The visible display may
		//		be locale-dependent and interactive.  The value sent to the server is stored in a hidden
		//		input field which uses the `name` attribute declared by the original widget.  That value sent
		//		to the serveris defined by the dijit.form.MappedTextBox.serialize method and is typically
		//		locale-neutral.

		serialize: function(/*anything*/val, /*Object?*/options){
			// summary: user replaceable function used to convert the attr('value') result to a String
			return val.toString ? val.toString() : ""; // String
		},

		toString: function(){
			// summary: display the widget as a printable string using the widget's value

			// TODO: seems like the filter() call here is unnecessary as attr('value') should do that
			var val = this.filter(this.attr('value'));
			return val != null ? (typeof val == "string" ? val : this.serialize(val, this.constraints)) : ""; // String
		},

		validate: function(){
			this.valueNode.value = this.toString();
			return this.inherited(arguments);
		},

		buildRendering: function(){
			this.inherited(arguments);

			// Create a hidden <input> node with the serialized value used for submit
			// (as opposed to the displayed value)
			var textbox = this.textbox;
			var valueNode = (this.valueNode = dojo.doc.createElement("input"));
			valueNode.setAttribute("type", textbox.type);
			dojo.style(valueNode, "display", "none");
			this.valueNode.name = this.textbox.name;
			dojo.place(valueNode, textbox, "after");

			// try to give the displayed node a different name, or ideally
			// remove that attribute altogether
			this.textbox.name = this.textbox.name + "_displayed_";
			this.textbox.removeAttribute("name");
		},

		_setDisabledAttr: function(/*Boolean*/ value){
			this.inherited(arguments);
			dojo.attr(this.valueNode, 'disabled', value);
		}
	}
);

/*=====
	dijit.form.RangeBoundTextBox.__Constraints = function(){
		// min: Number
		//		Minimum signed value.  Default is -Infinity
		// max: Number
		//		Maximum signed value.  Default is +Infinity
		this.min = min;
		this.max = max;
	}
=====*/

dojo.declare(
	"dijit.form.RangeBoundTextBox",
	dijit.form.MappedTextBox,
	{
		// summary:
		//		A dijit.form.MappedTextBox subclass which defines a range of valid values
		//
		// constraints: dijit.form.RangeBoundTextBox.__Constraints
		//
		// rangeMessage: String
		//		The message to display if value is out-of-range

		/*=====
		constraints: {},
		======*/
		rangeMessage: "",

		rangeCheck: function(/*Number*/ primitive, /*dijit.form.RangeBoundTextBox.__Constraints*/ constraints){
			// summary: user replaceable function used to validate the range of the numeric input value
			var isMin = "min" in constraints;
			var isMax = "max" in constraints;
			if(isMin || isMax){
				return (!isMin || this.compare(primitive,constraints.min) >= 0) &&
					(!isMax || this.compare(primitive,constraints.max) <= 0);
			}
			return true; // Boolean
		},

		isInRange: function(/*Boolean*/ isFocused){
			// summary: Need to over-ride with your own validation code in subclasses
			return this.rangeCheck(this.attr('value'), this.constraints);
		},

		_isDefinitelyOutOfRange: function(){
			// summary:
			//	Returns true if the value is out of range and will remain
			//	out of range even if the user types more characters
			var val = this.attr('value');
			var isTooLittle = false;
			var isTooMuch = false;
			if("min" in this.constraints){
				var min = this.constraints.min;
				val = this.compare(val, ((typeof min == "number") && min >= 0 && val !=0)? 0 : min);
				isTooLittle = (typeof val == "number") && val < 0;
			}
			if("max" in this.constraints){
				var max = this.constraints.max;
				val = this.compare(val, ((typeof max != "number") || max > 0)? max : 0);
				isTooMuch = (typeof val == "number") && val > 0;
			}
			return isTooLittle || isTooMuch;
		},

		_isValidSubset: function(){
			return this.inherited(arguments) && !this._isDefinitelyOutOfRange();
		},

		isValid: function(/*Boolean*/ isFocused){
			return this.inherited(arguments) &&
				((this._isEmpty(this.textbox.value) && !this.required) || this.isInRange(isFocused)); // Boolean
		},

		getErrorMessage: function(/*Boolean*/ isFocused){
			if(dijit.form.RangeBoundTextBox.superclass.isValid.call(this, false) && !this.isInRange(isFocused)){ return this.rangeMessage; } // String
			return this.inherited(arguments);
		},

		postMixInProperties: function(){
			this.inherited(arguments);
			if(!this.rangeMessage){
				this.messages = dojo.i18n.getLocalization("dijit.form", "validate", this.lang);
				this.rangeMessage = this.messages.rangeMessage;
			}
		},

		postCreate: function(){
			this.inherited(arguments);
			if(this.constraints.min !== undefined){
				dijit.setWaiState(this.focusNode, "valuemin", this.constraints.min);
			}
			if(this.constraints.max !== undefined){
				dijit.setWaiState(this.focusNode, "valuemax", this.constraints.max);
			}
		},

		_setValueAttr: function(/*Number*/ value, /*Boolean?*/ priorityChange){
			// summary:
			//		Hook so attr('value', ...) works.
			dijit.setWaiState(this.focusNode, "valuenow", value);
			this.inherited(arguments);
		}
	}
);


text:
<?php

namespace Josser\Client\Request;

use Josser\Client\Request\RequestInterface;

/**
 * JSON-RPC explicit notification object.
 *
 * @author Alan Gabriel Bem <alan.bem@gmail.com>
 */
class Notification implements RequestInterface
{
    /**
     * A string containing the name of the method to be invoked.
     *
     * @var string
     */
    private $method;

    /**
     * A Structured value that holds the parameter values to be used during the invocation of the method.
     *
     * @var array
     */
    private $params;

    /**
     * Constructor.
     *
     * @param string $method
     * @param array $params
     */
    public function __construct($method, array $params = array())
    {
        $this->method = $method;
        $this->params = $params;
    }

    /**
     * Get remote method name.
     *
     * @return string
     */
    public function getMethod()
    {
        return $this->method;
    }

    /**
     * Get method parameters.
     *
     * @return array
     */
    public function getParams()
    {
        return $this->params;
    }

    /**
     * Get request id.
     *
     * @return null
     */
    public function getId()
    {
        return null;
    }
}


text:
<?xml version="1.0"?>
<!-- JBoss, Home of Professional Open Source Copyright 2008, Red Hat Middleware
	LLC, and others contributors as indicated by the @authors tag. All rights
	reserved. See the copyright.txt in the distribution for a full listing of
	individual contributors. This copyrighted material is made available to anyone
	wishing to use, modify, copy, or redistribute it subject to the terms and
	conditions of the GNU Lesser General Public License, v. 2.1. This program
	is distributed in the hope that it will be useful, but WITHOUT A WARRANTY;
	without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
	PURPOSE. See the GNU Lesser General Public License for more details. You
	should have received a copy of the GNU Lesser General Public License, v.2.1
	along with this distribution; if not, write to the Free Software Foundation,
	Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -->
<ENVIRONMENT xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://www.jboss.org/blacktie">
	<DOMAIN>fooapp</DOMAIN>
	<MACHINES>
		<MACHINE id="myserv1" ipAddress="127.0.0.1"
			pathToExecutable="notExist" workingDirectory="." argLine="foo"
			serverId="1" />
		<MACHINE id="myserv2" ipAddress="127.0.0.1"
			pathToExecutable="notExist" workingDirectory="." argLine="foo"
			serverId="2" />
	</MACHINES>
	<SERVERS>
		<SERVER name='myserv'>
			<MACHINE-REF id="myserv1" />
			<MACHINE-REF id="myserv2" />
			<SERVICE_NAMES>
				<SERVICE name='TestOne'  externally-managed-destination='true'/>
				<SERVICE name='TestTwo'  externally-managed-destination='true'/>
				<SERVICE name='ConvService' conversational='true'  externally-managed-destination='true'/>
				<SERVICE name='JAVA_Converse'  externally-managed-destination='true'
					java_class_name="org.jboss.narayana.blacktie.jatmibroker.xatmi.services.TPCallXOctetService"
					advertised="true" size="1">
				</SERVICE>
				<SERVICE name='XMLParserTest' type='queue' coding_type="xml"/>
				<SERVICE name='JAVA_Topic' type='topic' externally-managed-destination='true'/>
			</SERVICE_NAMES>
		</SERVER>
	</SERVERS>
	<ORB
		OPT="-ORBInitRef NameService=corbaloc::${JBOSSAS_IP_ADDR}:3528/NameService -ORBListenEndpoints iiop://${JBOSSAS_IP_ADDR}:0"
		TRANS_FACTORY_ID="TransactionManagerService.OTS" />
	<SOCKETSERVER PORT="12341" />
	<MQ HOST="${JBOSSAS_IP_ADDR}" PORT="61613" USER="guest" PASSWORD="password1@"
		RECEIVE_TIMEOUT="10" TIME_TO_LIVE="40"  />
	<BUFFERS>
		<BUFFER name="abcdefghijklmnop">
			<ATTRIBUTE id="key" type="char[]" arrayLength="10" />
		</BUFFER>
		<BUFFER name="test">
			<ATTRIBUTE id="key" type="char[]" arrayLength="28" />
		</BUFFER>
		<BUFFER name="acct_info">
			<ATTRIBUTE id="acct_no" type="long" />
			<ATTRIBUTE id="name" type="char[]" arrayLength="50" />
			<ATTRIBUTE id="address" type="char[]" arrayLength="100" />
			<ATTRIBUTE id="foo" type="float[]" arrayLength="2" />
			<ATTRIBUTE id="balances" type="double[]" arrayLength="2" />
		</BUFFER>
		<BUFFER name="deposit">
			<ATTRIBUTE id="acct_no" type="long" />
			<ATTRIBUTE id="amount" type="short" />
			<ATTRIBUTE id="balance" type="short" />
			<ATTRIBUTE id="status" type="char[]" arrayLength="128" />
			<ATTRIBUTE id="status_len" type="short" />
		</BUFFER>
		<BUFFER name="inq_buf">
			<ATTRIBUTE id="input" type="char[]" arrayLength="100" />
			<ATTRIBUTE id="output" type="int" />
			<ATTRIBUTE id="failTest" type="int" />
		</BUFFER>
		<BUFFER name="dc_buf">
			<ATTRIBUTE id="input" type="char[]" arrayLength="100" />
			<ATTRIBUTE id="output" type="int" />
			<ATTRIBUTE id="failTest" type="int" />
		</BUFFER>
	</BUFFERS>
</ENVIRONMENT>


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Microsoft.Build.Framework;

using Cosmos.Build.Common;

namespace Cosmos.Build.MSBuild
{
    public class TheRingMaster : BaseToolTask
    {
        [Required]
        public string KernelAssemblyPath { get; set; }

        [Required]
        public string WorkingDir { get; set; }

        public override bool Execute()
        {
            var xSW = Stopwatch.StartNew();

            try
            {
                Log.LogMessage(MessageImportance.High, $"Invoking TheRingMaster.exe {KernelAssemblyPath}");
                return ExecuteTool(WorkingDir, Path.Combine(CosmosPaths.Build, "TheRingMaster", "TheRingMaster.exe"), KernelAssemblyPath, "The Ring Master");
            }
            finally
            {
                xSW.Stop();
                Log.LogMessage(MessageImportance.High, $"TheRingMaster invoked with KernelAssemblyPath = '{KernelAssemblyPath}'");
                Log.LogMessage(MessageImportance.High, "TheRingMaster task took {0}", xSW.Elapsed);
            }
        }
    }
}


text:
using SignalR.Dynamic.API.Common;
using SignalR.Dynamic.API.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace SignalR.Dynamic.API
{
    public class HubAssemblyProvider : IHubAssemblyProvider
    {

        IHubCodeGenerator codegen = null;
        ICodeDOMCompiler compiler = null;
        IPublisherMetadataProvider provider = null;
        Dictionary<string, Assembly> maps = new Dictionary<string, Assembly>();

        public HubAssemblyProvider(
            IHubCodeGenerator codegen,
            ICodeDOMCompiler compiler,
            IPublisherMetadataProvider provider)
        {
            this.codegen  = codegen;
            this.compiler = compiler;
            this.provider = provider;
            InitializeMaps();
        }

        private void InitializeMaps()
        {
            foreach (var metadata in provider.GetMetadata())
            {
                if (! maps.ContainsKey(metadata.Topic))
                {
                    maps[metadata.Topic] = null;
                }
            }
        }

        public Assembly GetAssembly(string topic)
        {
            throw new NotImplementedException();

        }

        public IEnumerable<Assembly> GetAssembies()
        {
            throw new NotImplementedException();
        }
    }
}


text:
<?php

namespace App\Models\Tevo;

use App\Events\ItemWasStored;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\Eloquent\Relations\HasOne;

/**
 * @mixin IdeHelperEvent
 */
class Event extends Model
{
    use StoresFromApi;

    protected $table = 'events';

    protected $fillable = [
        'id',
        'name',
        'occurs_at',
        'occurs_at_local',
        'venue_id',
        'configuration_id',
        'category_id',
        'popularity_score',
        'short_term_popularity_score',
        'long_term_popularity_score',
        'products_count',
        'products_eticket_count',
        'available_count',
        'state',
        'notes',
        'stubhub_id',
        'url',
        'tevo_created_at',
        'tevo_updated_at',
        'tevo_deleted_at',
    ];

    protected $casts = [
        'id'                          => 'integer',
        'name'                        => 'string',
        'occurs_at'                   => 'datetime',
        'occurs_at_local'             => 'datetime',
        'venue_id'                    => 'integer',
        'configuration_id'            => 'integer',
        'category_id'                 => 'integer',
        'popularity_score'            => 'decimal:12',
        'short_term_popularity_score' => 'decimal:7',
        'long_term_popularity_score'  => 'decimal:7',
        'products_count'              => 'integer',
        'products_eticket_count'      => 'integer',
        'available_count'             => 'integer',
        'state'                       => 'integer',
        'notes'                       => 'string',
        'stubhub_id'                  => 'integer',
        'url'                         => 'string',
        'seating_chart_url_medium'    => 'string',
        'seating_chart_url_large'     => 'string',
        'configuration_url'           => 'string',
        'tevo_created_at'             => 'datetime',
        'tevo_updated_at'             => 'datetime',
        'tevo_deleted_at'             => 'datetime',
        'created_at'                  => 'datetime',
        'updated_at'                  => 'datetime',
        'deleted_at'                  => 'datetime',
    ];

    /**
     * When deleting an Event deleted the related Performances
     */
    public static function boot() {
        parent::boot();

        self::deleting(function($event) {
            $event->performances()->each(function($performance) {
                $performance->delete();
            });
        });
    }

    /**
     * Events can have more than 1 Performance.
     */
    public function performances(): HasMany
    {
        return $this->hasMany(Performance::class);
    }

    /**
     * Events can have more than 1 Performer via 1 or more Performances.
     */
    public function performers(): HasManyThrough
    {
        return $this->hasManyThrough(Performance::class, Performer::class);
    }

    /**
     * Events can have only 1 Venue.
     */
    public function venue(): HasOne
    {
        return $this->hasOne(Venue::class);
    }

    /**
     * Events can have only 1 Configuration.
     */
    public function configuration(): HasOne
    {
        return $this->hasOne(Configuration::class);
    }

    /**
     * Events can have only 1 Category.
     */
    public function category(): HasOne
    {
        return $this->hasOne(Category::class);
    }

    /**
     * Mutator to nullify empty value.
     */
    public function setNotesAttribute($value): void
    {
        if (empty($value)) {
            $this->attributes['notes'] = null;
        } else {
            $this->attributes['notes'] = $value;
        }
    }

    /**
     * Mutate the $result as necessary.
     * Be sure to run the parent::mutateApiResult() to get the common mutations.
     */
    protected static function mutateApiResult(array $result): array
    {
        // Be sure to call the parent version for common mutations
        $result = parent::mutateApiResult($result);

        /**
         * Add custom mutations for this item type here
         */

        // No event should have a real score that is negative,
        // but yet I've seen it happen. Add some sanity.
        if ($result['long_term_popularity_score'] < 0) {
            $result['long_term_popularity_score'] = (float) 0;
        }
        if ($result['popularity_score'] < 0) {
            $result['popularity_score'] = (float) 0;
        }

        $result['occurs_at'] = rtrim($result['occurs_at'], 'Z');

        $result['configuration_id'] = $result['configuration']['id'] ?? null;
        unset($result['configuration']);

        $result['category_id'] = $result['category']['id'] ?? null;
        unset($result['category']);

        $result['venue_id'] = $result['venue']['id'];
        unset($result['venue']);

        return $result;
    }

    /**
     * Any operations that need to be run after save()
     * such as saving related Models can go here.
     */
    protected static function postSave(Model $event, array $result): Model
    {
        /**
         * Insert/Delete/Update Performances as necessary
         */
        if (! empty($result['performances'])) {
            $validEventPerformerIds = [];

            foreach ($result['performances'] as $resultPerformance) {
                $validEventPerformerIds[] = $resultPerformance['performer']['id'];

                Performance::withTrashed()->updateOrCreate(
                    [
                        'event_id'     => $event->id,
                        'performer_id' => $resultPerformance['performer']['id'],
                    ],
                    [
                        'primary'    => $resultPerformance['primary'],
                        'event_name' => $event->name,
                        'occurs_at'  => $event->occurs_at,
                        'venue_id'   => $event->venue_id,
                        'deleted_at' => null,
                    ]);
            }

            // Delete any Performances for this Event that have Performers
            // that were not in $result['performances']
            Performance::where('event_id', '=', $event->id)
                ->whereNotIn('performer_id', $validEventPerformerIds)
                ->delete();

            unset($validEventPerformerIds);
        } else {
            Performance::where('event_id', '=', $event->id)
                ->delete();
        }
        return $event;
    }
}


text:
package org.apache.logging.log4j.util;

import java.util.Iterator;
import java.util.Locale;
import java.util.Objects;

/**
 * Hive uses class with the same full name from log4j-api.
 * Added this class to avoid ClassNotFound errors from Hive.
 *

 * This is a copy of the log4j-api 2.14.1 code with some minor tweaks to avoid dependency on other classes.
 *
 * See HIVE-23088 for the problem description.
 */
public final class Strings {

  /**
   * The empty string.
   */
  public static final String EMPTY = "";

  /**
   * OS-dependent line separator, defaults to {@code "\n"} if the system property {@code "line.separator"} cannot be
   * read. Apache Log4J 2.x code uses a PropertyUtil and may get a different result - but we don't want to copy all
   * that code to Drill.
   */
  public static final String LINE_SEPARATOR = System.lineSeparator();

  private static final char DQUOTE = '\"';
  private static final char QUOTE = '\'';

  /**
   * Returns a double quoted string.
   *
   * @param str a String
   * @return {@code "str"}
   */
  public static String dquote(final String str) {
    return DQUOTE + str + DQUOTE;
  }

  /**
   * Checks if a String is blank. A blank string is one that is either
   * {@code null}, empty, or all characters are {@link Character#isWhitespace(char)}.
   *
   * @param s the String to check, may be {@code null}
   * @return {@code true} if the String is {@code null}, empty, or or all characters are {@link Character#isWhitespace(char)}
   */
  public static boolean isBlank(final String s) {
    if (s == null || s.isEmpty()) {
      return true;
    }
    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);
      if (!Character.isWhitespace(c)) {
        return false;
      }
    }
    return true;
  }

  /**
   *

   * Checks if a CharSequence is empty ("") or null.
   *

   *
   *

   * Strings.isEmpty(null)      = true
   * Strings.isEmpty("")        = true
   * Strings.isEmpty(" ")       = false
   * Strings.isEmpty("bob")     = false
   * Strings.isEmpty("  bob  ") = false
   *

   *
   *

   * NOTE: This method changed in Lang version 2.0. It no longer trims the CharSequence. That functionality is
   * available in isBlank().
   *

   *
   *

   * Copied from Apache Commons Lang org.apache.commons.lang3.StringUtils.isEmpty(CharSequence)
   *

   *
   * @param cs the CharSequence to check, may be null
   * @return {@code true} if the CharSequence is empty or null
   */
  public static boolean isEmpty(final CharSequence cs) {
    return cs == null || cs.length() == 0;
  }

  /**
   * Checks if a String is not blank. The opposite of {@link #isBlank(String)}.
   *
   * @param s the String to check, may be {@code null}
   * @return {@code true} if the String is non-{@code null} and has content after being trimmed.
   */
  public static boolean isNotBlank(final String s) {
    return !isBlank(s);
  }

  /**
   *

   * Checks if a CharSequence is not empty ("") and not null.
   *

   *
   *

   * Strings.isNotEmpty(null)      = false
   * Strings.isNotEmpty("")        = false
   * Strings.isNotEmpty(" ")       = true
   * Strings.isNotEmpty("bob")     = true
   * Strings.isNotEmpty("  bob  ") = true
   *

   *
   *

   * Copied from Apache Commons Lang org.apache.commons.lang3.StringUtils.isNotEmpty(CharSequence)
   *

   *
   * @param cs the CharSequence to check, may be null
   * @return {@code true} if the CharSequence is not empty and not null
   */
  public static boolean isNotEmpty(final CharSequence cs) {
    return !isEmpty(cs);
  }

  /**
   *
Joins the elements of the provided {@code Iterable} into
   * a single String containing the provided elements.

   *
   *
No delimiter is added before or after the list. Null objects or empty
   * strings within the iteration are represented by empty strings.

   *
   * @param iterable  the {@code Iterable} providing the values to join together, may be null
   * @param separator  the separator character to use
   * @return the joined String, {@code null} if null iterator input
   */
  public static String join(final Iterable<?> iterable, final char separator) {
    if (iterable == null) {
      return null;
    }
    return join(iterable.iterator(), separator);
  }

  /**
   *
Joins the elements of the provided {@code Iterator} into
   * a single String containing the provided elements.

   *
   *
No delimiter is added before or after the list. Null objects or empty
   * strings within the iteration are represented by empty strings.

   *
   * @param iterator  the {@code Iterator} of values to join together, may be null
   * @param separator  the separator character to use
   * @return the joined String, {@code null} if null iterator input
   */
  public static String join(final Iterator<?> iterator, final char separator) {

    // handle null, zero and one elements before building a buffer
    if (iterator == null) {
      return null;
    }
    if (!iterator.hasNext()) {
      return EMPTY;
    }
    final Object first = iterator.next();
    if (!iterator.hasNext()) {
      return Objects.toString(first, EMPTY);
    }

    // two or more elements
    final StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small
    if (first != null) {
      buf.append(first);
    }

    while (iterator.hasNext()) {
      buf.append(separator);
      final Object obj = iterator.next();
      if (obj != null) {
        buf.append(obj);
      }
    }

    return buf.toString();
  }

  /**
   *
Gets the leftmost {@code len} characters of a String.

   *
   *
If {@code len} characters are not available, or the
   * String is {@code null}, the String will be returned without
   * an exception. An empty String is returned if len is negative.

   *
   *

   * StringUtils.left(null, *)    = null
   * StringUtils.left(*, -ve)     = ""
   * StringUtils.left("", *)      = ""
   * StringUtils.left("abc", 0)   = ""
   * StringUtils.left("abc", 2)   = "ab"
   * StringUtils.left("abc", 4)   = "abc"
   *

   *
   *

   * Copied from Apache Commons Lang org.apache.commons.lang3.StringUtils.
   *

   *
   * @param str  the String to get the leftmost characters from, may be null
   * @param len  the length of the required String
   * @return the leftmost characters, {@code null} if null String input
   */
  public static String left(final String str, final int len) {
    if (str == null) {
      return null;
    }
    if (len < 0) {
      return EMPTY;
    }
    if (str.length() <= len) {
      return str;
    }
    return str.substring(0, len);
  }

  /**
   * Returns a quoted string.
   *
   * @param str a String
   * @return {@code 'str'}
   */
  public static String quote(final String str) {
    return QUOTE + str + QUOTE;
  }

  /**
   *

   * Removes control characters (char <= 32) from both ends of this String returning {@code null} if the String is
   * empty ("") after the trim or if it is {@code null}.
   *
   *

   * The String is trimmed using {@link String#trim()}. Trim removes start and end characters <= 32.
   *

   *
   *

   * Strings.trimToNull(null)          = null
   * Strings.trimToNull("")            = null
   * Strings.trimToNull("     ")       = null
   * Strings.trimToNull("abc")         = "abc"
   * Strings.trimToNull("    abc    ") = "abc"
   *

   *
   *

   * Copied from Apache Commons Lang org.apache.commons.lang3.StringUtils.trimToNull(String)
   *

   *
   * @param str the String to be trimmed, may be null
   * @return the trimmed String, {@code null} if only chars <= 32, empty or null String input
   */
  public static String trimToNull(final String str) {
    final String ts = str == null ? null : str.trim();
    return isEmpty(ts) ? null : ts;
  }

  private Strings() {
    // empty
  }

  /**
   * Shorthand for {@code str.toUpperCase(Locale.ROOT);}
   * @param str The string to upper case.
   * @return a new string
   * @see String#toLowerCase(Locale)
   */
  public static String toRootUpperCase(final String str) {
    return str.toUpperCase(Locale.ROOT);
  }

  /**
   * Creates a new string repeating given {@code str} {@code count} times.
   * @param str input string
   * @param count the repetition count
   * @return the new string
   * @throws IllegalArgumentException if either {@code str} is null or {@code count} is negative
   */
  public static String repeat(final String str, final int count) {
    Objects.requireNonNull(str, "str");
    if (count < 0) {
      throw new IllegalArgumentException("count");
    }
    StringBuilder sb = new StringBuilder(str.length() * count);
    for (int index = 0; index < count; index++) {
      sb.append(str);
    }
    return sb.toString();
  }

}


text:
using System;
using System.Linq;
using System.Collections.Specialized;
using System.Data;
using System.Reflection;
using NUnit.Core;
using NUnit.Core.Filters;
using Sitecore.TestStar.Core.Utility;
using Sitecore.TestStar.Core.Extensions;
using Sitecore.TestStar.Core.Managers;
using System.Web.UI;
using Sitecore.TestStar.Core.Entities;
using System.Text;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.IO;
using Cons = Sitecore.TestStar.Core.Utility.Constants;
using Sitecore.TestStar.Core.Providers;

namespace Sitecore.TestStar.UI.sublayouts {
	public partial class UnitTestPage : UserControl {

		#region Events

		protected void Page_Load(object sender, EventArgs e) {

		}

		#endregion Events
	}
}