text:
using namespace UAlbertaBot;

HLSearch::HLSearch() :_tt(20000), _cache(20000), _bestMove(StrategyManager::ProtossHighLevelSearch)
{
}

HLSearch::~HLSearch()
{
}

long long HLSearch::search(double timeLimit, int frameLimit, int maxHeight)
{

	_stats.clear();
	_stats.startTimer();
	_timeUp = false;
	_timeLimitMs = timeLimit;

	HLState state(BWAPI::Broodwar, BWAPI::Broodwar->self(), BWAPI::Broodwar->enemy());
	int currentEval = state.evaluate(BWAPI::Broodwar->self()->getID());
	Logger::LogAppendToFile(UAB_LOGFILE, "\n\nStarting search at frame %d, static eval: %d\n",
		BWAPI::Broodwar->getFrameCount(),
		currentEval);

	//if (currentEval > 150 || currentEval < -200)
	//{
	//	Logger::LogAppendToFile(UAB_LOGFILE, "Game seems decided, skipping HL search\n");
	//	return _stats.getRunningTimeMilliSecs();
	//}
	_minFrame = 1000000;
	Logger::LogAppendToFile(UAB_LOGFILE, _stats.header() + " score\tbest move\tmin frame\tmax frame\n");
	//for (int height = 2; height <= maxHeight && !_timeUp; height += 2)
	//{
	int height = maxHeight;
	for (int frames = 2000; frames <= frameLimit && !_timeUp; frames += 2000)
	{
		_maxFrame = 0;
		int prevFrame = _minFrame;
		_minFrame = 1000000;
		int score = alphaBeta(state, 0, height, state.currentFrame() + frames, BWAPI::Broodwar->self()->getID(), HLMove(), MIN_SCORE, MAX_SCORE);
		Logger::LogAppendToFile(UAB_LOGFILE, _stats.toString());
		Logger::LogAppendToFile(UAB_LOGFILE, " %d %s %d %d\n", score, _bestMove.toString().c_str(), _minFrame - state.currentFrame(), _maxFrame - state.currentFrame());
		if (prevFrame == _minFrame || (_minFrame - state.currentFrame()) > frameLimit)
		{
			break;
		}
	}

	return _stats.getRunningTimeMilliSecs();
}

int HLSearch::alphaBeta(const HLState& state, int depth, int height, int frameLimit, int turn, const HLMove &firstSideMove, int alpha, int beta)
{
	_stats.incNodeCount();

	if (firstSideMove.isEmpty() && (height <=0 || state.currentFrame() >= frameLimit || state.gameOver())){
		if (state.currentFrame() < _minFrame)
		{
			_minFrame = state.currentFrame();
		}
		if (state.currentFrame() > _maxFrame)
		{
			_maxFrame = state.currentFrame();
		}
		return state.evaluate(turn);
	}
	if (_stats.getNodeCount() % 10 && _stats.getRunningTimeMilliSecs() > _timeLimitMs)
	{
		_timeUp = true;
	}
	int score = MIN_SCORE;
	int al = alpha;
	HLMove bestMove;
	int i = 0;
	HLMove ttBest;
	if (firstSideMove.isEmpty())
	{
		_stats.incTTquery();
		const HLEntry &e = _tt.lookup(state);
		if (e._hash == state.getHash())
		{
			_stats.incTTfound();
			ttBest = e._bestMove;
		}
	}
	else
	{
		_stats.incTTquery();
		const HLEntry &e = _tt.lookup(state, depth,firstSideMove);
		if (e._hash == state.getHash(depth, firstSideMove))
		{
			_stats.incTTfound();
			ttBest = e._bestMove;
		}
	}
	////todo: use value to return or at least shrink alpha-beta window?

	auto &moves = state.getMoves(turn);
	UAB_ASSERT(moves.size() != 0, "No moves generated at depth %d", depth);
	if (!ttBest.isEmpty())
	{
		auto it=std::find(moves.begin(), moves.end(), ttBest);
		UAB_ASSERT(it != moves.end(), "Couldn't find best move among valid moves");
		if (it != moves.end())
		{
			std::iter_swap(it, moves.begin());
		}
	}
	//std::sort(moves.begin(), moves.end(), [this, &state, depth](const HLMove &m1, const HLMove &m2)
	//{
	//	_stats.incTTquery();
	//	const HLEntry &e1 = _tt.lookup(state, depth, m1);
	//	if (e1._hash != state.getHash(depth, m1))
	//	{
	//		return false;
	//	}
	//	_stats.incTTfound();
	//	_stats.incTTquery();
	//	const HLEntry &e2 = _tt.lookup(state, depth, m2);
	//	if (e2._hash != state.getHash(depth, m2))
	//	{
	//		return true;
	//	}
	//	_stats.incTTfound();
	//	return e1._value > e2._value;
	//});

	for (auto it = moves.begin(); it != moves.end() && !_timeUp;it++){
		auto m = *it;
		//Logger::LogAppendToFile(UAB_LOGFILE, "Searching depth %d, move %s, move %s\n", depth, firstSideMove.toString().c_str(), m.toString().c_str());

		int value;
		if (firstSideMove.isEmpty()){
			value = alphaBeta(state, depth + 1, height - 1, frameLimit, 1 - turn, m, -beta, -al);
		}
		else{

			//Logger::LogAppendToFile(UAB_LOGFILE, "Start frame: %d\n", newState.currentFrame());

			std::array < HLMove, 2 > movePair;
			if (turn == 1){
				movePair = std::array < HLMove, 2 > { {firstSideMove, m} };
			}
			else{//move for player 1 first
				movePair = std::array < HLMove, 2 > { {m, firstSideMove} };
			}
			//Logger::LogAppendToFile(UAB_LOGFILE, "Turn %d depth %d Checking moves: %s %s hash: %u\n", turn, depth,
			//	firstSideMove.toString().c_str(), m.toString().c_str(), state.getHash(depth,movePair));
			try
			{
				_stats.incCacheQuery();
				const auto &entry = _cache.lookup(state, depth, movePair);
				if (entry._hash == state.getHash(depth, movePair))//found
				{
					_stats.incCacheFound();
					//Logger::LogAppendToFile(UAB_LOGFILE, "Moves "+ firstSideMove.toString() + m.toString()+" matches\n");
					//Logger::LogAppendToFile(UAB_LOGFILE, " hashes: %u %u\n", entry._hash, entry._state.getHash());
					if (state.currentFrame() == entry._state.currentFrame()){//didn't progress
						//Logger::LogAppendToFile(UAB_LOGFILE, "No progress (cached)");
						continue;
					}
					value = alphaBeta(entry._state, depth + 1, height - 1, frameLimit, 1 - turn, HLMove(), -beta, -al);
				}
				else
				{
					HLState newState(state);
					newState.applyAndForward(depth, frameLimit-newState.currentFrame(), movePair);
					if (state.currentFrame() == newState.currentFrame()){//didn't progress
						//Logger::LogAppendToFile(UAB_LOGFILE, "No progress");
						continue;
					}
					_stats.addFwd(newState.currentFrame() - state.currentFrame());
					_cache.store(state, depth, movePair, newState);
					value = alphaBeta(newState, depth + 1, height - 1, frameLimit, 1 - turn, HLMove(), -beta, -al);
				}

			}
			catch (const BOSS::Assert::BOSSException &){
				//Logger::LogAppendToFile(UAB_LOGFILE, "No Legal build order");
				continue;//couldn't find legal build order, skip
			}

		}

		i++;
		if (value > score){
			score = value;
			bestMove = m;
			if (value > alpha){
				al = value;
				if (al >= beta){
					break;
				}
			}
		}
		//break;//temporary, let's only check 1 move wide
	}
	if (!_timeUp)
	{
		_stats.addBF(i);

		if (firstSideMove.isEmpty())
		{
			_tt.store(state, bestMove, score, alpha, beta, height);
		}
		else
		{
			_tt.store(state, depth, firstSideMove, bestMove, score, alpha, beta, height);
		}
	}
	if (depth == 0){
		if (!bestMove.isEmpty())
		{
			_bestMove = bestMove;
		}
		else if (height == 2)//only use default move if first ID iteration
		{
			//_bestMove = HLMove(StrategyManager::ProtossHighLevelSearch);
			Logger::LogAppendToFile(UAB_LOGFILE, "Couldn't find a strategy, using default\n");
		}
	}

	return score;
}

HLMove HLSearch::getBestMove()
{
	return _bestMove;
}

//std::vector<Squad> HLSearch::getSquads(const std::set<BWAPI::UnitInterface*> & combatUnits)
//{
//	auto searchSquads = _bestMove.getSquads();
//	std::set<BWAPI::UnitInterface*> unitsToAdd(combatUnits.begin(),combatUnits.end());
//
//	//remove non combat units
//	for (auto &s : searchSquads){
//		for (unsigned int i = 0; i < s.getUnits().size();i++){
//			auto &u = s.getUnits()[i];
//			if (combatUnits.count(u) == 0){//if unit is not combat, remove it from squad
//				s.removeUnit(u);
//				i--;
//			}
//			else{//unit already assigned
//				unitsToAdd.erase(u);
//			}
//		}
//	}
//
//	//assign remaining units
//	for (auto &u : unitsToAdd){
//		bool assigned=false;
//		for (auto &s : searchSquads){
//			if (u->getRegion() == s.getRegion()){
//				s.addUnit(u);
//				assigned = true;
//				break;
//			}
//		}
//		if (!assigned){//create new squad
//			std::vector<BWAPI::UnitInterface *> unit(1, u);
//			searchSquads.push_back(HLSquad(unit, SquadOrder()));
//		}
//	}
//
//	std::vector<Squad> squads(searchSquads.size());
//	//transform HLSquad into Squad
//	std::transform(searchSquads.begin(), searchSquads.end(), squads.begin(),
//		[](const HLSquad &s){return static_cast<Squad>(s); });
//
//	return squads;
//}


text:
local pairs = pairs
local ipairs = ipairs
local type = type
local print = print
local unpack = unpack
local setmetatable = setmetatable
local require = require
local error = error
local assert = assert
local pb = require "pb"
local string_format = string.format
local string_gmatch = string.gmatch
local net_api_list = require("net.net_api_list")
local table_remove = table.remove
local lower = string.lower
local DIS_TYPE = DIS_TYPE --require("net.lua_dispatcher_type")
local lua_distribute = lua_distribute
local client_rpc = require("net.client_rpc")

local SIMULATION_SERVER = false

local function make_rpc(rpc, name, ...)
    local rf = rpc.remoteF[name]
    if not rf then
        error(string_format("can't find remote function named %s", name))
        return nil
    end

    local code_type = rf.type
    local code = rf.code

    local bytes = assert(pb.encode(code_type, ...))

    return code, bytes
end

local function parse_rpc(rpc, code, bytes)
    local rf = rpc.localF[code]
    if not rf then
        error(string_format("rfid(%d) not found in LocalF", rfid))
        return false
    end

    local lf = client_rpc[rf.name]
    if lf then
        local data2 = assert(pb.decode(rf.type, bytes))
        lf(data2)

        local key = "rpc_" .. rf.name
        lua_distribute(lower(key), unpack(data2))

    end
    return true, rf.name
end

--模拟服务端处理,call server_rpc.lua 方法
local function simulation_remote_rpc(rpc, code, bytes)
    local rf = rpc.localF[code]
    if not rf then
        error(string_format("rfid(%d) not found in LocalF", code))
        return false
    end
    local remote_rpc = require("net.server_rpc")

    local lf = remote_rpc[rf.name]
    if lf then
        local data2 = assert(pb.decode(rf.type, bytes))
        lf(data2)
    end
    return true, rf.name
end

--模拟发送
local function simulation_client_rpc(rpc, code, data)
    local rf = rpc.localF[code]
    if not rf then
        error(string_format("rfid(%d) not found in LocalF", code))
        return false
    end

    local bytes = assert(pb.encode(rf.type, data))
    parse_rpc(rpc, code, bytes)
end

local function parse_protocol(rpc)
    local rpcS = {}
    local rpcC = {}

    -- parse server
    -- parse client
    for k, v in pairs(net_api_list) do
        -- if type(v) == "table" then
        local rf = {}
        rf.type = v.type
        rf.code = v.code
        rf.name = k
        rpcC[rf.code] = rf
        rpcS[k] = rf
        -- end
    end

    rpc.remoteF = rpcS
    rpc.localF = rpcC
end

local function init(rpc)
    parse_protocol(rpc)
    print("--------------------- init rpc ----------------------")
    Logger.LogTable(rpc.remoteF)
    Logger.LogTable(rpc.localF)
end

local function debug_list_all_rpc(rpc)
    local log = "<color=yellow>===========remote============\n"
    for name, rf in pairs(rpc.remoteF) do
        log = string_format("%s  %d %s %s\n", log, name, rf.type, rf.name)
    end
    local client_rpc = require("net.client_rpc")
    log = string_format("%s\n===========local==========\n", log)
    for code, rf in pairs(rpc.localF) do
        log = string_format("%s %s %d %s\n", log, code, rf.type, client_rpc[rf.name])
    end
    print("%s</color>", log)
end

local main_net = CS.Hugula.Net.NetWork.main
local mt = {
    __index = function(table, key)
        return function(rpc, ...)
            local code, bytes = rpc:make_rpc(key, ...)
            if SIMULATION_SERVER then
                Logger.Log("data:", pb.tohex(bytes))
                Logger.Log(
                    string.format("<color=#40ad23> send to SIMULATION_SERVER key=%s,code=%d,time=%d </color> ", key, code, os.time())
                )
                simulation_remote_rpc(rpc, code, bytes)
            else

                main_net:SendBytes(code, bytes)
            end
        end
    end
}

local function reload(rpc)
    main_net = CS.Hugula.Net.NetWork.main
    package.loaded["net.net_api_list"] = nil
    net_api_list = require("net.net_api_list")

    init(rpc)
end

local function new()
    local ins = {}
    ins.init = init
    ins.make_rpc = make_rpc
    ins.parse_rpc = parse_rpc
    ins.simulation_client_rpc = simulation_client_rpc
    ins.debug_list_all_rpc = debug_list_all_rpc
    ins.reload = reload
    setmetatable(ins, mt)
    return ins
end

return new()

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import styled from '@emotion/styled';

import SelectControl from 'app/components/forms/selectControl';
import NumberDragControl from 'app/components/numberDragControl';
import Tooltip from 'app/components/tooltip';
import {t, tct} from 'app/locale';
import space from 'app/styles/space';
import Input from 'app/views/settings/components/forms/controls/input';
import {
  AlertRuleThresholdType,
  ThresholdControlValue,
} from 'app/views/settings/incidentRules/types';

type Props = ThresholdControlValue & {
  type: string;
  disabled: boolean;
  disableThresholdType: boolean;
  placeholder: string;
  onChange: (value: ThresholdControlValue, e: React.FormEvent) => void;
  onThresholdTypeChange: (thresholdType: AlertRuleThresholdType) => void;
};

type State = {
  currentValue: string | null;
};

class ThresholdControl extends React.Component<Props, State> {
  state: State = {
    currentValue: null,
  };

  handleThresholdChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const {value} = e.target;

    // Only allow number and partial number inputs
    if (!/^[0-9]*\.?[0-9]*$/.test(value)) {
      return;
    }

    const {onChange, thresholdType} = this.props;

    // Empty input
    if (value === '') {
      this.setState({currentValue: null});
      onChange({thresholdType, threshold: ''}, e);
      return;
    }

    // Only call onChange if the new number is valid, and not partially typed
    // (eg writing out the decimal '5.')
    if (/\.+0*$/.test(value)) {
      this.setState({currentValue: value});
      return;
    }

    const numberValue = Number(value);

    this.setState({currentValue: null});
    onChange({thresholdType, threshold: numberValue}, e);
  };

  /**
   * Coerce the currentValue to a number and trigger the onChange.
   */
  handleThresholdBlur = (e: React.FocusEvent<HTMLInputElement>) => {
    if (this.state.currentValue === null) {
      return;
    }

    const {onChange, thresholdType} = this.props;
    onChange({thresholdType, threshold: Number(this.state.currentValue)}, e);
    this.setState({currentValue: null});
  };

  handleTypeChange = ({value}, _) => {
    const {onThresholdTypeChange} = this.props;
    onThresholdTypeChange(value);
  };

  handleDragChange = (delta: number, e: React.MouseEvent) => {
    const {onChange, thresholdType, threshold} = this.props;
    const currentValue = threshold || 0;
    onChange({thresholdType, threshold: currentValue + delta}, e);
  };

  render() {
    const {currentValue} = this.state;
    const {
      thresholdType,
      threshold,
      placeholder,
      type,
      onChange: _,
      onThresholdTypeChange: __,
      disabled,
      disableThresholdType,
      ...props
    } = this.props;

    return (
      <div {...props}>
        <SelectControl
          isDisabled={disabled || disableThresholdType}
          name={`${type}ThresholdType`}
          value={thresholdType}
          options={[
            {value: AlertRuleThresholdType.BELOW, label: t('Below')},
            {value: AlertRuleThresholdType.ABOVE, label: t('Above')},
          ]}
          onChange={this.handleTypeChange}
        />
        <StyledInput
          disabled={disabled}
          name={`${type}Threshold`}
          placeholder={placeholder}
          value={currentValue ?? threshold ?? ''}
          onChange={this.handleThresholdChange}
          onBlur={this.handleThresholdBlur}
          // Disable lastpass autocomplete
          data-lpignore="true"
        />
        <DragContainer>
          <Tooltip
            title={tct('Drag to adjust threshold[break]You can hold shift to fine tune', {
              break: <br />,
            })}
          >
            <NumberDragControl step={5} axis="y" onChange={this.handleDragChange} />
          </Tooltip>
        </DragContainer>
      </div>
    );
  }
}

const StyledInput = styled(Input)`
  /* Match the height of the select controls */
  height: 40px;
`;

const DragContainer = styled('div')`
  position: absolute;
  top: 4px;
  right: 12px;
`;

export default styled(ThresholdControl)`
  position: relative;
  display: grid;
  align-items: center;
  grid-template-columns: 1fr 3fr;
  grid-gap: ${space(1)};
`;


text:
import time
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter

from sklearn.metrics import roc_curve, auc
from sklearn.ensemble import RandomForestClassifier
from sklearn.cross_validation import StratifiedShuffleSplit
from sklearn.utils import shuffle

from scipy import interp

import pickle

# My code
import visualization.viz as viz

def get_tpr_fpr(X, y, clf, cross_val):
    '''
    GOAL:
        Get the stats to plot an ROC curve
    INPUT:
        X - (samples x features) numpy array
        y - (samles,) numpy array
        clf - classifier to use
        cross_val - cross-validation strategy to use
    '''
    t1 = time.time()
    # collect vals for the ROC curves
    tpr_list = []
    mean_fpr = np.linspace(0, 1, 100)
    auc_list = []

    # Get the false-positive and true-positive rate
    for i, (train, test) in enumerate(cross_val):
        clf.fit(X[train], y[train])
        y_pred = clf.predict_proba(X[test])[:, 1]

        # get fpr, tpr
        fpr, tpr, thresholds = roc_curve(y[test], y_pred)
        roc_auc = auc(fpr, tpr)
        tpr_list.append(interp(mean_fpr, fpr, tpr))
        tpr_list[-1][0] = 0.0
        auc_list.append(roc_auc)

        if (i % 10 == 0):
            print('{perc}% done! {time}s elapsed'.format(
                 perc=100*float(i)/cross_val.n_iter, time=(time.time() - t1))
                 )
    return tpr_list, auc_list, mean_fpr

def roc_curve_cv(X, y, clf, cross_val, color='blue',
                 path='/home/irockafe/Desktop/roc.pdf',
                 save=False, plot=False,
                 ):
    '''
    PURPOSE:
        Creates an ROC curve
    INPUT:
        X - (samples x features) numpy array
        y - (samles,) numpy array
        clf - classifier to use
        cross_val - cross-validation strategy to use
        color - color to plot ROC curve
        path- where to dump a pdf of the cross-validated ROC curve
    '''
    tpr_list, auc_list, mean_fpr = get_tpr_fpr(X, y, clf, cross_val)
    # Return the stuff you can use to plot
    print 'Plottttt!'
    my_plt = viz.roc_curve(tpr_list, mean_fpr, auc_list,
                           cross_val, path, color=color)
    if plot:
        my_plt.show()

    return my_plt

def roc_curve_cv_null(X, y, clf, cross_val, num_shuffles=5, color='black',
                      path='/home/irockafe/Desktop.roc.pdf',
                      save=False, plot=True,
                      ):
    '''
    PURPOSE:
        Creates a null ROC curve by shuffling class labels
    INPUT:
        X - (samples x features) numpy array
        y - (samles,) numpy array
        clf - classifier to use (scikit)
        cross_val - cross-validation strategy to use (scikit crossvalidation
            object)
        num_shuffles - number of times to shuffle class labels
        color - color to plot the ROC curve
        path- where to dump a pdf of the cross-validated ROC curve
    '''
    tpr_list, auc_list, mean_fpr = get_tpr_fpr(X, y, clf, cross_val)
    # Return the stuff you can use to plot
    # shuffle y lots of times
    # collect tpr and fpr rates from each fold and shuffle
    # Then plot the mean of them all
    null_tpr_list = []
    null_auc_list = []
    for i in range(0, num_shuffles):
        # Iterate through the shuffled y vals and repeat with appropriate params
        # Retain the auc vals for final plotting of distribution
        y_shuffle = shuffle(y)
        cross_val.y = y_shuffle
        cross_val.y_indices = y_shuffle
        print ('Number of differences b/t original and' +
               'shuffle: {num}'.format(num=(y == cross_val.y).sum())
               )
        # Get auc values for number of iterations
        mean_tpr_null, auc_list_null, mean_fpr_null = get_tpr_fpr(X,
                                                                  y_shuffle,
                                                                  clf,
                                                                  cross_val)
        null_tpr_list += mean_tpr_null
        null_auc_list += auc_list_null

    my_plt = viz.roc_curve(null_tpr_list, mean_fpr_null, null_auc_list,
                           cross_val, path, color=color)
    if save:
        my_plt.savefig(path, format='pdf')
    if plot:
        my_plt.show()
    return my_plt

def rt_slice(df, rt_bounds):
    '''
    PURPOSE:
        Given dataframe (features x samples)
        with 'mz' and 'rt' column headers,
        retain only the features whose rt is between left
        and right bounds (1st and second entries of rt_bounds)
    INPUT:
        df - a pandas dataframe feature table with 'mz' and 'rt' column
            headers (i.e. from xcms), along with sample column headers
            and features along the rows
        rt_bounds: the boundaries of your rt_slice (left_bound, right_bound)
    OUTPUT:
        Feature table containing only the features between the specified.
        rt window. Note that it also contains the rt and mz columns, too.
    '''

    out_df = df.loc[(df['rt'] > rt_bounds[0]) &
                    (df['rt'] < rt_bounds[1])]
    return out_df

def plot_mz_rt(df, rt_bounds, path='/home/irockafe/Desktop/poop.pdf',
               bins=100):
    '''
    PURPOSE: Plot the mz/rt space of your dataset,
        along with histograms of the rt and mz presence
    INPUT:
        df - a pandas dataframe feature table,
            containing columns labeled 'rt' and 'mz', along with
            the sample columns
        rt_bounds - iterable containing retention time bounds
            for a particular slice: (left bound, right bound)
        path - where to save the figure to.
    OUTPUT:
        a pdf file showing mz/rt points and the rt-bound

    '''

    # the random data
    x = df['rt']
    y = df['mz']
    print np.max(x)
    print np.max(y)
    nullfmt = NullFormatter()         # no labels

    # definitions for the axes
    left, width = 0.1, 0.65
    bottom, height = 0.1, 0.65
    bottom_h = left_h = left + width + 0.02

    rect_scatter = [left, bottom, width, height]
    rect_histx = [left, bottom_h, width, 0.2]
    rect_histy = [left_h, bottom, 0.2, height]

    # start with a rectangular Figure
    plt.figure(1, figsize=(10, 10))

    axScatter = plt.axes(rect_scatter)
    axHistx = plt.axes(rect_histx)
    axHisty = plt.axes(rect_histy)

    # no labels
    axHistx.xaxis.set_major_formatter(nullfmt)
    axHisty.yaxis.set_major_formatter(nullfmt)

    # the scatter plot:
    axScatter.scatter(x, y, s=1)
    x_min = np.min(x)-50
    x_max = np.max(x)+50
    axScatter.set_xlim(x_min, x_max)
    y_min = np.min(y)-50
    y_max = np.max(y)+50
    axScatter.set_ylim(y_min, y_max)

    # Add vertical/horizontal lines to scatter and histograms
    axScatter.axvline(x=rt_bounds[0], lw=2, color='r', alpha=0.5)
    axScatter.axvline(x=rt_bounds[1], lw=2, color='r', alpha=0.5)

    axHistx.axvline(x=rt_bounds[0], lw=2, color='r', alpha=0.5)
    axHistx.axvline(x=rt_bounds[1], lw=2, color='r', alpha=0.5)

    axHistx.hist(x.dropna(), bins=bins)
    axHisty.hist(y.dropna(), bins=bins, orientation='horizontal')

    axHistx.set_xlim(axScatter.get_xlim())
    axHisty.set_ylim(axScatter.get_ylim())

    axScatter.set_ylabel('m/z', fontsize=30)
    axScatter.set_xlabel('Retention Time', fontsize=30)

    axHistx.set_ylabel('# of Features', fontsize=20)
    axHisty.set_xlabel('# of Features', fontsize=20)

    plt.savefig(path,
                format='pdf')
    plt.show()

def slice_and_predict(df, y, rt_window, not_samples, rf_estimators=1000,
                      n_iter=10, test_size=0.3, random_state=1,
                      mzrt_path='/home/irockafe/Desktop/poop.pdf',
                      roc_path='/home/irockafe/Desktop/roc.pdf',
                      ):
    '''
    PURPOSE: Slice mass-spec run into time-windows, then using
        that subset, try to predict outcome
    INPUT:
        df -
            pandas dataframe, from xcms, that includes columns with 'mz'
            and 'rt'. Do all your preprocessing before this function!
            (sample-thresholds, normalization, etc)
        y -
            class-labels encoded by scikit LabelEncoder.
            Make sure their order matches the dataframe's
        rt_window -
            (left_bound, right_bound) of retention times
        not_samples -
            a list of column headers to be removed from df before
            converting to feature table e.g. ['mz', 'rt', 'mzmin']
        rf_estimators -
            Number of trees in random forest
        n_iter -
            Number of cross-validation iterations
        test_size -
            fraction of samples to be held back as test set
        random_state -
            numpy random state
        mzrt_path -
            where file showing mzrt files will be saved
        roc_path -
            where file showing roc curve will be saved
    OUTPUT:
        pdf files
            - showing mzrt space, with histograms of density
            - showing cross-validated ROC curves
        auc_vals -
            The auc values from cross-validation (this way you can plot
            stuff)
    '''

    # plot selection
    plot_mz_rt(df, rt_window, path=mzrt_path)
    # Get slice and convert to feature table
    df_slice = rt_slice(df, rt_window)
    # remove columns with adduct info, extranneous stuff: mz, rt, etc
    samples_list = df_slice.columns.difference(not_samples)
    # convert to samples x features
    df_slice_processed = df_slice[samples_list].T
    X_slice = df_slice_processed.as_matrix()
    print "slice shape", X_slice.shape
    print 'y shape', y.shape

    # Run RF
    rf_estimators = rf_estimators
    n_iter = n_iter
    test_size = test_size
    random_state = random_state
    cross_val_rf = StratifiedShuffleSplit(y, n_iter=n_iter, test_size=test_size,
                                          random_state=random_state)
    clf_rf = RandomForestClassifier(n_estimators=rf_estimators,
                                    random_state=random_state)
    tpr_vals, auc_vals, mean_fpr = roc_curve_cv(X_slice, y, clf_rf,
                                                cross_val_rf,
                                                save=True, path=roc_path)
    return auc_vals

def make_sliding_window(min_val, max_val, width, step):
    '''
    PURPOSE: Create a sliding window given min, max, window width
        and step-size
    INPUT:
        min_val: Minimum value
        max_val: Maximum value
        width: Window width
        step: stepsize for each window
    OUTPUT:
        list of tuples [(left,right),(left2, right2),...]
        that give the bounds of a sliding window
    '''
    if step > width:
        raise ValueError("Your step should be less than" +
                         "or equal to the width of the window")
    left_bound = np.arange(min_val, max_val, step)
    right_bound = left_bound + width
    rt_bounds = zip(left_bound, right_bound)
    # remove any bounds that go past the maximum value
    for idx, i in enumerate(rt_bounds):
        if i[1] > max_val:
            rt_bounds.pop(idx)
    return rt_bounds

def sliding_rt_window_aucs(X_df, y, sliding_window, not_samples,
                           rf_trees=500, n_iter=3, test_size=0.3,
                           output_path='/home/irockafe/Desktop/'):

    all_aucs = np.full([len(sliding_window), n_iter], np.nan)
    for i, rt_slice in enumerate(sliding_window):
        print 'RT plot', rt_slice
        auc_vals = slice_and_predict(X_df, y, rt_slice,
                                     not_samples, rf_estimators=rf_trees,
                                     n_iter=n_iter, test_size=test_size,
                                     random_state=1,
                                     mzrt_path=(output_path +
                                                '/mzrt_window_%i.pdf' % i),
                                     roc_path=(output_path +
                                               'roc_window_%i.pdf' % i))
        # add aucs vals to array
        all_aucs[i] = auc_vals
        print '\n\n\n'+'-'*50+'NEXT ROUND'+'-'*50+'\n\n\n'
        # write aucs to file

    pickle.dump(all_aucs,
                open(output_path+'auc_vals.pkl', 'wb'))
    return all_aucs

def plot_auc_vs_rt(auc_vals, sliding_window, df,
                   path, plot=True, save=True):
    # plot auc_vals vs. median of sliding_window
    # get middle of sliding window points
    x = [np.mean(i) for i in sliding_window]
    y_mean = [np.mean(i) for i in auc_vals]
    y_std = [np.std(i) for i in auc_vals]

    # Set up the figure
    left, width = 0.1, 0.65
    bottom, height = 0.1, 0.65
    bottom_h = left + width + 0.02

    rect_scatter = [left, bottom, width, height]
    rect_histx = [left, bottom_h, width, 0.2]

    # Start with rect figure
    plt.figure(1, figsize=(10, 10))
    axScatter = plt.axes(rect_scatter)
    axHistx = plt.axes(rect_histx)
    # no labels
    nullfmt = NullFormatter()
    axHistx.xaxis.set_major_formatter(nullfmt)
    # scatter plot
    axScatter.scatter(x, y_mean, 100)
    axScatter.errorbar(x, y_mean, yerr=y_std,
                       fmt='o', capsize=5)

    # Histograms
    axHistx.hist(df['rt'], bins=100)

    # Labels
    axScatter.set_ylabel('AUC', fontsize=30)
    axScatter.set_xlabel('Retention Time', fontsize=30)
    axScatter.set_ylim([0.5, 1.0])

    axHistx.set_ylabel('# of Features', fontsize=20)
    # plot a histogram of the feature prevalence
    plt.savefig(path, format='pdf')
    plt.show()

#


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

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

using AChartEngine;
using AChartEngine.Charts;
using AChartEngine.Renderers;

namespace Sample.AChartEngine.Demo.Charts
{

	/// <summary>
	/// Trigonometric functions demo chart.
	/// </summary>
	public class TrigonometricFunctionsChart : AbstractDemoChart
	{
	  /// <summary>
	  /// Returns the chart name. </summary>
	  /// <returns> the chart name </returns>
	  public override string Name
	  {
		  get
		  {
			return "Trigonometric functions";
		  }
	  }

	  /// <summary>
	  /// Returns the chart description. </summary>
	  /// <returns> the chart description </returns>
	  public override string Desc
	  {
		  get
		  {
			return "The graphical representations of the sin and cos functions (line chart)";
		  }
	  }

	  /// <summary>
	  /// Executes the chart demo. </summary>
	  /// <param name="context"> the context </param>
	  /// <returns> the built intent </returns>
	  public override Intent Execute(Context context)
	  {
		string[] titles = new string[] {"sin", "cos"};
		IList<double[]> x = new List<double[]>();
		IList<double[]> values = new List<double[]>();
		int step = 4;
		int count = 360 / step + 1;
		x.Add(new double[count]);
		x.Add(new double[count]);
		double[] sinValues = new double[count];
		double[] cosValues = new double[count];
		values.Add(sinValues);
		values.Add(cosValues);
		for (int i = 0; i < count; i++)
		{
		  int angle = i * step;
		  x[0][i] = angle;
		  x[1][i] = angle;
		  double rAngle = Java.Lang.Math.ToRadians(angle);
		  sinValues[i] = Math.Sin(rAngle);
		  cosValues[i] = Math.Cos(rAngle);
		}
		int[] colors = new int[] {Color.Blue, Color.Cyan};
		PointStyle[] styles = new PointStyle[] {PointStyle.Point, PointStyle.Point};
		XYMultipleSeriesRenderer renderer = BuildRenderer(colors, styles);
		SetChartSettings(renderer, "Trigonometric functions", "X (in degrees)", "Y", 0, 360, -1, 1, Color.Gray, Color.LightGray);
		renderer.XLabels = 20;
		renderer.YLabels = 10;
		return ChartFactory.GetLineChartIntent(context, BuildDataset(titles, x, values), renderer);
	  }

	}

}


text:
package org.apache.sysml.test.gpu;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import org.apache.sysml.api.mlcontext.Matrix;
import org.apache.sysml.test.utils.TestUtils;
import org.junit.Test;

/**
 * Tests builtin binary ops on GPU
 */
public class BinaryOpTests extends GPUTests {

	private final static String TEST_NAME = "BinaryOpTests";
	private final int seed = 42;

	@Override
	public void setUp() {
		super.setUp();
		TestUtils.clearAssertionInformation();
		addTestConfiguration(TEST_DIR, TEST_NAME);
		getAndLoadTestConfiguration(TEST_NAME);
	}

	@Test
	public void testSolve() {
		// Test Ax = b
		// Dimensions of A = m * n
		// Dimensions of x = n * 1
		// Dimensions of b = m * 1

		double sparsity = 1.0; // Only dense matrices supported by "solve"
		final int[] sides = { 32, 33, 128, 256, 513, 2049 };
		for (int i = 0; i < sides.length; i++) {
			for (int j = i; j < sides.length; j++) {
				int m = sides[j];
				int n = sides[i];
				runSolveTest(sparsity, m, n);
			}
		}

	}

	/**
	 * Runs the test for solve (Ax = b) for input with given dimensions and sparsities
	 * A can be overdetermined (rows in A > columns in A)
	 *
	 * @param sparsity sparsity for the block A and b
	 * @param m        rows in A
	 * @param n        columns in A
	 */
	protected void runSolveTest(double sparsity, int m, int n) {
		String scriptStr = "x = solve(A, b)";
		System.out.println("In solve, A[" + m + ", " + n + "], b[" + m + ", 1]");
		Matrix A = generateInputMatrix(spark, m, n, sparsity, seed);
		Matrix b = generateInputMatrix(spark, m, 1, sparsity, seed);
		HashMap<String, Object> inputs = new HashMap<>();
		inputs.put("A", A);
		inputs.put("b", b);
		List<Object> outCPU = runOnCPU(spark, scriptStr, inputs, Arrays.asList("x"));
		List<Object> outGPU = runOnGPU(spark, scriptStr, inputs, Arrays.asList("x"));
		assertHeavyHitterPresent("gpu_solve");
		assertEqualObjects(outCPU.get(0), outGPU.get(0));
	}
}


text:
require File.dirname(__FILE__) + '/../../test_helper'
require 'rest/accounts_controller'

require 'json'
# assert_response status_code
# assert_redirect
# assert_redirect_to
# Re-raise errors caught by the controller.
class Rest::AccountsController; def rescue_action(e) raise e end; end

class AccountsControllerTest < Test::Unit::TestCase

  fixtures  :account_types,
            :account_type_values,
            :accounts,
            :databases,
            :data_types,
            :detail_status,
            :details,
            :detail_value_propositions,
            :entities,
            :entities2details,
            :relation_side_types,
            :relations,
            :instances,
            :detail_values,
            :integer_detail_values,
            :date_detail_values,
            :ddl_detail_values,
            :links,
            :user_types,
            :users

  def setup
    @controller   = Rest::AccountsController.new
    @request      = ActionController::TestRequest.new
    @response      = ActionController::TestResponse.new

    @db1_admin_user_id = 2
  end

  def test_without_login
    assert true
#    id = 1
#    get :show, {:format => 'json', :id => id}, {'user' => nil}
#    assert_response 401
#    json = %Q~{"errors": ["Please login to consume the REST API"]}~
#    assert_equal json, @response.body
  end

  def test_accessing_irrelevant_item
    res_id = 3
    res_name = 'Account'
    user = User.find @db1_admin_user_id
    json = {:errors =>["#{res_name}[#{res_id}] does not belong to User[#{user.id}] (\"#{user.login}\")"]}.to_json
    get :show, {:format => 'json', :id => 3}, {'user' => user}
    assert_equal json, @response.body
  end

  def test_get_all
    # CASE 01: GET /accounts
    user = User.find @db1_admin_user_id
    ######################################################################
    #                           CASE 01
    #   GET /accounts
    ######################################################################
    json = Account.find(:all)
    get :index, {:format => 'json'}, {'user' => user}
    #assert_equal '', @response.body
    result = JSON.parse(@response.body)
    assert_response :success
    assert_equal json.length, result['resources'].length
    #JSON.parse(json)

  end

  def test_get_all_with_pagination
    # CASE 01: Mention of start_index and max_results
    # CASE 02: Mention of Order by with direction
    # CASE 03: Mention of Order by without direction
    # CASE 04: Mention a condition also

    user = User.find_by_id(@db1_admin_user_id)

    parent_resource = :asdf
    parent_id = nil
    start_index = 0
    max_results = 3
    order_by = 'name'
    direction = 'DESC'
    table_name = 'details'
    conditions = 'database_id=6'
    #total_records = Detail.count_by_sql "SELECT COUNT(*) FROM  #{table_name} WHERE #{conditions}"
    conditions = 'id=50'

    total_records = Account.count
    max_results = 3
    #########################################################
    #                        CASE 01
    #        Mention of start_index and max_results
    #########################################################
    get :index, {
      parent_resource => parent_id,
      :format => 'json',
      :start_index => start_index,
      :max_results => max_results},
      {'user' => user}

    #assert_equal '', @response.body
    assert_response 200
    result = @response.body
    result = JSON.parse result
    assert_equal max_results, result['resources'].length
    assert_equal total_records, result['total_resources']

    order_by = 'name'
    direction = 'desc'
    #########################################################
    #                        CASE 02
    #        Mention of order by with direction
    #########################################################
    get :index, {
      parent_resource => parent_id,
      :format => 'json',
      :start_index => start_index,
      :max_results => max_results,
      :order_by => order_by,
      :direction => direction
    },
      {'user' => user}

    #assert_equal '', @response.body
    assert_response 200
    result = @response.body
    result = JSON.parse result
    assert_equal max_results, result['resources'].length
    assert_equal 'desc', result['direction']

    #########################################################
    #                        CASE 03
    #        Mention of order by with direction
    #########################################################
    get :index, {
      parent_resource => parent_id,
      :format => 'json',
      :start_index => start_index,
      :max_results => max_results,
      :order_by => order_by,
      #:direction => direction
    },
      {'user' => user}

    #assert_equal '', @response.body
    assert_response 200
    result = @response.body
    result = JSON.parse result
    assert_equal max_results, result['resources'].length
    assert_equal 'asc', result['direction']

    conditions = "country='Russia'"
    #########################################################
    #                        CASE 04
    #        Mention of order by specifying condition
    #########################################################
    get :index, {
      parent_resource => parent_id,
      :format => 'json',
      :start_index => start_index,
      :max_results => max_results,
      :order_by => order_by,
      :conditions => conditions
    },
      {'user' => user}
    #assert_equal '', @response.body
    assert_response 200
    result = @response.body
    result = JSON.parse result
    assert_equal 1, result['resources'].length
    assert_equal 'asc', result['direction']

  end

  def test_get_single
    # CASE 01: GET /accounts/:id with all ok
    # CASE 02: GET /accounts/:id with wrong id
    user = User.find @db1_admin_user_id

    account = 1
    ######################################################################
    #                           CASE 01
    #   GET /accounts/id with all ok
    ######################################################################
    model = Account.find(account)
    get :show, {:format => 'json', :id => account}, {'user' => user}
    assert_response :success
    assert_similar model, @response.body

    account = 79884 #1
    ######################################################################
    #                           CASE 02
    #   GET /accounts/id with wrong id
    ######################################################################
    json = {:errors => ["Account[#{account}] does not exists"]}.to_json
    get :show, {:format => 'json', :id => account}, {'user' => user}
    assert_response 404
    assert_equal json, @response.body
    #JSON.parse(json)

  end

  def test_post
    # CASE 01: POST /accounts with all ok
    # CASE 02: POST /accounts with resource missing
    # CASE 03: POST /accounts with resource but account_type missing
    # CASE 04: POST /accounts with resource but account_type wrong.
    user = User.find @db1_admin_user_id
    account =
      {
        :account_type_url     => 'http://localhost:3000/account_types/1.json',
        :name                 => 'test_account',
        :street               =>  'I-8/2 Street 35',
        :zip_code             => '051000',
        :city                 => 'Islamabad',
        :country              => 'Pakistan',
        :status               => 'active',
        :end_date             => '2105-05-22',
#        :subscription_id      => 'PAK-98745',
#        :subscription_gateway => 'No Gateway',
        :vat_number           => 'asdfs',
#        :attachment_count     => 0
      }

    ###################################################################
    #                          CASE 01
    #    POST /accounts with all ok
    ###################################################################
    pre_count = Account.count
    post :create, {:format => 'json', :account => account.to_json}, {'user' => user}
    #assert_equal '', @response.body
    assert_response 201
    post_count = Account.count
    assert_equal 1, post_count - pre_count
    #assert_equal '', @response.body

    ###################################################################
    #                          CASE 02
    #    POST /accounts with resource missing
    ###################################################################
    json = {:errors => ['Provide account resource to be created/updated']}.to_json
    pre_count = Account.count
    post :create, {:format => 'json'}, {'user' => user}
    assert_response 400
    post_count = Account.count
    assert_equal 0, post_count - pre_count
    assert_equal json, @response.body

    account.delete :account_type_url
    ###################################################################
    #                          CASE 03
    #    POST /accounts with resource but without mention of account type id
    ###################################################################
    json = {:errors => ['Account type is not mentioend in account resource']}.to_json
    pre_count = Account.count
    post :create, {:format => 'json', :account => account.to_json},
      {'user' => user}
    assert_response 400
    post_count = Account.count
    assert_equal 0, post_count - pre_count
    assert_equal json, @response.body

    account[:account_type_url] = 'http://localhost:3000/account_types/19857.json'
    ###################################################################
    #                          CASE 04
    #    POST /accounts with resource but without mention of account type id
    ###################################################################
    json = {:errors => ["AccountType[19857] does not exists"]}.to_json
    pre_count = Account.count
    post :create, {:format => 'json', :account => account.to_json},
      {'user' => user}
    assert_response 404
    post_count = Account.count
    assert_equal 0, post_count - pre_count
    assert_equal json, @response.body

  end

  def test_put
    # CASE 01: GET an account, change its name and put it back.
    # CASE 02: PUT accounts/:id with wrong id
    # CASE 03: PUT accounts/:id with account resource missing
    user = User.find @db1_admin_user_id
    #####################################################################
    #                         CASE 01
    #   PUT /accounts
    #####################################################################

    account = JSON.parse(Account.find(1).to_json(:format => 'json'))

    account['name'] = 'TEST CHANGEOVER'

    put :update, {:format => 'json', :id => 1, :account => account.to_json},
      {'user' => user}
    model = Account.find(1)
    assert_response 200
    assert_similar model, @response.body
    #assert_equal '', @response.body

    # JUST TO CLEARE THE TEST
    account['url'] = 'http://www.myowndb.com/accounts/1454.json'
    #####################################################################
    #                         CASE 02
    #   PUT /accounts with wrong id
    #####################################################################
    json = {:errors => ["Account[1454] does not exists"]}.to_json
    put :update, {:format => 'json', :id => 1454, :account => account.to_json},
      {'user' => user}
    #assert_response 404
    assert_equal json, @response.body

    #####################################################################
    #                         CASE 03
    #   PUT /accounts with account resource missing
    #####################################################################
    json = {:errors => ["Provide account resource to be created/updated"]}.to_json
    put :update, {:format => 'json', :id => 1454}, {'user' => user}
    assert_response 400
    assert_equal json, @response.body

  end

  def test_put_without_lock_version
    user = User.find @db1_admin_user_id
    account = JSON.parse(Account.find(1).to_json(:format => 'json'))

    account['name'] = 'TEST CHANGEOVER'
    account.delete('lock_version')

    put :update, {:format => 'json', :id => 1, :account => account.to_json},
      {'user' => user}
    json = {:errors => ['Provide lock_version for update/delete operations']}.to_json
    assert_response 400
    assert_equal json, @response.body
  end

  def test_get_and_put
    user = User.find @db1_admin_user_id

    get :show, {:format => 'json', :id => 1}, {'user' => user}
    account = JSON.parse(@response.body)

    account['name'] = 'GET AND PUT TEST'

    put :update, {:format => 'json', :id => 1, :account => account.to_json},
      {'user' => user}
    assert_response 200
    new_val = JSON.parse(@response.body)
    assert_equal account['name'], new_val['name']
  end

  def test_get_and_put_conflict
    id = 1
    res_id = 78
    user = User.find @db1_admin_user_id

    get :show, {:format => 'json', :id => id}, {'user' => user}
    resource = JSON.parse(@response.body)

    resource['name'] = 'GET AND PUT TEST'
    resource['url'] = 'http://localhost:300/accounts/' + res_id.to_s + '.json'

    json = {:errors => ["Requested ID is #{id} and ID in resource is #{res_id}. Are you dispatching your resource at the right location?"]}.to_json
    put :update, {:format => 'json', :id => id, :account => resource.to_json},
      {'user' => user}
    assert_response 400
    assert_equal json, @response.body
  end

  def test_get_and_put_version_conflict
    user = User.find_by_id @db1_admin_user_id

    id = 1
    res_name = 'account'

    get :show, {:format => 'json', :id => id}, {'user' => user}
    resource1 = JSON.parse(@response.body)

    resource1['name'] = 'GET AND PUT TEST'

    get :show, {:format => 'json', :id => id}, {'user' => user}
    resource2 = JSON.parse(@response.body)

    resource2['name'] = 'GET AND PUT TEST8'

    put :update, {:format => 'json', :id => id, res_name => resource1.to_json}, {'user' => user}
    #assert_equal '', @response.body
    assert_response 200
    new_val = JSON.parse(@response.body)
    assert_equal resource1['name'], new_val['name']

    msg = 'Attempted to update a stale object'
    put :update, {:format => 'json', :id => id, res_name => resource2.to_json}, {'user' => user}
    assert_response 409
    assert_equal msg, JSON.parse(@response.body)['message']

  end

  def test_delete
    # CASE 01: DELETE /accounts/:id with all ok
    # CASE 02: DELETE /accounts/:id with wrong id
    user = User.find @db1_admin_user_id

    account = 1
    lock_version = Account.find(account).lock_version.to_i
    ####################################################################
    #                           CASE 01
    #  DELETE /accounts/:id with all ok
    ####################################################################
    pre_count = Account.count
    delete :destroy, {:format => 'json', :lock_version => lock_version, :id => account},
      {'user' => user}
    post_count = Account.count
    assert_response 200
    assert_equal 1, pre_count - post_count

  end

  def test_delete_with_wrong_account
    user = User.find(@db1_admin_user_id)
    account = 18787 #1
    lock_version = 7979
    ####################################################################
    #                           CASE 02
    #  DELETE /accounts/:id with wrong id
    ####################################################################
    pre_count = Account.count
    json = {:errors => ["Account[#{account}] does not exists"]}.to_json
    delete :destroy, {:format => 'json', :lock_version => lock_version, :id => account},
      {'user' => user}
    post_count = Account.count
    assert_response 404
    assert_equal 0, pre_count - post_count
    assert_equal json, @response.body

  end

  def test_delete_with_version_conflict
    # Get a resource
    # Get its lock version
    # modify resource
    # post it back
    user = User.find @db1_admin_user_id

    id = 1
    res_name = 'account'
    lock_version = nil
    klass = Account

    get :show, {:format => 'json', :id => id}, {'user' => user}
    resource = JSON.parse(@response.body)

    lock_version = resource['lock_version']

    # PUT it back
    put :update, {:format => 'json', res_name => resource.to_json, :id => id},
      {'user' => user}

    msg = 'Attempted to delete a stale object'
    pre_count = klass.count
    delete :destroy, {:format => 'json', :id => id, :lock_version => lock_version},
      {'user' => user}
    post_count = klass.count
    assert_response 409
    assert_equal 0, post_count - pre_count
    assert_equal msg, JSON.parse(@response.body)['message']
  end

  def test_delete_without_lock_version

    user = User.find @db1_admin_user_id

    account = 1
    #lock_version = Account.find(account).lock_version.to_i
    ####################################################################
    #                           CASE 01
    #  DELETE /accounts/:id with all ok
    ####################################################################
    pre_count = Account.count
    json = {:errors => ['Provide lock_version for update/delete operations']}.to_json
    delete :destroy, {:format => 'json', :id => account}, {'user' => user}
    post_count = Account.count
    assert_response 400
    assert_equal json, @response.body
    assert_equal 0, pre_count - post_count

  end

end


text:
export function getJSON(url) {

  return () => fetch(url).then((res) => res.json());
}


text:
<?php

namespace App\Model\Entity;

use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Criteria;
use JsonSerializable;

/**
 * @ORM\Entity
 */
class CommentThread implements JsonSerializable
{
    /**
     * @ORM\Id
     * @ORM\Column(type="string", length=36, options={"fixed":true})
     */
    protected $id;

    /**
     * @ORM\OneToMany(targetEntity="Comment", mappedBy="commentThread")
     * @ORM\OrderBy({ "postedAt" = "ASC" })
     */
    protected $comments;

    public function addComment(Comment $comment)
    {
        $this->comments->add($comment);
    }

    /**
     * @return Comment[]
     */
    public function findAllPublic(): array
    {
        $publicComments = Criteria::create()
            ->where(Criteria::expr()->eq("isPrivate", false));
        return $this->comments->matching($publicComments)->getValues();
    }

    public function filterPublic(User $currentUser)
    {
        $publicComments = Criteria::create()
            ->where(Criteria::expr()->eq("isPrivate", false))
            ->orWhere(Criteria::expr()->eq("user", $currentUser));
        $this->comments = $this->comments->matching($publicComments);
    }

    public function jsonSerialize(): mixed
    {
        return [
            "id" => $this->getId(),
            "comments" => $this->comments->toArray()
        ];
    }

    public static function createThread($id)
    {
        $thread = new CommentThread();
        $thread->id = $id;
        $thread->comments = new ArrayCollection();
        return $thread;
    }

    /*
     * Accessors
     */

    public function getId(): ?string
    {
        return $this->id === null ? null : (string)$this->id;
    }

    public function getComments(): Collection
    {
        return $this->comments;
    }
}


text:
package com.intellij.util;

import consulo.util.dataholder.Key;
import javax.annotation.Nonnull;

/**
 * @author ik
 */
public interface CharTable {
  Key<CharTable> CHAR_TABLE_KEY = new Key<CharTable>("Char table");

  @Nonnull
  CharSequence intern(@Nonnull CharSequence text);

  @Nonnull
  CharSequence intern(@Nonnull CharSequence baseText, int startOffset, int endOffset);
}


text:
Build static sites using [Middleman](https://middlemanapp.com/) with [Gulp Starter](https://github.com/vigetlabs/gulp-starter).

Watch the screencast: https://youtu.be/-io8EeB3GHI

## Installation
1. Clone the repo — `git clone git@github.com:craigmdennis/middleman-gulp-starter.git`
1. Run setup — `bin/setup`

Setup installs Bundler, Gem dependencies and NPM dependencies.

## Developing using Middleman + Gulp Starter
1. Run `middleman serve` to use the `environments/development` config

Middleman will launch Gulp Starter as an external pipeline, in development mode.

## Production builds
1. Run `middleman build` to use the `environments/production` config

Middleman will minify HTML and Gulp starter will handle everything else

## Running Middleman without Gulp Starter
There may be [instances where you want to run the standard Middleman tasks without initiating Gulp Starter](https://github.com/craigmdennis/middleman-gulp-starter/pull/17#issue-147191865). To do that you simply need to pass in another environment. It doesn't even need to exist.

`middleman serve -e debug`

Now you can create `environments/debug` and add your own custom config in there.

## Revving Assets
You'll no longer be able to use the built in Middleman asset helpers like `javascript_include_tag` on their own. Instead, you'll have to add a set of **gulp_asset_helpers**. Filenames get hashed so you can cache them forever. [Learn more](helpers/README.md)

```ruby
gulp_asset_path('image/asset.jpg') # -> /image/logo-n39o4orb81.png
gulp_js_path('app.js')             # -> /javascripts/app-f43e9abc11.js
gulp_css_path('app.css')           # -> /stylesheets/app-d29e4cdb76.css
gulp_image_path('logo.png')        # -> /images/logo-n39o4orb81.png
```

So instead of this:
```erb
<%= image_tag 'logo.png', alt: 'logo' %>
```

You would do this:
```erb
<%= image_tag gulp_image_path('logo.png'), alt: 'logo' %>
```

Instead of this:
```erb
<%= stylesheet_link_tag :site %>
```

You would do this:
```erb
<%= stylesheet_link_tag gulp_css_path('site.css') %>
```

### When NOT to use the `gulp_asset_path` helpers
Due to the way that Middleman merges the temporary folder with the source folder in the sitemap, when you reference it you don't need to use the `gulp_image_path` helper as the files in the sitemap will already be the revved files.

```haml
- sitemap.resources.select{ |r| r.path.start_with?("images/some-folder-of-images") }.each do |image|
    = image_tag image.path
```

You can disable asset revving in production on the [`config.json`](https://github.com/craigmdennis/middleman-gulp-starter/blob/master/gulpfile.js/config.json#L78) at the bottom.

## Contributing
Please make sure to submit PRs to the latest feature branch.

## Release History
Please consult the [official changelog](https://github.com/craigmdennis/middleman-gulp-starter/blob/master/CHANGELOG.md)


text:
.. enviropy documentation master file, created by
   sphinx-quickstart on Thu Feb 23 01:53:38 2017.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Enviropy: statistical methods and plotting tools for environmental data
=======================================================================

Right now this is a fun project to learn Python with the goal of having a
convenient package for storing and analyzing environmental data.

--------------------

A quick overview
----------------

Connect to external data sources
    >>> from enviropy.external import read_manages3, read_gint
    >>> read_manages3('C:\path\to\Site.mdb')
    >>> read_gint('C:\path\to\gint.gpj')

The User Guide
--------------

A user guide is planned...

.. toctree::
   :maxdepth: 2

   user/install
   user/quickstart
   user/advanced

The API Documentation
---------------------

Specifics on functions, classes, and methods will go here...

.. toctree::
   :maxdepth: 2

   enviropy

The Contributor Guide
---------------------

Contributions are encouraged and welcomed...

.. toctree::
   :maxdepth: 2

   dev/contributing


text: exec mono ./DevIlExamples.exe "$@"


text:
import sys
from nose.tools import *
from job_queue import Job_Queue, try_using
from cStringIO import StringIO

class Capturing(list):
    def __enter__(self):
        self._stdout = sys.stdout
        sys.stdout = self._stringio = StringIO()
        return self
    def __exit__(self, *args):
        self.extend(self._stringio.getvalue().splitlines())
        sys.stdout = self._stdout

class Test_Job_Queue():

    from multiprocessing import Process as Bucket

    def test_init(self):
        jobs = Job_Queue(5)
        assert_equal(jobs._queued, [])
        assert_equal(jobs._running, [])
        assert_equal(jobs._completed, [])
        assert_equal(jobs._num_of_jobs, 0)
        assert_equal(jobs._max, 5)
        assert_false(jobs._finished)
        assert_false(jobs._closed)
        assert_false(jobs._debug)
        jobs._debug = True
        assert_true(jobs._debug)

    def populate(self,queue_size=5,job_size=10,debug=False):
        jobs = Job_Queue(queue_size)
        jobs._debug = debug

        def foo():
            return 10

        for x in range(job_size):
            jobs.append(self.Bucket(
                target = foo,
                args = [],
                kwargs = {},
                ))

        return jobs

    def test_empty(self):
	"""This case is when less jobs than the size of the queue are added
	"""
        jobs = self.populate(2,1)
        jobs.close()
        jobs.start()

    @raises(Exception)
    def test_some(self):
        jobs = self.populate()
        jobs.start()

    def test_length(self):
        jobs = self.populate()
        assert_equal( jobs._num_of_jobs, 10)
        assert_equal( len(jobs._queued), 10)
        assert_equal(len(jobs), 10)

    def test_closed(self):
        jobs = self.populate()
        assert_false(jobs._closed)
        jobs.close()
        assert_true(jobs._closed)

    def test_runs(self):
        jobs = self.populate()
        jobs.close()
        assert_false(jobs._finished)
        jobs.start()
        assert_true(jobs._finished)
        assert_false(jobs._all_alive())
        assert_equal(jobs._running,[])

    def test_runs_debug(self):
        with Capturing() as output:
            jobs = self.populate(debug=True)
            jobs.close()
            assert_false(jobs._finished)
            jobs.start()
            assert_true(jobs._finished)
            assert_false(jobs._all_alive())
            assert_equal(jobs._running,[])

        assert_true(len(output)>0)

    def test_runs_try_using(self):
        try_using("multiprocessing")
        try_using("threading")

class Test_Job_Queue_Threads(Test_Job_Queue):

    from threading import Thread as Bucket


text:
package nsmc.mongo

import java.net.InetAddress

import org.apache.spark.SparkConf

private[nsmc]
case class MongoConnectorConf(
  host: String,
  port: Int = MongoConnectorConf.DefaultPort,
  splitIndexed: Boolean,
  splitSize: Int,
  directToShards: Boolean,
  useShardChunks: Boolean,
  user: Option[String],
  password: Option[String]
  ) {
  def getDestination() : Destination = Destination(host, port, this)
}

private[nsmc]
object MongoConnectorConf extends nsmc.Logging {
  val DefaultPort = 27017
  val DefaultSplitSize = 4

  val ConnectionHostProperty = "spark.nsmc.connection.host"
  val ConnectionPortProperty = "spark.nsmc.connection.port"
  val ConnectionUserProperty = "spark.nsmc.user"
  val ConnectionPasswordProperty = "spark.nsmc.password"
  val PartitioningSplitIndexedProperty = "spark.nsmc.split.indexed.collections"
  val PartitioningSplitSizeProperty = "spark.nsmc.split.chunk.size"
  val PartitioningDirectToShardsProperty = "spark.nsmc.direct.to.shards"
  val PartitioningUseShardChunksProperty = "spark.nsmc.partition.on.shard.chunks"

  def apply(conf: SparkConf): MongoConnectorConf = {
    val host = conf.get(ConnectionHostProperty, InetAddress.getLocalHost.getHostAddress)
    val port = conf.getInt(ConnectionPortProperty, DefaultPort)
    val splitIndexed = conf.getBoolean(PartitioningSplitIndexedProperty, false)
    val splitSize = conf.getInt(PartitioningSplitSizeProperty, DefaultSplitSize)
    val directToShards = conf.getBoolean(PartitioningDirectToShardsProperty, false)
    val useShardChunks = conf.getBoolean(PartitioningUseShardChunksProperty, false)
    val user = conf.getOption(ConnectionUserProperty)
    val password = conf.getOption(ConnectionPasswordProperty)

    val userString = user.getOrElse("<absent>")
    val passwordString = if (password.isDefined) "<present>" else "<absent>"
    logDebug(s"host='$host' port='$port' user='$userString' password='$passwordString'")

    logDebug(s"$PartitioningSplitIndexedProperty=$splitIndexed")
    logDebug(s"$PartitioningSplitSizeProperty=$splitSize")
    logDebug(s"$PartitioningDirectToShardsProperty=$directToShards")
    logDebug(s"$PartitioningUseShardChunksProperty=$useShardChunks")

    MongoConnectorConf(host, port, splitIndexed, splitSize, directToShards, useShardChunks, user, password)
  }
}


text:
package com.ponkotuy.restype

import com.ponkotuy.data.Ship
import com.ponkotuy.parser.Query
import org.json4s._
import org.json4s.native.Serialization.write

import scala.util.matching.Regex

/**
 * @author ponkotuy
 * Date: 15/04/12.
 */
object Ship2 extends ResType {
  import ResType._

  override def regexp: Regex = s"\\A$GetMember/ship2\\z".r

  override def postables(q: Query): Seq[Result] = postablesFromObj(q.obj)

  def postablesFromObj(obj: JValue): Seq[Result] = {
    val ship = Ship.fromJson(obj)
    if (ship.isEmpty) Nil
    else {
      NormalPostable("/ship", write(ship), ver = 2, s"所持艦娘数 -> ${ship.size}") :: Nil
    }
  }
}


text:
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
const es = require("event-stream");
const _ = require("underscore");
const util = require("gulp-util");
const fs = require("fs");
const path = require("path");
const allErrors = [];
let startTime = null;
let count = 0;
function onStart() {
    if (count++ > 0) {
        return;
    }
    startTime = new Date().getTime();
    util.log(`Starting ${util.colors.green('compilation')}...`);
}
function onEnd() {
    if (--count > 0) {
        return;
    }
    log();
}
const buildLogPath = path.join(path.dirname(path.dirname(__dirname)), '.build', 'log');
try {
    fs.mkdirSync(path.dirname(buildLogPath));
}
catch (err) {
    // ignore
}
function log() {
    const errors = _.flatten(allErrors);
    const seen = new Set();
    errors.map(err => {
        if (!seen.has(err)) {
            seen.add(err);
            util.log(`${util.colors.red('Error')}: ${err}`);
        }
    });
    const regex = /^([^(]+)\((\d+),(\d+)\): (.*)$/;
    const messages = errors
        .map(err => regex.exec(err))
        .filter(match => !!match)
        .map(x => x)
        .map(([, path, line, column, message]) => ({ path, line: parseInt(line), column: parseInt(column), message }));
    try {
        fs.writeFileSync(buildLogPath, JSON.stringify(messages));
    }
    catch (err) {
        //noop
    }
    util.log(`Finished ${util.colors.green('compilation')} with ${errors.length} errors after ${util.colors.magenta((new Date().getTime() - startTime) + ' ms')}`);
}
function createReporter() {
    const errors = [];
    allErrors.push(errors);
    const result = (err) => errors.push(err);
    result.hasErrors = () => errors.length > 0;
    result.end = (emitError) => {
        errors.length = 0;
        onStart();
        return es.through(undefined, function () {
            onEnd();
            if (emitError && errors.length > 0) {
                if (!errors.__logged__) {
                    log();
                }
                errors.__logged__ = true;
                const err = new Error(`Found ${errors.length} errors`);
                err.__reporter__ = true;
                this.emit('error', err);
            }
            else {
                this.emit('end');
            }
        });
    };
    return result;
}
exports.createReporter = createReporter;


text:
package org.encog.examples.neural.benchmark;

import org.encog.Encog;
import org.encog.mathutil.matrices.Matrix;
import org.encog.mathutil.matrices.MatrixMath;

public class MatrixBenchmark {

	public static Matrix generateRandomMatrix(final int size) {
		final Matrix result = new Matrix(size, size);
		for (int row = 0; row < size; row++) {
			for (int col = 0; col < size; col++) {
				result.set(row, col, Math.random() * 100);
			}
		}
		return result;
	}

	public static void main(final String args[]) {
		long start, stop;

		start = System.currentTimeMillis();
		final Matrix a = MatrixBenchmark.generateRandomMatrix(500);
		final Matrix b = MatrixBenchmark.generateRandomMatrix(500);
		stop = System.currentTimeMillis();
		System.out.println("Setup matrix: " + ((stop - start)) / 1000.0);

		start = System.currentTimeMillis();
		MatrixMath.multiply(a, b);
		stop = System.currentTimeMillis();
		System.out.println("Multiply matrix: " + ((stop - start)) / 1000.0);
		Encog.getInstance().shutdown();
	}
}


text:
import * as ng from 'angular';

//  getString: function (string, scope, context) {
declare namespace ng.gettext {
	interface gettextCatalog {
		getString(string: string, scope?: any, context?: string): string;
	}
}


text:
<?php

namespace iakio\phpunit\smartrunner\commands\tests;

use iakio\phpunit\smartrunner\commands\RunCommand;
use iakio\phpunit\smartrunner\Cache;
use iakio\phpunit\smartrunner\FileSystem;
use iakio\phpunit\smartrunner\Phpunit;
use Prophecy\Argument;

class RunCommandTest extends \PHPUnit_Framework_TestCase
{
    /** @var  Cache */
    private $cache;

    /** @var  FileSystem */
    private $fs;

    /** @var  Phpunit */
    private $phpunit;

    /** @var  RunCommand */
    private $command;

    public function setUp()
    {
        $this->cache = $this->prophesize('iakio\phpunit\smartrunner\Cache');
        $this->fs = $this->prophesize('iakio\phpunit\smartrunner\FileSystem');
        $this->phpunit = $this->prophesize('iakio\phpunit\smartrunner\Phpunit');
        $this->command = new RunCommand($this->phpunit->reveal(), $this->cache->reveal(), $this->fs->reveal());
        $this->fs->cacheDirExists()->willReturn(true);
    }

    public function test_do_nothing_if_file_is_unknown()
    {
        $arg = 'unknownfile';
        $this->cache->get($arg)
            ->shouldBeCalled()
            ->willReturn([]);
        $this->fs->saveSuiteFile()->shouldNotBeCalled();
        $this->phpunit->exec()->shouldNotBeCalled();
        $this->command->run([$arg]);
    }

    public function test_run_itself_if_file_is_testable()
    {
        $arg = 'tests/CalcTest.php';
        $this->cache->get($arg)
            ->shouldBeCalled()
            ->willReturn([]);
        $this->fs->saveSuiteFile([$arg])->shouldBeCalled();
        $this->fs->fileExists(Argument::any())->willReturn(true);

        $this->phpunit->exec(Argument::any())->shouldBeCalled();
        $this->command->run([$arg]);
    }

    public function test_run_related_tests_if_file_is_cached()
    {
        $arg = 'src/Calc.php';
        $related_tests = [
            'tests/BankAccountTest.php',
            'tests/CalcTest.php',
        ];
        $this->cache->get($arg)
            ->shouldBeCalled()
            ->willReturn($related_tests);
        $this->fs->saveSuiteFile($related_tests)->shouldBeCalled();
        $this->fs->fileExists(Argument::any())->willReturn(true);
        $this->phpunit->exec(Argument::any())->shouldBeCalled();
        $this->command->run([$arg]);
    }

    public function test_show_messages_if_cache_directory_does_not_exist()
    {
        $arg = 'tests/CalcTest.php';
        $this->fs->cacheDir()->willReturn('.smartrunner');
        $this->fs->cacheDirExists()->willReturn(false);
        $this->fs->saveSuiteFile(Argument::any())->shouldNotBeCalled();
        $this->command->run([$arg]);
        $this->expectOutputString(
            ".smartrunner directory does not exist.\n".
            "Run `smartrunner init [phpunit.xml]` first.\n"
        );
    }

    public function test_show_usage_if_file_does_not_given()
    {
        $this->command->run([]);
        $this->expectOutputRegex('/Usage/');
    }

    public function test_remove_cache_if_files_do_not_exist()
    {
        $arg = 'src/Calc.php';
        $related_tests = [
            'tests/BankAccountTest.php',
            'tests/CalcTest.php',
        ];
        $this->cache->get($arg)
            ->shouldBeCalled()
            ->willReturn($related_tests);
        $this->cache->remove('src/Calc.php', 'tests/BankAccountTest.php')->shouldBeCalled();
        $this->fs->saveCache($this->cache)->shouldBeCalled();

        $this->fs->cacheDir()->willReturn('.smartrunner');
        $this->fs->fileExists('tests/BankAccountTest.php')->willReturn(false);
        $this->fs->fileExists('tests/CalcTest.php')->willReturn(true);
        $this->fs->saveSuiteFile(['tests/CalcTest.php'])->shouldBeCalled();
        $this->command->run([$arg]);
    }
}


text:
	# Input: Array of integers
	# Output: Sum of integers in array
	# Steps to solve the problem.
		# 1. Set up initial total variable
		# 2. Use for loop to iterate through array until end of array
		# 3. Add each array index value to total
		# 4. Return total

# 1. total initial solution
	# def total(given_array)
	# 	sum_of_array_values = 0
	# 	for i in given_array
	# 		sum_of_array_values += i
	# 	end
	# 	sum_of_array_values
	# end

# 3. total refactored solution

	def total(given_array)
		sum_of_array_values = 0
		given_array.each { |num|
			sum_of_array_values += num
		}
		sum_of_array_values
	end

# 4. sentence_maker pseudocode
	# Input: Array of strings
	# Output: A sentence combining all the strings
	# Steps to solve the problem.
		# 1. Set up initial sentence variable
		# 2. Use for loop to iterate through array until end of the array
		# 	3. Add each array index value (string) to the sentence
		# 	4. Add a space after each index value
		# 5. Add a period at the end, outside the for loop.
		# 6. Capitalize the first word in the sentence.
		# 7. Return sentence

# 5. sentence_maker initial solution

	# def sentence_maker(array_of_strings)
	# 	sentence = ""
	# 	for i in array_of_strings
	# 		sentence += i.to_s + " "
	# 	end
	# 	sentence = sentence.capitalize.chomp(' ') + "."
	# 	sentence
	# end

# 6. sentence_maker refactored solution

	def sentence_maker(array_of_strings)
		sentence = ""
		array_of_strings.each { |tiny_string|
			sentence += tiny_string.to_s + " "
		}
		sentence.capitalize.chomp(' ') + "."
	end


text:
blue='\e[1;38;5;27m'
red='\e[1;38;5;160m'
green='\e[1;38;5;46m'
NC='\e[0m'

clear;

if [[ $UID != 0 ]];
then
	echo -e "${red}Inicia el Script como root (sudo su) para que funcione correctamente${NC}";
	sleep 3s;
	clear;
	exit 1;
fi

echo -e "${blue}Vamos a comprobar si tienes conexion para poder instalar todos los modulos:${NC}";
sleep 5s;

if netcat -z google.com 80 &>/dev/null;
then
	echo -e "${green}Tienes conexión, iniciando la instalación...${NC}";
	sleep 3s;

        echo -e "${blue}Actualizando el sistema...${NC}";
        apt update
        apt upgrade -y

        echo -e "${blue}Instalando Ubuntu Cleaner en el sistema...${NC}";
	sleep 3s;
        cd /root
        mkdir ubugod
        cd ubugod
     add-apt-repository ppa:gerardpuig/ppa
     apt update && apt install ubuntu-cleaner
     apt install python-dbus

        echo -e "${blue}Instalando Iconos Papirus y Paper en el sistema...${NC}";
	sleep 3s;
            add-apt-repository ppa:papirus/papirus -y
            add-apt-repository ppa:snwh/pulp -y
            apt update
            apt install papirus-icon-theme paper-icon-theme paper-cursor-theme paper-gtk-theme -y

        echo -e "${blue}Actualizando el sistema...${NC}";
	sleep 3s;
            apt update
            apt upgrade -y

        echo -e "${blue}Instalando Chromium en el sistema...${NC}";
	sleep 3s;
            apt install chromium-browser -y

        echo -e "${blue}Instalando Vlc en el sistema...${NC}";
	sleep 3s;
            add-apt-repository ppa:videolan/master-daily -y
            apt update
            apt install vlc -y

        echo -e "${blue}Instalando Gimp en el sistema...${NC}";
	sleep 3s;
            apt install gimp -y

        echo -e "${blue}Instalando Brackets en el sistema...${NC}";
	sleep 3s;
            add-apt-repository ppa:webupd8team/brackets -y
            apt update
            apt install brackets -y

        echo -e "${blue}Instalando Sublime Text 3 en el sistema...${NC}";
	sleep 3s;
            apt install sublime-text-installer -y

	echo -e "${blue}Instalando Calibre eBook en el sistema...${NC}";
	sleep 3s;
	    sudo -v && wget -nv -O- https://download.calibre-ebook.com/linux-installer.py | sudo python -c "import sys; main=lambda:sys.stderr.write('Download failed\n'); exec(sys.stdin.read()); main()"

        echo -e "${blue}Instalando Steam en el sistema...${NC}";
	sleep 3s;
        cd /root/ubugod
            wget https://steamcdn-a.akamaihd.net/client/installer/steam.deb
            dpkg -i steam.deb -y
            apt install -f
            dpkg -i steam.deb -y

        echo -e "${blue}Instalando Playonlinux en el sistema...${NC}";
	sleep 3s;
            apt install playonlinux -y

        echo -e "${blue}Actualizando el sistema...${NC}";
	sleep 3s;
            apt update
            apt upgrade -y
            apt autoremove -y
            #cd /root
            #rm ubugod -R
else
        echo -e "${red}No tienes conexión para instalar correctamente los modulos${NC}";
	sleep 3s;

        echo -e "${blue}Cerrando Script automaticamante${NC}";
    sleep 3s;
clear;
fi


text:
package rand

import (
	"bufio"
	"crypto/rand"
	"io"

	"golang.org/x/sys/unix"
	"gvisor.dev/gvisor/pkg/sync"
)

// reader implements an io.Reader that returns pseudorandom bytes.
type reader struct {
	once         sync.Once
	useGetrandom bool
}

// Read implements io.Reader.Read.
func (r *reader) Read(p []byte) (int, error) {
	r.once.Do(func() {
		_, err := unix.Getrandom(p, 0)
		if err != unix.ENOSYS {
			r.useGetrandom = true
		}
	})

	if r.useGetrandom {
		return unix.Getrandom(p, 0)
	}
	return rand.Read(p)
}

// bufferedReader implements a threadsafe buffered io.Reader.
type bufferedReader struct {
	mu sync.Mutex
	r  *bufio.Reader
}

// Read implements io.Reader.Read.
func (b *bufferedReader) Read(p []byte) (int, error) {
	b.mu.Lock()
	n, err := b.r.Read(p)
	b.mu.Unlock()
	return n, err
}

// Reader is the default reader.
var Reader io.Reader = &bufferedReader{r: bufio.NewReader(&reader{})}

// Read reads from the default reader.
func Read(b []byte) (int, error) {
	return io.ReadFull(Reader, b)
}

// Init can be called to make sure /dev/urandom is pre-opened on kernels that
// do not support getrandom(2).
func Init() error {
	p := make([]byte, 1)
	_, err := Read(p)
	return err
}


text:
.tundra .dojoxGrid {
	position: relative;
	background-color: #e9e9e9;
	font-size: 0.85em; /* inherit font-family from dojo.css */
	-moz-outline-style: none;
	outline: none;
	overflow: hidden;
	height: 0;
}

.tundra .dojoxGrid table {
	padding: 0;
}

.tundra .dojoxGrid td {
	-moz-outline: none;
}

/* master header */

.tundra .dojoxGrid-master-header {
	position: relative;
}

/* master view */

.tundra .dojoxGrid-master-view  {
	position: relative;
}

/* views */

.tundra .dojoxGrid-view {
	position: absolute;
	overflow: hidden;
}

/* header */

.tundra .dojoxGrid-header {
	position: absolute;
	overflow: hidden;
}

.tundra .dojoxGrid-header {
	background-color:  #e9e9e9;
}

.tundra .dojoxGrid-header table {
	text-align: center;
}

.tundra .dojoxGrid-header .dojoxGrid-cell-content {
	text-align: center;
}

.tundra .dojoxGrid-header .dojoxGrid-cell {
	border: 1px solid transparent;
	/* border-color: #F6F4EB #ACA899 #ACA899 #F6F4EB; */
	border-color: white #ACA899 #919191 white;
	background: url(../../../dijit/themes/tundra/images/tabEnabled.png) #e9e9e9 repeat-x top;
	padding-bottom: 2px;
	color: #000 !important;
}

.tundra .dojoxGrid-header .dojoxGrid-cell-over {
	background: url(../../../dijit/themes/tundra/images/tabHover.png) #e9e9e9 repeat-x top;
	color: #000 !important;
}

.tundra .dojoxGrid-sort-down {
	background: url(../../../dijit/themes/tundra/images/arrowDown.png) right no-repeat;
	padding-left: 0px;
	margin-left: 0px;
}

.tundra .dojoxGrid-sort-up {
	background: url(../../../dijit/themes/tundra/images/arrowUp.png) right no-repeat;
	padding-left: 0px;
	margin-left: 0px;
}

.tundra .gridArrowButtonChar {
	display:none !important;
}
.dijit_a11y .gridArrowButtonChar {
	display:inline !important;
}

/* content */

.tundra .dojoxGrid-scrollbox {
	position: relative;
	overflow: scroll;
	background-color: #fefefe;
	width: 100%;
}

.tundra .dojoxGrid-content {
	position: relative;
	overflow: hidden;
	 -moz-outline-style: none;
	outline: none;
}

/* rowbar */

.tundra .dojoxGrid-rowbar {
	border: none;
	/*
	border-color: #F6F4EB #ACA899 #ACA899 #F6F4EB;
	*/
	background: url(images/tabEnabled_rotated.png) #e9e9e9 repeat-y right;
	border-right: 1px solid #cccccc;
	padding: 0px;
}

.tundra .dojoxGrid-rowbar-inner {
	border: none;
	border-bottom: 1px solid #cccccc;
}

.tundra .dojoxGrid-rowbar-over {
	background: url(images/tabHover_rotated.png) #e9e9e9 repeat-y right;
}

.tundra .dojoxGrid-rowbar-selected {
	background-color: #D9E8F9;
	background-image: none;
	background: url(../../../dijit/themes/tundra/images/tabDisabled.png) #dddddd repeat-x top;
	border-right: 1px solid #cccccc;
	background-position: center;
	background-repeat: no-repeat;
}

/* rows */

.tundra .dojoxGrid-row {
	position: relative;
	width: 9000em;
}

.tundra .dojoxGrid-row {
	border: none;
	border-left: none;
	border-right: none;
	background-color: white;
	border-top: none;
}

.tundra .dojoxGrid-row-over {
	border-top-color: #cccccc;
	border-bottom-color: #cccccc;
}

.tundra .dojoxGrid-row-over .dojoxGrid-cell {
	background-color: #60a1ea;
	color:#fff;
	/*background: url(../../../dijit/themes/tundra/images/tabEnabled.png) #e9e9e9 repeat-x top;*/
}

.tundra .dojoxGrid-row-odd {
	background-color: #f2f5f9;
	/*background-color: #F9F7E8;*/
}

.tundra .dojoxGrid-row-selected {
	background-color: #aec7e3;
	/*
	background: url(../../../dijit/themes/tundra/images/tabDisabled.png) #dddddd repeat-x top;
	*/
}

.tundra .dojoxGrid-row-table {
	table-layout: fixed;
	width: 0;
	border-collapse: collapse;
}

.tundra .dojoxGrid-invisible {
	visibility: hidden;
}

.tundra .Xdojo-ie .dojoxGrid-invisible {
	display: none;
}

.tundra .dojoxGrid-invisible td, .dojoxGrid-header .dojoxGrid-invisible td {
	border-top-width: 0;
	border-bottom-width: 0;
	padding-top: 0;
	padding-bottom: 0;
	height: 0;
	overflow: hidden;
}

/* cells */

.tundra .dojoxGrid-cell {
	border: 1px dotted #D5CDB5;
	padding: 3px 3px 3px 3px;
	text-align: left;
	overflow: hidden;
}

.dj_ie6 .tundra .dojoxGrid-cell {
	border: 1px solid white;
	border-right: 1px solid #D5CDB5;
}

.tundra .dojoxGrid-cell-focus {
	border: 1px dotted #a6a6a6;
}

.tundra .dojoxGrid-cell-over {
	border: 1px dotted #a6a6a6;
}

.tundra .dojoxGrid-cell-focus.dojoxGrid-cell-over {
	border: 1px dotted #595959;
}

.tundra .dojoxGrid-cell-clip {
	width: 100%;
	overflow: hidden;
	white-space:nowrap;
	text-overflow: ellipsis;
}

/* editing */

/* FIXME: these colors are off! */
.tundra .dojoxGrid-row-editing td {
	/* background-color: #F4FFF4; */
	background-color: #60a1ea;
	/* padding: 0px 3px 0px 3px; */
}

.tundra .dojoxGrid-row-inserting td {
	background-color: #F4FFF4;
}
.tundra .dojoxGrid-row-inflight td {
	background-color: #F2F7B7;
}
.tundra .dojoxGrid-row-error td {
	background-color: #F8B8B6;
}

.tundra .dojoxGrid-input,
.tundra .dojoxGrid-select,
.tundra .dojoxGrid-textarea {
	margin: 0;
	padding: 0px;
	border-style: none;
	width: 100%;
	font-size: 100%;
	font-family: inherit;
}

.dojoxGrid-hidden-focus {
	position: absolute;
	left: -1000px;
	top: -1000px;
	height: 0px, width: 0px;
}

.dijit_a11y .dojoxGrid-rowbar-selected {
	border-top: 1px solid white;
	border-bottom: 1px dashed black;
	border-top: 0;
	background: none;
}

.dijit_a11y .dojoxGrid-rowbar-selected .dojoxGrid-rowbar-inner {
	border: 0;
	border-top: 1px solid white;
}

.dijit_a11y .dojoxGrid-row-selected {
	border-bottom: 1px dashed black;
}


text:
layout: sidebar-right
title: "Undercover Princess by Connie Glynn"
date: 2018-03-20
author: amelie-magotte
category: young-adult
excerpt: 'Undercover Princess will appeal to anyone who loves drama, humour and wild characters doing wild things.'
featured-image: /images/featured/featured-undercover-princess.jpg
featured-alt: Undercover Princess
featured-link-text: "Read Amélie's review of Undercover Princess, by Connie Glynn."
breadcrumb: young-adult
genre: literary-fiction
genre-image: /images/featured/featured-undercover-princess-genre.jpg
genre-alt: "Undercover Princess"
---

![Undercover Princess](/images/featured/featured-undercover-princess.jpg)

**[See Undercover Princess in our catalogue](https://suffolk.spydus.co.uk/cgi-bin/spydus.exe/ENQ/OPAC/BIBENQ?BRN=2264677)**

> ""I know that you lied because..." she paused to move to her bed and started to rummage through her bag, violently chucking various objects and pieces of paper to the side. Lottie momentarily considered bolting for the door and running all the way back to Cornwall, but before she could finish that thought Ellie had located the item she was looking for and shoved the new-found object in Lottie's face. It was the diamond-shaped locket with the wolf crest expertly engraved on the surface. Ellie popped it open to reveal a small family photo: a king and a queen with a young girl at their side.

> "Lottie's face went deathly pale as she realized who the little girl in the photo was. Lottie turned her gaze back to Ellie, but she already knew how her sentence was going to end. "Because..." she repeated, "I'm the princess of Maradova."

Lottie Pumpkin has finally got a scholarship to the most prestigious school in the whole of the UK – so prestigious that the richest business owners' sons and daughters and even royalty go there! With such amazing company, beautiful views, and the best sort of education possible, what more could she ask for?

But when Lottie turns up, feeling genuinely squashed by the famous people surrounding her, a surprise comes her way. Her roommate is no other than the princess of Maradova.

What is even more of a shock is the fact that Lottie, who has never thought of anything better than being a princess, is despised by this royal annoyance by the name of Ellie Wolf (apparently) – just for liking princesses! A rebellious, wild, freedom-loving princess, Ellie cannot think what Lottie can love about the status that 'ruins her life'.

Eventually, after a lot of bickering, the two become surprisingly firm friends, and get up to all sorts of mischief. At the heart of this is that Ellie has 'given her role' of princess to Lottie. This means a lot more than just fancy dresses, as she is soon to find out!

This book is very well written, keeping you in suspense all the way through. By no means do you have to like princesses at all: it will definitely appeal to anyone who loves drama, humour and wild characters doing wild things.


text:
// <copyright file="UserQR.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2013 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>

using System;
using System.Linq;
using MathNet.Numerics.LinearAlgebra.Factorization;
using MathNet.Numerics.Threading;

namespace MathNet.Numerics.LinearAlgebra.Double.Factorization
{
    ///
    /// <para>A class which encapsulates the functionality of the QR decomposition.</para>
    /// <para>Any real square matrix A may be decomposed as A = QR where Q is an orthogonal matrix
    /// (its columns are orthogonal unit vectors meaning QTQ = I) and R is an upper triangular matrix
    /// (also called right triangular matrix).</para>
    ///
    /// <remarks>
    /// The computation of the QR decomposition is done at construction time by Householder transformation.
    /// </remarks>
    internal sealed class UserQR : QR
    {
        ///
        /// Initializes a new instance of the <see cref="UserQR"/> class. This object will compute the
        /// QR factorization when the constructor is called and cache it's factorization.
        ///
        /// <param name="matrix">The matrix to factor.</param>
        /// <param name="method">The QR factorization method to use.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="matrix"/> is <c>null</c>.</exception>
        public static UserQR Create(Matrix<double> matrix, QRMethod method = QRMethod.Full)
        {
            if (matrix.RowCount < matrix.ColumnCount)
            {
                throw Matrix.DimensionsDontMatch<ArgumentException>(matrix);
            }

            Matrix<double> q;
            Matrix<double> r;

            var minmn = Math.Min(matrix.RowCount, matrix.ColumnCount);
            var u = new double[minmn][];

            if (method == QRMethod.Full)
            {
                r = matrix.Clone();
                q = Matrix<double>.Build.SameAs(matrix, matrix.RowCount, matrix.RowCount, fullyMutable: true);

                for (var i = 0; i < matrix.RowCount; i++)
                {
                    q.At(i, i, 1.0);
                }

                for (var i = 0; i < minmn; i++)
                {
                    u[i] = GenerateColumn(r, i, i);
                    ComputeQR(u[i], r, i, matrix.RowCount, i + 1, matrix.ColumnCount, Control.MaxDegreeOfParallelism);
                }

                for (var i = minmn - 1; i >= 0; i--)
                {
                    ComputeQR(u[i], q, i, matrix.RowCount, i, matrix.RowCount, Control.MaxDegreeOfParallelism);
                }
            }
            else
            {
                q = matrix.Clone();

                for (var i = 0; i < minmn; i++)
                {
                    u[i] = GenerateColumn(q, i, i);
                    ComputeQR(u[i], q, i, matrix.RowCount, i + 1, matrix.ColumnCount, Control.MaxDegreeOfParallelism);
                }

                r = q.SubMatrix(0, matrix.ColumnCount, 0, matrix.ColumnCount);
                q.Clear();

                for (var i = 0; i < matrix.ColumnCount; i++)
                {
                    q.At(i, i, 1.0);
                }

                for (var i = minmn - 1; i >= 0; i--)
                {
                    ComputeQR(u[i], q, i, matrix.RowCount, i, matrix.ColumnCount, Control.MaxDegreeOfParallelism);
                }
            }

            return new UserQR(q, r, method);
        }

        UserQR(Matrix<double> q, Matrix<double> rFull, QRMethod method)
            : base(q, rFull, method)
        {
        }

        ///
        /// Generate column from initial matrix to work array
        ///
        /// <param name="a">Initial matrix</param>
        /// <param name="row">The first row</param>
        /// <param name="column">Column index</param>
        /// <returns>Generated vector</returns>
        static double[] GenerateColumn(Matrix<double> a, int row, int column)
        {
            var ru = a.RowCount - row;
            var u = new double[ru];

            for (var i = row; i  t*t);
            norm = Math.Sqrt(norm);

            if (row == a.RowCount - 1 || norm == 0)
            {
                a.At(row, column, -u[0]);
                u[0] = Constants.Sqrt2;
                return u;
            }

            var scale = 1.0/norm;
            if (u[0] < 0.0)
            {
                scale *= -1.0;
            }

            a.At(row, column, -1.0/scale);

            for (var i = 0; i < ru; i++)
            {
                u[i] *= scale;
            }

            u[0] += 1.0;
            var s = Math.Sqrt(1.0/u[0]);

            for (var i = 0; i < ru; i++)
            {
                u[i] *= s;
            }

            return u;
        }

        ///
        /// Perform calculation of Q or R
        ///
        /// <param name="u">Work array</param>
        /// <param name="a">Q or R matrices</param>
        /// <param name="rowStart">The first row</param>
        /// <param name="rowDim">The last row</param>
        /// <param name="columnStart">The first column</param>
        /// <param name="columnDim">The last column</param>
        /// <param name="availableCores">Number of available CPUs</param>
        static void ComputeQR(double[] u, Matrix<double> a, int rowStart, int rowDim, int columnStart, int columnDim, int availableCores)
        {
            if (rowDim < rowStart || columnDim < columnStart)
            {
                return;
            }

            var tmpColCount = columnDim - columnStart;

            if ((availableCores > 1) && (tmpColCount > 200))
            {
                var tmpSplit = columnStart + (tmpColCount/2);
                var tmpCores = availableCores/2;

                CommonParallel.Invoke(
                    () => ComputeQR(u, a, rowStart, rowDim, columnStart, tmpSplit, tmpCores),
                    () => ComputeQR(u, a, rowStart, rowDim, tmpSplit, columnDim, tmpCores));
            }
            else
            {
                for (var j = columnStart; j < columnDim; j++)
                {
                    var scale = 0.0;
                    for (var i = rowStart; i < rowDim; i++)
                    {
                        scale += u[i - rowStart]*a.At(i, j);
                    }

                    for (var i = rowStart; i < rowDim; i++)
                    {
                        a.At(i, j, a.At(i, j) - (u[i - rowStart]*scale));
                    }
                }
            }
        }

        ///
        /// Solves a system of linear equations, AX = B, with A QR factorized.
        ///
        /// <param name="input">The right hand side <see cref="Matrix{T}"/>, B.</param>
        /// <param name="result">The left hand side <see cref="Matrix{T}"/>, X.</param>
        public override void Solve(Matrix<double> input, Matrix<double> result)
        {
            // The solution X should have the same number of columns as B
            if (input.ColumnCount != result.ColumnCount)
            {
                throw new ArgumentException("Matrix column dimensions must agree.");
            }

            // The dimension compatibility conditions for X = A\B require the two matrices A and B to have the same number of rows
            if (FullR.RowCount != input.RowCount)
            {
                throw new ArgumentException("Matrix row dimensions must agree.");
            }

            // The solution X row dimension is equal to the column dimension of A
            if (FullR.ColumnCount != result.RowCount)
            {
                throw new ArgumentException("Matrix column dimensions must agree.");
            }

            var inputCopy = input.Clone();

            // Compute Y = transpose(Q)*B
            var column = new double[FullR.RowCount];
            for (var j = 0; j < input.ColumnCount; j++)
            {
                for (var k = 0; k < FullR.RowCount; k++)
                {
                    column[k] = inputCopy.At(k, j);
                }

                for (var i = 0; i < FullR.RowCount; i++)
                {
                    double s = 0;
                    for (var k = 0; k < FullR.RowCount; k++)
                    {
                        s += Q.At(k, i)*column[k];
                    }

                    inputCopy.At(i, j, s);
                }
            }

            // Solve R*X = Y;
            for (var k = FullR.ColumnCount - 1; k >= 0; k--)
            {
                for (var j = 0; j < input.ColumnCount; j++)
                {
                    inputCopy.At(k, j, inputCopy.At(k, j)/FullR.At(k, k));
                }

                for (var i = 0; i < k; i++)
                {
                    for (var j = 0; j < input.ColumnCount; j++)
                    {
                        inputCopy.At(i, j, inputCopy.At(i, j) - (inputCopy.At(k, j)*FullR.At(i, k)));
                    }
                }
            }

            for (var i = 0; i < FullR.ColumnCount; i++)
            {
                for (var j = 0; j < inputCopy.ColumnCount; j++)
                {
                    result.At(i, j, inputCopy.At(i, j));
                }
            }
        }

        ///
        /// Solves a system of linear equations, Ax = b, with A QR factorized.
        ///
        /// <param name="input">The right hand side vector, b.</param>
        /// <param name="result">The left hand side <see cref="Matrix{T}"/>, x.</param>
        public override void Solve(Vector<double> input, Vector<double> result)
        {
            // Ax=b where A is an m x n matrix
            // Check that b is a column vector with m entries
            if (FullR.RowCount != input.Count)
            {
                throw new ArgumentException("All vectors must have the same dimensionality.");
            }

            // Check that x is a column vector with n entries
            if (FullR.ColumnCount != result.Count)
            {
                throw Matrix.DimensionsDontMatch<ArgumentException>(FullR, result);
            }

            var inputCopy = input.Clone();

            // Compute Y = transpose(Q)*B
            var column = new double[FullR.RowCount];
            for (var k = 0; k < FullR.RowCount; k++)
            {
                column[k] = inputCopy[k];
            }

            for (var i = 0; i < FullR.RowCount; i++)
            {
                double s = 0;
                for (var k = 0; k < FullR.RowCount; k++)
                {
                    s += Q.At(k, i)*column[k];
                }

                inputCopy[i] = s;
            }

            // Solve R*X = Y;
            for (var k = FullR.ColumnCount - 1; k >= 0; k--)
            {
                inputCopy[k] /= FullR.At(k, k);
                for (var i = 0; i < k; i++)
                {
                    inputCopy[i] -= inputCopy[k]*FullR.At(i, k);
                }
            }

            for (var i = 0; i < FullR.ColumnCount; i++)
            {
                result[i] = inputCopy[i];
            }
        }
    }
}


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

<title>All Classes</title>
<meta name="date" content="2015-04-28">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

BuildConfig

CanvasElement

DuktapeWrapper

MainActivity

R

R.attr

R.color

R.dimen

R.drawable

R.id

R.integer

R.layout

R.mipmap

R.raw

R.string

R.style

R.styleable

XMLHTTPRequest