text:
define(
({
	"clearFilterDialogTitle": "Vymazat filtr",
	"filterDefDialogTitle": "Filtr",
	"ruleTitleTemplate": "Pravidlo ${0}",
	"conditionEqual": "rovná se",
	"conditionNotEqual": "nerovná se",
	"conditionLess": "je menší než",
	"conditionLessEqual": "menší nebo rovno",
	"conditionLarger": "je větší než",
	"conditionLargerEqual": "větší nebo rovno",
	"conditionContains": "obsahuje",
	"conditionIs": "je",
	"conditionStartsWith": "začíná na",
	"conditionEndWith": "končí na",
	"conditionNotContain": "neobsahuje",
	"conditionIsNot": "není",
	"conditionNotStartWith": "nezačíná na",
	"conditionNotEndWith": "nekončí na",
	"conditionBefore": "před",
	"conditionAfter": "po",
	"conditionRange": "rozsah",
	"conditionIsEmpty": "je prázdné",
	"all": "vše",
	"any": "libovolné",
	"relationAll": "všechna pravidla",
	"waiRelAll": "Vyhovovat všem následujícím pravidlům:",
	"relationAny": "libovolné pravidlo",
	"waiRelAny": "Vyhovovat libovolnému z následujících pravidel:",
	"relationMsgFront": "Vyhovovat:",
	"relationMsgTail": "",
	"and": "a",
	"or": "nebo",
	"addRuleButton": "Přidat pravidlo",
	"waiAddRuleButton": "Přidat nové pravidlo",
	"removeRuleButton": "Odebrat pravidlo",
	"waiRemoveRuleButtonTemplate": "Odebrat pravidlo ${0}",
	"cancelButton": "Storno",
	"waiCancelButton": "Zrušit toto dialogové okno",
	"clearButton": "Vymazat",
	"waiClearButton": "Vymazat tento filtr",
	"filterButton": "Filtrovat",
	"waiFilterButton": "Odeslat tento filtr",
	"columnSelectLabel": "Sloupec",
	"waiColumnSelectTemplate": "Sloupec pravidla ${0}",
	"conditionSelectLabel": "Podmínka",
	"waiConditionSelectTemplate": "Podmínka pravidla ${0}",
	"valueBoxLabel": "Hodnota",
	"waiValueBoxTemplate": "Zadat hodnotu filtru pro pravidlo ${0}",
	"rangeTo": "do",
	"rangeTemplate": "od ${0} do ${1}",
	"statusTipHeaderColumn": "Sloupec",
	"statusTipHeaderCondition": "Pravidla",
	"statusTipTitle": "Panel filtru",
	"statusTipMsg": "Klepnutím sem na panel filtru provedete filtrování podle hodnoty pro ${0}.",
	"anycolumn": "libovolný sloupec",
	"statusTipTitleNoFilter": "Panel filtru",
	"statusTipTitleHasFilter": "Filtr",
	"statusTipRelAny": "Vyhovovat libovolnému pravidlu",
	"statusTipRelAll": "Vyhovovat všem pravidlům",
	"defaultItemsName": "položek",
	"filterBarMsgHasFilterTemplate": "Zobrazeno ${0} z ${1} ${2}.",
	"filterBarMsgNoFilterTemplate": "Není použit žádný filtr",
	"filterBarDefButton": "Definovat filtr",
	"waiFilterBarDefButton": "Filtrovat tabulku",
	"a11yFilterBarDefButton": "Filtrovat...",
	"filterBarClearButton": "Vymazat filtr",
	"waiFilterBarClearButton": "Vymazat tento filtr",
	"closeFilterBarBtn": "Zavřít panel filtru",
	"clearFilterMsg": "Tato akce odebere filtr a zobrazí se všechny dostupné záznamy.",
	"anyColumnOption": "Libovolné sloupec",
	"trueLabel": "Pravda",
	"falseLabel": "Nepravda"
})
);


text:
package org.apache.ignite.internal;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.compute.ComputeJob;
import org.apache.ignite.compute.ComputeJobAdapter;
import org.apache.ignite.compute.ComputeJobContext;
import org.apache.ignite.compute.ComputeJobResult;
import org.apache.ignite.compute.ComputeTaskFuture;
import org.apache.ignite.compute.ComputeTaskSplitAdapter;
import org.apache.ignite.compute.ComputeTaskTimeoutException;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.util.typedef.G;
import org.apache.ignite.resources.JobContextResource;
import org.apache.ignite.resources.LoggerResource;
import org.apache.ignite.spi.IgniteSpiAdapter;
import org.apache.ignite.spi.IgniteSpiException;
import org.apache.ignite.spi.IgniteSpiMultipleInstancesSupport;
import org.apache.ignite.spi.collision.CollisionContext;
import org.apache.ignite.spi.collision.CollisionExternalListener;
import org.apache.ignite.spi.collision.CollisionJobContext;
import org.apache.ignite.spi.collision.CollisionSpi;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.apache.ignite.testframework.junits.common.GridCommonTest;
import org.junit.Test;

/**
 * Job collision cancel test.
 */
@SuppressWarnings( {"PublicInnerClass"})
@GridCommonTest(group = "Kernal Self")
public class GridJobCollisionCancelSelfTest extends GridCommonAbstractTest {
    /** */
    private static final Object mux = new Object();

    /** */
    private static final int SPLIT_COUNT = 2;

    /** */
    private static final long maxJobExecTime = 10000;

    /** */
    private static int cancelCnt;

    /** */
    private static int execCnt;

    /** */
    private static int colResolutionCnt;

    /** */
    public GridJobCollisionCancelSelfTest() {
        super(true);
    }

    /**
     * @throws Exception If failed.
     */
    @SuppressWarnings( {"AssignmentToCatchBlockParameter"})
    @Test
    public void testCancel() throws Exception {
        Ignite ignite = G.ignite(getTestIgniteInstanceName());

        ignite.compute().localDeployTask(GridCancelTestTask.class, GridCancelTestTask.class.getClassLoader());

        ComputeTaskFuture<?> res0 =
            executeAsync(ignite.compute().withTimeout(maxJobExecTime * 2), GridCancelTestTask.class.getName(), null);

        try {
            Object res = res0.get();

            info("Cancel test result: " + res);

            synchronized (mux) {
                // Every execute must be called.
                assert execCnt <= SPLIT_COUNT : "Invalid execute count: " + execCnt;

                // Job returns 1 if was cancelled.
                assert (Integer)res <= SPLIT_COUNT  : "Invalid task result: " + res;

                // Should be exactly the same as Jobs number.
                assert cancelCnt <= SPLIT_COUNT : "Invalid cancel count: " + cancelCnt;

                // One per start and one per stop and some that come with metrics update.
                assert colResolutionCnt > SPLIT_COUNT + 1:
                    "Invalid collision resolution count: " + colResolutionCnt;
            }
        }
        catch (ComputeTaskTimeoutException e) {
            error("Task execution got timed out.", e);
        }
        catch (Exception e) {
            assert e.getCause() != null;

            if (e.getCause() instanceof IgniteCheckedException)
                e = (Exception)e.getCause();

            if (e.getCause() instanceof IOException)
                e = (Exception)e.getCause();

            assert e.getCause() instanceof InterruptedException : "Invalid exception cause: " + e.getCause();
        }
    }

    /**
     * @return Configuration.
     * @throws Exception If failed.
     */
    @Override protected IgniteConfiguration getConfiguration() throws Exception {
        IgniteConfiguration cfg = super.getConfiguration();

        cfg.setCollisionSpi(new GridTestCollision());

        return cfg;
    }

    /**
     *
     */
    public static class GridCancelTestTask extends ComputeTaskSplitAdapter<Serializable, Object> {
        /** */
        @LoggerResource
        private IgniteLogger log;

        /** {@inheritDoc} */
        @Override public Collection<? extends ComputeJob> split(int gridSize, Serializable arg) {
            if (log.isInfoEnabled())
                log.info("Splitting task [task=" + this + ", gridSize=" + gridSize + ", arg=" + arg + ']');

            Collection<GridCancelTestJob> jobs = new ArrayList<>(SPLIT_COUNT);

            for (int i = 0; i < SPLIT_COUNT; i++)
                jobs.add(new GridCancelTestJob());

            return jobs;
        }

        /** {@inheritDoc} */
        @Override public Object reduce(List<ComputeJobResult> results) {
            if (log.isInfoEnabled())
                log.info("Aggregating job [job=" + this + ", results=" + results + ']');

            int res = 0;

            for (ComputeJobResult result : results) {
                assert result != null;

                if (result.getData() != null)
                    res += (Integer)result.getData();
            }

            return res;
        }
    }

    /**
     * Test job.
     */
    public static class GridCancelTestJob extends ComputeJobAdapter {
        /** */
        @LoggerResource
        private IgniteLogger log;

        /** */
        @JobContextResource
        private ComputeJobContext jobCtx;

        /** */
        @SuppressWarnings( {"FieldAccessedSynchronizedAndUnsynchronized"})
        private boolean isCancelled;

        /** */
        private final long thresholdTime;

        /** */
        public GridCancelTestJob() {
            thresholdTime = System.currentTimeMillis() + maxJobExecTime;
        }

        /** {@inheritDoc} */
        @Override public Serializable execute() {
            synchronized (mux) {
                execCnt++;
            }

            if (log.isInfoEnabled())
                log.info("Executing job: " + jobCtx.getJobId());

            long now = System.currentTimeMillis();

            while (!isCancelled && now < thresholdTime) {
                synchronized (mux) {
                    try {
                        mux.wait(thresholdTime - now);
                    }
                    catch (InterruptedException ignored) {
                        // No-op.
                    }
                }

                now = System.currentTimeMillis();
            }

            synchronized (mux) {
                return isCancelled ? 1 : 0;
            }
        }

        /** {@inheritDoc} */
        @Override public void cancel() {
            synchronized (mux) {
                isCancelled = true;

                cancelCnt++;

                mux.notifyAll();
            }

            log.warning("Job cancelled: " + jobCtx.getJobId());
        }
    }

    /**
     * Test collision SPI.
     */
    @IgniteSpiMultipleInstancesSupport(true)
    public static class GridTestCollision extends IgniteSpiAdapter implements CollisionSpi {
        /** */
        @LoggerResource
        private IgniteLogger log;

        /** {@inheritDoc} */
        @Override public void onCollision(CollisionContext ctx) {
            Collection<CollisionJobContext> activeJobs = ctx.activeJobs();
            Collection<CollisionJobContext> waitJobs = ctx.waitingJobs();

            synchronized (mux) {
                colResolutionCnt++;
            }

            for (CollisionJobContext job : waitJobs)
                job.activate();

            for (CollisionJobContext job : activeJobs)
                job.cancel();
        }

        /** {@inheritDoc} */
        @Override public void spiStart(String igniteInstanceName) throws IgniteSpiException {
            // Start SPI start stopwatch.
            startStopwatch();

            // Ack start.
            if (log.isInfoEnabled())
                log.info(startInfo());
        }

        /** {@inheritDoc} */
        @Override public void spiStop() throws IgniteSpiException {
            // Ack stop.
            if (log.isInfoEnabled())
                log.info(stopInfo());
        }

        /** {@inheritDoc} */
        @Override public void setExternalCollisionListener(CollisionExternalListener lsnr) {
            // No-op.
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring
{
    using Models;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// Extension methods for Train.
    /// </summary>
    public static partial class TrainExtensions
    {
            /// <summary>
            /// Sends a training request for a version of a specified LUIS app. This POST
            /// request initiates a request asynchronously. To determine whether the
            /// training request is successful, submit a GET request to get training
            /// status. Note: The application version is not fully trained unless all the
            /// models (intents and entities) are trained successfully or are up to date.
            /// To verify training success, get the training status at least once after
            /// training is complete.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='appId'>
            /// The application ID.
            /// </param>
            /// <param name='versionId'>
            /// The version ID.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<EnqueueTrainingResponse> TrainVersionAsync(this ITrain operations, System.Guid appId, string versionId, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.TrainVersionWithHttpMessagesAsync(appId, versionId, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Gets the training status of all models (intents and entities) for the
            /// specified LUIS app. You must call the train API to train the LUIS app
            /// before you call this API to get training status. "appID" specifies the LUIS
            /// app ID. "versionId" specifies the version number of the LUIS app. For
            /// example, "0.1".
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='appId'>
            /// The application ID.
            /// </param>
            /// <param name='versionId'>
            /// The version ID.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<IList<ModelTrainingInfo>> GetStatusAsync(this ITrain operations, System.Guid appId, string versionId, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.GetStatusWithHttpMessagesAsync(appId, versionId, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

    }
}


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Speedup = mongoose.model('Speedup'),
	Context = mongoose.model('Context'),
	lodash = require('lodash');

// create
exports.create = function(req,res) {
	console.log('hi');
	console.log(req.body.type);

	// var data = req.body;
	// var context = new Context(data.context);

	// context.save(function(err, savedData) {
	// 	if (err) {
	// 		return res.status(500).json({ error: 'Cannot save metric speedup context' });
	// 	}
	// 	//console.log(savedData);
	// 	data.context = savedData._id;
	// 	//console.log(data);

	// 	var speedup = new Speedup(data);

	// 	speedup.save(function(err) {
	// 		if (err) {
	// 			console.log(err);
	// 			return res.status(500).json({ error: 'Cannot save metric speedup'});
	// 		}
	// 		return res.json(speedup);
	// 	});

	// });

	exports.createOne(req.body, function(result) {
		if (!result) {
			return res.status(500).json({ error: 'Cannot save metric speedup'});
		} else {
			console.log(result);
			return res.json(result);
		}
	});

};

exports.createOne = function(data, callBack) {
	var context = new Context(data.context);

	context.save(function(err, savedData) {
		if (err != null) {
			callBack(false);
			return false;
		}

		data.context = savedData._id;
		var speedup = new Speedup(data);

		speedup.save(function(err, savedData2) {
			if (err != null) {
				callBack(false);
				return false;
			}
			callBack(savedData2);
		});

	});
}

// get all
exports.all = function(req,res) {
	console.log('all called');

	Speedup.find().sort('timeStamp').populate('context').exec(function(err, speedups){
		if (err) {
			return res.status(500).json({ error: 'Cannot get all metric speedup'});
		}
		return res.json(speedups);
	});
};

// destroy !deprecated
exports.destroy = function(req,res) {
	var speedup = req.speedup;

	speedup.remove(function(err) {
		if (err) {
			console.log(err);
			return res.status(500).json({ error: 'Cannot delete metric speedup'});
		}
		return res.json(speedup);
	});
};

// empty aka. destroy all, !deprecated
exports.empty = function(req,res) {
	Speedup.remove({}, function(err, speedup) {
		if (err) {
			return res.json(err);
		}

		return res.json('emptied');
	});
};

// update: !deprecated
exports.update = function(req,res) {
	var speedup = req.speedup;
	speedup = lodash.extend(speedup, req.body);

	speedup.save(function(err) {
		if (err) {
			console.log(err);
			return res.status(500).json({ error: 'Cannot save metric speedup'});
		}
		return res.json(speedup);
	});
};

// show one
exports.show = function(req,res) {
	return res.json(req.speedup);
};

// get one by id
exports.get = function(req,res,next,id) {
	Speedup.findById(id).populate('context').exec(function(err, speedup) {
		console.log(id);
		console.log(speedup);

		if (err) {
			return next(err);
		}

		if (!speedup) {
			return next(new Error('Failed to load Speedup ' + id));
		}

		req.speedup = speedup;
		next();
	});
};


text:
        <title>Kairos</title>
        <?php
          include "../include/include_css.php";
          include "../header/header.php";
          include "../../classes/model/validaOperario.php";
        ?>

        <meta charset="UTF-8">

                <form method="post" action="novaAmostraClasse.php">

                            Registro de Amostra

 <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button> Ajuda:
                            Para cadastrar amostra o usuário deve escolher o departamento, selecionar a atividade e clicar no botão cadastrar dados.

                            Obs: A pagina será redirecionada para que o usuário coloque as informações adicionais.

                                CNPJ
                                <select  class="form-control" name="cnpj" id="cnpj" required>
                                    <option value="">Selecione o CNPJ</option>
                                </select>

                                Departamento
                                <select  class="form-control" name="departamento" id="cmbDepartamento" required>
                                    <option value="">Selecione o Departamento</option>
                                </select>

                                Atividade
                                <select  class="form-control" name="atividade" id="cmbAtividade" required>
                                    <option value="">Selecione o Atividade</option>
                                </select>

                                <input id="btnCadastrar" type="submit" name="cadastrar" class="btn btn-success" value="Cadastrar Dados">

                </form>

    <?php include_once '../include/include_js.php'; ?>


text:
module ControllerScaffoldingHelper

	def render_for_controller(partial, local_vars)
    render(:partial => partial, :locals => local_vars).html_safe
  end

end


text:
require 'bundler/setup'
require 'cached_at'
require 'minitest/autorun'
require 'active_record'

class Minitest::Spec
  class << self
    alias :context :describe
  end
end

ActiveRecord::Base::establish_connection(adapter: 'sqlite3', database: ':memory:')

ActiveRecord::Base.connection.execute(%{CREATE TABLE users  (id INTEGER PRIMARY KEY, name VARCHAR, updated_at DATETIME, cached_at DATETIME);})
ActiveRecord::Base.connection.execute(%{CREATE TABLE posts  (id INTEGER PRIMARY KEY, title STRING, user_id INTEGER, updated_at DATETIME);})

class User < ActiveRecord::Base
  include CachedAt
end

class Post < ActiveRecord::Base
  belongs_to :user, touch: true
end


text:
.teacher_dashboard_today_schedule_container{
    /*overflow-x: scroll;*/
    border: 2px solid #e0e0e0;
}

.teacher_dashboard_today_schedule_table{
    table-layout: fixed;
    border: 2px solid #e0e0e0;
    min-height: 150px;
    width: 100%;
}

.teacher_dashboard_today_schedule_table th{
    /*min-width: 250px;*/
    text-align: center;
    border: 2px solid #e0e0e0;
}

.teacher_dashboard_today_schedule_period{
    background-color: #ffa63a;
    color: white;
}

.teacher_dashboard_today_schedule_break{
    background-color: #fe4972;
    color: white;
}

.teacher_dashboard_today_schedule_table td{
    padding: 1vw;
    border: 2px solid #e0e0e0;
    text-align: center;
}

.teacher_dashboard_deadline{
    color: #fe4972;
}

.teacher_dashboard_upcoming_type{
    float: right;
    background: #fe4972;
    color: white;
    padding: 0.3vw;
    font-weight: bold;
    border-radius: 5px;
}

.teacher_attendance_radio input[type="radio"] {
    display:none;
}

.teacher_attendance_radio label {
    display:inline-block;
    background-color:#ddd;
    padding:4px 11px;
    font-family:Arial;
    font-size:16px;
    color: white;
}

.present:checked + label {
    background-color:#48b51b;
}

.absent:checked + label {
    background-color:#e61515;
}

.late:checked + label {
    background-color:#f9c91c;
}

.teacher_profile_crop{
    position: relative;
    width: 220px;
    height: 220px;
    overflow: hidden;
}

.teacher_profile_img{
    width: 220px;
    height: auto;
}

.teacher_profile_group{
    padding: 15px;
}

.teacher_profile_label{
    color: #919191;
    line-height: 30px;
}

.teacher_profile_value{
    color: black;
    font-size: 11pt;
}

.teacher_course_evaluation{
    width: 70%;
}

.teacher_course_evaluation th{
    padding: 10px;
    background-color: gainsboro;
}

.teacher_course_evaluation td{
    padding: 5px 10px 5px 10px;
    /*border-bottom: solid 1px gainsboro;*/
}

.teacher_course_implementation{
    width: 100%;
}

.teacher_course_implementation th{
    padding: 10px;
    background-color: gainsboro;
}

.teacher_course_implementation td{
    padding: 10px;
    /*border-bottom: solid 1px gainsboro;*/
}

.set-align-right{
    text-align: right;
}

.set-right{
    float: right;
}

.set-margin-left{
    margin-left: 15px;
}

.set-margin-right{
    margin-right: 15px;
}

.set-margin-top{
    margin-top: 10px;
}

.set-margin-top2{
    margin-top: 100px;
}

.set-margin-bottom{
    margin-bottom: 10px;
}

.set-center{
    text-align: center;
}

.btn-danger{
    background-color: #fe4972;
    color: white;
}

.btn-yellow{
    background-color: #ffa63a;
    color: white;
}

.btn-yellow:hover{
    background-color: #f38e14;
    color: white;
}

.teacher_photo_crop{
    position: relative;
    width: 100px;
    height: 100px;
    overflow: hidden;
}

.teacher_photo_img{
    width: 100px;
    height: auto;
}

.teacher_course_student_mid{
    width: 100%;
    margin-top: 30px;
    margin-bottom: 30px;
}

.teacher_course_student_mid td{
    padding: 10px;
}

.teacher_course_student_mid_td{
    font-weight: bold;
    background-color: gainsboro;
    /*border: 1px solid white !important*/
}

.teacher_course_student_mid td input[type="radio"] {
    display:none;
}

.teacher_course_student_mid td label {
    background-color: #fff;
    border: 1px solid gainsboro;
    width: 15px;
    height: 15px;
}

.teacher_course_student_mid td input[type="radio"]:checked + label {
    background: url("../img/teacher/checkmark.png");
}

.option_tick{
    background: url("../img/teacher/checkmark.png");
    width: 15px;
    height: 15px;
    display: inline-block
}

textarea{
    resize: vertical;
}

@media print {
    .teacher_course_implementation th {
        background-color: gainsboro !important;
        -webkit-print-color-adjust: exact;
    }

    .option_tick{
        background: url("../img/teacher/checkmark.png") !important;
    }

    .teacher_course_student_mid .x_panel .col-md-12  {
        width: 100% !important;
    }

    .teacher_course_student_mid_td {
        background-color: gainsboro !important;
        width: 10% !important;
    }

    .print-size-td{
        width: 100% !important;
    }

    .print-size30{
        width: 30% !important;
    }

    .set-border-top{
        border-top: 1px solid black !important;
    }
}

.print-padding{
    padding: 10px 20px 0;
}

.date {
    background: #2c9609 !important;
    border-radius: 0 !important;
    padding: 6px !important;
}

.day{
    color: black !important;
    background: white;
    margin: 0px -4px -4px -4px !important;
}

.quizandassignment{
    background: #fe4972 !important;
}

.title_center{
    text-align: center;
}

.report-title{
    font-weight: bold;
    color: black;
    font-size: x-large;
}

.print-title{
    width: 100%;
    padding: 10px 0;
}

.set-bold{
    font-weight: bold;
}

.no-border{
    border-bottom: none !important;
    padding: 1px 30px 6px !important;
}

.font-h2{
    font-size: 18px;
}

.report2-title{
    font-weight: bold;
    color: black;
    font-size: xx-large;
}

.comment-table{
    width: 100%;
}

.comment-table textarea{
    border-color: black;
}

.print-name{
    font-size: large;
}

.set-border-top{
    border-top: 1px solid black;
}

input[type=checkbox] {
    display:none;
}

input[type=checkbox] + label, .worknotavailable
{
    background: red;
    height: 20px;
    width: 20px;
    display:inline-block;
    padding: 0 0 0 0px;
}
input[type=checkbox]:checked + label, .workavailable
{
    background: green;
    height: 20px;
    width: 20px;
    display:inline-block;
    padding: 0 0 0 0px;
}

.teacher_sidebar_crop{
    position: relative;
    width: 57px;
    height: 57px;
    overflow: hidden;
    margin-top: 20px;
    margin-left: 15%;
    border-radius: 50%;
}

.teacher_sidebar_photo{
    width: 57px;
    height: auto;
    background: #fff;
    z-index: 1000;
    position: inherit;
    border: 1px solid rgba(52,73,94,0.44);
}

.x_content p img{
    width: 100%;
    height: 100%;
}

.conflict1{
    background-color: red !important;
}

.conflict2{
    background-color: orange !important;
}

.conflict3{
    background-color: darkgray !important;
}

.not-conflicted{
    background-color: green;
}

.dragging{
    background-color: blue;
    padding: 10px;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView android:id="@+android:id/title"
		  xmlns:android="http://schemas.android.com/apk/res/android"
		  android:layout_width="match_parent"
		  android:layout_height="wrap_content"
		  android:paddingBottom="@dimen/list_item_padding"
		  android:paddingEnd="@dimen/list_item_padding"
		  android:paddingLeft="@dimen/list_item_padding"
		  android:paddingRight="@dimen/list_item_padding"
		  android:paddingStart="@dimen/list_item_padding"
		  android:paddingTop="@dimen/list_item_padding"
		  android:textAppearance="@style/TextAppearance.AppCompat.Body2"
		  android:textColor="@color/accent"/>


text:
<?php

try {
    directory_mirror($uploadedImages, FCPATH . 'images/');
} catch (Throwable $e) {
    echo 'Failed to export uploads!';
}


text:
#if !defined CUBIC_UTILITIES_H
#define CUBIC_UTILITIES_H

#include "DataTypes.h"
#include "SkTDArray.h"

double calcPrecision(const Cubic& cubic);
#ifdef SK_DEBUG
double calcPrecision(const Cubic& cubic, double t, double scale);
#endif
void chop_at(const Cubic& src, CubicPair& dst, double t);
bool clockwise(const Cubic& c);
double cube_root(double x);
int cubic_to_quadratics(const Cubic& cubic, double precision,
        SkTDArray<Quadratic>& quadratics);
void cubic_to_quadratics(const Cubic& cubic, double precision, SkTDArray<double>& ts);
void coefficients(const double* cubic, double& A, double& B, double& C, double& D);
bool controls_contained_by_ends(const Cubic& c);
int cubicRootsValidT(double A, double B, double C, double D, double t[3]);
int cubicRootsReal(double A, double B, double C, double D, double s[3]);
void demote_cubic_to_quad(const Cubic& cubic, Quadratic& quad);
double dx_at_t(const Cubic& , double t);
double dy_at_t(const Cubic& , double t);
//void dxdy_at_t(const Cubic& , double t, _Point& y);
_Vector dxdy_at_t(const Cubic& cubic, double t);
bool ends_are_extrema_in_x_or_y(const Cubic& );
int find_cubic_inflections(const Cubic& src, double tValues[]);
int find_cubic_max_curvature(const Cubic& src, double tValues[]);
bool monotonic_in_y(const Cubic& c);
bool rotate(const Cubic& cubic, int zero, int index, Cubic& rotPath);
bool serpentine(const Cubic& c);
void sub_divide(const Cubic& src, double t1, double t2, Cubic& dst);
void sub_divide(const Cubic& , const _Point& a, const _Point& d, double t1, double t2, _Point [2]);
_Point top(const Cubic& , double startT, double endT);
void xy_at_t(const Cubic& , double t, double& x, double& y);
_Point xy_at_t(const Cubic& , double t);

extern const int gPrecisionUnit;

#endif


text:
package org.elasticsearch.action.admin.indices.create;

import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.SortedSetSelector;
import org.apache.lucene.search.SortedSetSortField;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.Version;
import org.elasticsearch.action.admin.cluster.state.ClusterStateRequest;
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
import org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse;
import org.elasticsearch.action.admin.indices.shrink.ResizeType;
import org.elasticsearch.action.admin.indices.stats.CommonStats;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse;
import org.elasticsearch.action.admin.indices.stats.ShardStats;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.Murmur3HashFunction;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.allocation.decider.EnableAllocationDecider;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.engine.SegmentsStats;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.index.seqno.SeqNoStats;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.InternalSettingsPlugin;
import org.elasticsearch.test.VersionUtils;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.IntFunction;
import java.util.stream.IntStream;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.index.query.QueryBuilders.nestedQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;

public class SplitIndexIT extends ESIntegTestCase {

    @Override
    protected Collection<Class<? extends Plugin>> nodePlugins() {
        return Arrays.asList(InternalSettingsPlugin.class);
    }

    public void testCreateSplitIndexToN() throws IOException {
        int[][] possibleShardSplits = new int[][] {{2,4,8}, {3, 6, 12}, {1, 2, 4}};
        int[] shardSplits = randomFrom(possibleShardSplits);
        assertEquals(shardSplits[0], (shardSplits[0] * shardSplits[1]) / shardSplits[1]);
        assertEquals(shardSplits[1], (shardSplits[1] * shardSplits[2]) / shardSplits[2]);
        internalCluster().ensureAtLeastNumDataNodes(2);
        final boolean useRouting =  randomBoolean();
        final boolean useNested = randomBoolean();
        final boolean useMixedRouting = useRouting ? randomBoolean() : false;
        CreateIndexRequestBuilder createInitialIndex = prepareCreate("source");
        final int routingShards = shardSplits[2] * randomIntBetween(1, 10);
        Settings.Builder settings = Settings.builder().put(indexSettings())
            .put("number_of_shards", shardSplits[0])
            .put("index.number_of_routing_shards", routingShards);
        if (useRouting && useMixedRouting == false && randomBoolean()) {
            settings.put("index.routing_partition_size", randomIntBetween(1, routingShards - 1));
            if (useNested) {
                createInitialIndex.addMapping("t1", "_routing", "required=true", "nested1", "type=nested");
            } else {
                createInitialIndex.addMapping("t1", "_routing", "required=true");
            }
        } else if (useNested) {
            createInitialIndex.addMapping("t1", "nested1", "type=nested");
        }
        logger.info("use routing {} use mixed routing {} use nested {}", useRouting, useMixedRouting, useNested);
        createInitialIndex.setSettings(settings).get();

        int numDocs = randomIntBetween(10, 50);
        String[] routingValue = new String[numDocs];

        BiFunction<String, Integer, IndexRequestBuilder> indexFunc = (index, id) -> {
            try {
                return client().prepareIndex(index, "t1", Integer.toString(id))
                    .setSource(jsonBuilder().startObject()
                        .field("foo", "bar")
                        .field("i", id)
                        .startArray("nested1")
                        .startObject()
                        .field("n_field1", "n_value1_1")
                        .field("n_field2", "n_value2_1")
                        .endObject()
                        .startObject()
                        .field("n_field1", "n_value1_2")
                        .field("n_field2", "n_value2_2")
                        .endObject()
                        .endArray()
                        .endObject());
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        };
        for (int i = 0; i < numDocs; i++) {
            IndexRequestBuilder builder = indexFunc.apply("source", i);
            if (useRouting) {
                String routing = randomRealisticUnicodeOfCodepointLengthBetween(1, 10);
                if (useMixedRouting && randomBoolean()) {
                    routingValue[i] = null;
                } else {
                    routingValue[i] = routing;
                }
                builder.setRouting(routingValue[i]);
            }
            builder.get();
        }

        if (randomBoolean()) {
            for (int i = 0; i < numDocs; i++) { // let's introduce some updates / deletes on the index
                if (randomBoolean()) {
                    IndexRequestBuilder builder = indexFunc.apply("source", i);
                    if (useRouting) {
                        builder.setRouting(routingValue[i]);
                    }
                    builder.get();
                }
            }
        }

        ImmutableOpenMap<String, DiscoveryNode> dataNodes = client().admin().cluster().prepareState().get().getState().nodes()
            .getDataNodes();
        assertTrue("at least 2 nodes but was: " + dataNodes.size(), dataNodes.size() >= 2);
        ensureYellow();
        client().admin().indices().prepareUpdateSettings("source")
            .setSettings(Settings.builder()
                .put("index.blocks.write", true)).get();
        ensureGreen();
        assertAcked(client().admin().indices().prepareResizeIndex("source", "first_split")
            .setResizeType(ResizeType.SPLIT)
            .setSettings(Settings.builder()
                .put("index.number_of_replicas", 0)
                .put("index.number_of_shards", shardSplits[1]).build()).get());
        ensureGreen();
        assertHitCount(client().prepareSearch("first_split").setSize(100).setQuery(new TermsQueryBuilder("foo", "bar")).get(), numDocs);

        for (int i = 0; i < numDocs; i++) { // now update
            IndexRequestBuilder builder = indexFunc.apply("first_split", i);
            if (useRouting) {
                builder.setRouting(routingValue[i]);
            }
            builder.get();
        }
        flushAndRefresh();
        assertHitCount(client().prepareSearch("first_split").setSize(100).setQuery(new TermsQueryBuilder("foo", "bar")).get(), numDocs);
        assertHitCount(client().prepareSearch("source").setSize(100).setQuery(new TermsQueryBuilder("foo", "bar")).get(), numDocs);
        for (int i = 0; i < numDocs; i++) {
            GetResponse getResponse = client().prepareGet("first_split", "t1", Integer.toString(i)).setRouting(routingValue[i]).get();
            assertTrue(getResponse.isExists());
        }

        client().admin().indices().prepareUpdateSettings("first_split")
            .setSettings(Settings.builder()
                .put("index.blocks.write", true)).get();
        ensureGreen();
        // now split source into a new index
        assertAcked(client().admin().indices().prepareResizeIndex("first_split", "second_split")
            .setResizeType(ResizeType.SPLIT)
            .setSettings(Settings.builder()
                .put("index.number_of_replicas", 0)
                .put("index.number_of_shards", shardSplits[2]).build()).get());
        ensureGreen();
        assertHitCount(client().prepareSearch("second_split").setSize(100).setQuery(new TermsQueryBuilder("foo", "bar")).get(), numDocs);
        // let it be allocated anywhere and bump replicas
        client().admin().indices().prepareUpdateSettings("second_split")
            .setSettings(Settings.builder()
                .put("index.number_of_replicas", 1)).get();
        ensureGreen();
        assertHitCount(client().prepareSearch("second_split").setSize(100).setQuery(new TermsQueryBuilder("foo", "bar")).get(), numDocs);

        for (int i = 0; i < numDocs; i++) { // now update
            IndexRequestBuilder builder = indexFunc.apply("second_split", i);
            if (useRouting) {
                builder.setRouting(routingValue[i]);
            }
            builder.get();
        }
        flushAndRefresh();
        for (int i = 0; i < numDocs; i++) {
            GetResponse getResponse = client().prepareGet("second_split", "t1", Integer.toString(i)).setRouting(routingValue[i]).get();
            assertTrue(getResponse.isExists());
        }
        assertHitCount(client().prepareSearch("second_split").setSize(100).setQuery(new TermsQueryBuilder("foo", "bar")).get(), numDocs);
        assertHitCount(client().prepareSearch("first_split").setSize(100).setQuery(new TermsQueryBuilder("foo", "bar")).get(), numDocs);
        assertHitCount(client().prepareSearch("source").setSize(100).setQuery(new TermsQueryBuilder("foo", "bar")).get(), numDocs);
        if (useNested) {
            assertNested("source", numDocs);
            assertNested("first_split", numDocs);
            assertNested("second_split", numDocs);
        }
        assertAllUniqueDocs(client().prepareSearch("second_split").setSize(100)
            .setQuery(new TermsQueryBuilder("foo", "bar")).get(), numDocs);
        assertAllUniqueDocs(client().prepareSearch("first_split").setSize(100)
            .setQuery(new TermsQueryBuilder("foo", "bar")).get(), numDocs);
        assertAllUniqueDocs(client().prepareSearch("source").setSize(100)
            .setQuery(new TermsQueryBuilder("foo", "bar")).get(), numDocs);
    }

    public void assertNested(String index, int numDocs) {
        // now, do a nested query
        SearchResponse searchResponse = client().prepareSearch(index).setQuery(nestedQuery("nested1", termQuery("nested1.n_field1",
            "n_value1_1"), ScoreMode.Avg)).get();
        assertNoFailures(searchResponse);
        assertThat(searchResponse.getHits().getTotalHits(), equalTo((long)numDocs));
    }

    public void assertAllUniqueDocs(SearchResponse response, int numDocs) {
        Set<String> ids = new HashSet<>();
        for (int i = 0; i < response.getHits().getHits().length; i++) {
            String id = response.getHits().getHits()[i].getId();
            assertTrue("found ID "+ id + " more than once", ids.add(id));
        }
        assertEquals(numDocs, ids.size());
    }

    public void testSplitIndexPrimaryTerm() throws Exception {
        final List<Integer> factors = Arrays.asList(1, 2, 4, 8);
        final List<Integer> numberOfShardsFactors = randomSubsetOf(scaledRandomIntBetween(1, factors.size()), factors);
        final int numberOfShards = randomSubsetOf(numberOfShardsFactors).stream().reduce(1, (x, y) -> x * y);
        final int numberOfTargetShards = numberOfShardsFactors.stream().reduce(2, (x, y) -> x * y);
        internalCluster().ensureAtLeastNumDataNodes(2);
        prepareCreate("source").setSettings(Settings.builder().put(indexSettings())
            .put("number_of_shards", numberOfShards)
            .put("index.number_of_routing_shards",  numberOfTargetShards)).get();

        final ImmutableOpenMap<String, DiscoveryNode> dataNodes =
                client().admin().cluster().prepareState().get().getState().nodes().getDataNodes();
        assertThat(dataNodes.size(), greaterThanOrEqualTo(2));
        ensureYellow();

        // fail random primary shards to force primary terms to increase
        final Index source = resolveIndex("source");
        final int iterations = scaledRandomIntBetween(0, 16);
        for (int i = 0; i < iterations; i++) {
            final String node = randomSubsetOf(1, internalCluster().nodesInclude("source")).get(0);
            final IndicesService indexServices = internalCluster().getInstance(IndicesService.class, node);
            final IndexService indexShards = indexServices.indexServiceSafe(source);
            for (final Integer shardId : indexShards.shardIds()) {
                final IndexShard shard = indexShards.getShard(shardId);
                if (shard.routingEntry().primary() && randomBoolean()) {
                    disableAllocation("source");
                    shard.failShard("test", new Exception("test"));
                    // this can not succeed until the shard is failed and a replica is promoted
                    int id = 0;
                    while (true) {
                        // find an ID that routes to the right shard, we will only index to the shard that saw a primary failure
                        final String s = Integer.toString(id);
                        final int hash = Math.floorMod(Murmur3HashFunction.hash(s), numberOfShards);
                        if (hash == shardId) {
                            final IndexRequest request =
                                    new IndexRequest("source", "type", s).source("{ \"f\": \"" + s + "\"}", XContentType.JSON);
                            client().index(request).get();
                            break;
                        } else {
                            id++;
                        }
                    }
                    enableAllocation("source");
                    ensureGreen();
                }
            }
        }

        final Settings.Builder prepareSplitSettings = Settings.builder().put("index.blocks.write", true);
        client().admin().indices().prepareUpdateSettings("source").setSettings(prepareSplitSettings).get();
        ensureYellow();

        final IndexMetaData indexMetaData = indexMetaData(client(), "source");
        final long beforeSplitPrimaryTerm = IntStream.range(0, numberOfShards).mapToLong(indexMetaData::primaryTerm).max().getAsLong();

        // now split source into target
        final Settings splitSettings =
                Settings.builder().put("index.number_of_replicas", 0).put("index.number_of_shards", numberOfTargetShards).build();
        assertAcked(client().admin().indices().prepareResizeIndex("source", "target")
            .setResizeType(ResizeType.SPLIT)
            .setSettings(splitSettings).get());

        ensureGreen();

        final IndexMetaData aftersplitIndexMetaData = indexMetaData(client(), "target");
        for (int shardId = 0; shardId < numberOfTargetShards; shardId++) {
            assertThat(aftersplitIndexMetaData.primaryTerm(shardId), equalTo(beforeSplitPrimaryTerm + 1));
        }
    }

    private static IndexMetaData indexMetaData(final Client client, final String index) {
        final ClusterStateResponse clusterStateResponse = client.admin().cluster().state(new ClusterStateRequest()).actionGet();
        return clusterStateResponse.getState().metaData().index(index);
    }

    public void testCreateSplitIndex() {
        internalCluster().ensureAtLeastNumDataNodes(2);
        Version version = VersionUtils.randomVersionBetween(random(), Version.V_6_0_0_rc2, Version.CURRENT);
        prepareCreate("source").setSettings(Settings.builder().put(indexSettings())
            .put("number_of_shards", 1)
            .put("index.version.created", version)
            .put("index.number_of_routing_shards",  2)
        ).get();
        final int docs = randomIntBetween(0, 128);
        for (int i = 0; i < docs; i++) {
            client().prepareIndex("source", "type")
                .setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", XContentType.JSON).get();
        }
        ImmutableOpenMap<String, DiscoveryNode> dataNodes =
                client().admin().cluster().prepareState().get().getState().nodes().getDataNodes();
        assertTrue("at least 2 nodes but was: " + dataNodes.size(), dataNodes.size() >= 2);
        // ensure all shards are allocated otherwise the ensure green below might not succeed since we require the merge node
        // if we change the setting too quickly we will end up with one replica unassigned which can't be assigned anymore due
        // to the require._name below.
        ensureGreen();
        // relocate all shards to one node such that we can merge it.
        client().admin().indices().prepareUpdateSettings("source")
            .setSettings(Settings.builder()
                .put("index.blocks.write", true)).get();
        ensureGreen();

        final IndicesStatsResponse sourceStats = client().admin().indices().prepareStats("source").setSegments(true).get();

        // disable rebalancing to be able to capture the right stats. balancing can move the target primary
        // making it hard to pin point the source shards.
        client().admin().cluster().prepareUpdateSettings().setTransientSettings(Settings.builder().put(
            EnableAllocationDecider.CLUSTER_ROUTING_REBALANCE_ENABLE_SETTING.getKey(), "none"
        )).get();
        try {

            final boolean createWithReplicas = randomBoolean();
            assertAcked(client().admin().indices().prepareResizeIndex("source", "target")
                .setResizeType(ResizeType.SPLIT)
                .setSettings(Settings.builder()
                    .put("index.number_of_replicas", createWithReplicas ? 1 : 0)
                    .put("index.number_of_shards", 2).build()).get());
            ensureGreen();

            final ClusterState state = client().admin().cluster().prepareState().get().getState();
            DiscoveryNode mergeNode = state.nodes().get(state.getRoutingTable().index("target").shard(0).primaryShard().currentNodeId());
            logger.info("split node {}", mergeNode);

            final long maxSeqNo = Arrays.stream(sourceStats.getShards())
                .filter(shard -> shard.getShardRouting().currentNodeId().equals(mergeNode.getId()))
                .map(ShardStats::getSeqNoStats).mapToLong(SeqNoStats::getMaxSeqNo).max().getAsLong();
            final long maxUnsafeAutoIdTimestamp = Arrays.stream(sourceStats.getShards())
                .filter(shard -> shard.getShardRouting().currentNodeId().equals(mergeNode.getId()))
                .map(ShardStats::getStats)
                .map(CommonStats::getSegments)
                .mapToLong(SegmentsStats::getMaxUnsafeAutoIdTimestamp)
                .max()
                .getAsLong();

            final IndicesStatsResponse targetStats = client().admin().indices().prepareStats("target").get();
            for (final ShardStats shardStats : targetStats.getShards()) {
                final SeqNoStats seqNoStats = shardStats.getSeqNoStats();
                final ShardRouting shardRouting = shardStats.getShardRouting();
                assertThat("failed on " + shardRouting, seqNoStats.getMaxSeqNo(), equalTo(maxSeqNo));
                assertThat("failed on " + shardRouting, seqNoStats.getLocalCheckpoint(), equalTo(maxSeqNo));
                assertThat("failed on " + shardRouting,
                    shardStats.getStats().getSegments().getMaxUnsafeAutoIdTimestamp(), equalTo(maxUnsafeAutoIdTimestamp));
            }

            final int size = docs > 0 ? 2 * docs : 1;
            assertHitCount(client().prepareSearch("target").setSize(size).setQuery(new TermsQueryBuilder("foo", "bar")).get(), docs);

            if (createWithReplicas == false) {
                // bump replicas
                client().admin().indices().prepareUpdateSettings("target")
                    .setSettings(Settings.builder()
                        .put("index.number_of_replicas", 1)).get();
                ensureGreen();
                assertHitCount(client().prepareSearch("target").setSize(size).setQuery(new TermsQueryBuilder("foo", "bar")).get(), docs);
            }

            for (int i = docs; i < 2 * docs; i++) {
                client().prepareIndex("target", "type")
                    .setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", XContentType.JSON).get();
            }
            flushAndRefresh();
            assertHitCount(client().prepareSearch("target").setSize(2 * size).setQuery(new TermsQueryBuilder("foo", "bar")).get(),
                2 * docs);
            assertHitCount(client().prepareSearch("source").setSize(size).setQuery(new TermsQueryBuilder("foo", "bar")).get(), docs);
            GetSettingsResponse target = client().admin().indices().prepareGetSettings("target").get();
            assertEquals(version, target.getIndexToSettings().get("target").getAsVersion("index.version.created", null));
        } finally {
            // clean up
            client().admin().cluster().prepareUpdateSettings().setTransientSettings(Settings.builder().put(
                EnableAllocationDecider.CLUSTER_ROUTING_REBALANCE_ENABLE_SETTING.getKey(), (String)null
            )).get();
        }

    }

    public void testCreateSplitWithIndexSort() throws Exception {
        SortField expectedSortField = new SortedSetSortField("id", true, SortedSetSelector.Type.MAX);
        expectedSortField.setMissingValue(SortedSetSortField.STRING_FIRST);
        Sort expectedIndexSort = new Sort(expectedSortField);
        internalCluster().ensureAtLeastNumDataNodes(2);
        prepareCreate("source")
            .setSettings(
                Settings.builder()
                    .put(indexSettings())
                    .put("sort.field", "id")
                    .put("index.number_of_routing_shards",  16)
                    .put("sort.order", "desc")
                    .put("number_of_shards", 2)
                    .put("number_of_replicas", 0)
            )
            .addMapping("type", "id", "type=keyword,doc_values=true")
            .get();
        for (int i = 0; i < 20; i++) {
            client().prepareIndex("source", "type", Integer.toString(i))
                .setSource("{\"foo\" : \"bar\", \"id\" : " + i + "}", XContentType.JSON).get();
        }
        ImmutableOpenMap<String, DiscoveryNode> dataNodes = client().admin().cluster().prepareState().get().getState().nodes()
            .getDataNodes();
        assertTrue("at least 2 nodes but was: " + dataNodes.size(), dataNodes.size() >= 2);
        DiscoveryNode[] discoveryNodes = dataNodes.values().toArray(DiscoveryNode.class);
        String mergeNode = discoveryNodes[0].getName();
        // ensure all shards are allocated otherwise the ensure green below might not succeed since we require the merge node
        // if we change the setting too quickly we will end up with one replica unassigned which can't be assigned anymore due
        // to the require._name below.
        ensureGreen();

        flushAndRefresh();
        assertSortedSegments("source", expectedIndexSort);

        client().admin().indices().prepareUpdateSettings("source")
            .setSettings(Settings.builder()
                .put("index.blocks.write", true)).get();
        ensureYellow();

        // check that index sort cannot be set on the target index
        IllegalArgumentException exc = expectThrows(IllegalArgumentException.class,
            () -> client().admin().indices().prepareResizeIndex("source", "target")
                .setResizeType(ResizeType.SPLIT)
                .setSettings(Settings.builder()
                    .put("index.number_of_replicas", 0)
                    .put("index.number_of_shards", 4)
                    .put("index.sort.field", "foo")
                    .build()).get());
        assertThat(exc.getMessage(), containsString("can't override index sort when resizing an index"));

        // check that the index sort order of `source` is correctly applied to the `target`
        assertAcked(client().admin().indices().prepareResizeIndex("source", "target")
            .setResizeType(ResizeType.SPLIT)
            .setSettings(Settings.builder()
                .put("index.number_of_replicas", 0)
                .put("index.number_of_shards", 4).build()).get());
        ensureGreen();
        flushAndRefresh();
        GetSettingsResponse settingsResponse =
            client().admin().indices().prepareGetSettings("target").execute().actionGet();
        assertEquals(settingsResponse.getSetting("target", "index.sort.field"), "id");
        assertEquals(settingsResponse.getSetting("target", "index.sort.order"), "desc");
        assertSortedSegments("target", expectedIndexSort);

        // ... and that the index sort is also applied to updates
        for (int i = 20; i < 40; i++) {
            client().prepareIndex("target", "type")
                .setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", XContentType.JSON).get();
        }
        flushAndRefresh();
        assertSortedSegments("target", expectedIndexSort);
    }
}


text:
/**
 * Master Controller
 */

'use strict';
app.controller('MasterCtrl', ['$scope', '$http', '$rootScope', 'cfpLoadingBar', '$location', '$cookieStore', '$window', 'UserService', function ($scope, $http, $rootScope, cfpLoadingBar, $location, $cookieStore, $window, UserService) {

    /**
     * Sidebar Toggle & Cookie Control
     *
     */
    var mobileView = 992;

    $scope.getWidth = function () {
        return window.innerWidth;
    };

    $scope.$watch($scope.getWidth, function (newValue, oldValue) {
        if (newValue >= mobileView) {
            if (angular.isDefined($cookieStore.get('toggle'))) {
                if ($cookieStore.get('toggle') == false) {
                    $scope.toggle = false;
                }
                else {
                    $scope.toggle = true;
                }
            }
            else {
                $scope.toggle = true;
            }
        }
        else {
            $scope.toggle = false;
        }

    });

    $scope.toggleSidebar = function () {
        $scope.toggle = !$scope.toggle;
        $cookieStore.put('toggle', $scope.toggle);
    };

    window.onresize = function () {
        $scope.$apply();
    };

    $scope.init = function init() {
        $scope.user = UserService.getCurrentUser();
    };

    $scope.$on('login', function(event, args){
        $scope.user = args;
    });

    $scope.$on('logout', function(event, args){
       $scope.user = undefined;
    });

    $scope.$on("$locationChangeStart", function(event, next, current) {
        console.log("location changing to:" + next);
        var title = 'Fantasy Ally';

        if(next.indexOf('/scoreboards') > -1){
            title = 'Live Scoreboard';
        }else if(next.indexOf('/sites') > -1){
            title = 'Teams';
        }else if(next.indexOf('/account') > -1){
            title = 'Account';
        }

        $scope.title = title;
    });

    $scope.logout = function logout() {
        UserService.logout().then(function (data) {
            $rootScope.$broadcast('logout', data);
            $location.path('/login');
        }, function (err) {
            $location.path('/login');
        });
    };
}]);


text:
<?php

class sfCloudControlMongoDBLoggerListener
{
  /**
   * Adds the current worker id to the log entry.
   *
   * The key 'wrk_id' will be added containing the worker identifier.
   * If this is not a worker process, no changes will be made.
   *
   * @param sfEvent $event
   * @param array $logEntry
   *
   * @return array
   */
  public static function addWorkerId(sfEvent $event, array $logEntry)
  {
    if (CloudControlBaseTask::isWorker())
    {
      $logEntry['wrk_id'] = CloudControlBaseTask::getWorkerId();
    }

    return $logEntry;
  }
}


text:
        <button type="button" class="close" data-dismiss="modal" aria-label="Fechar">×</button>

Excluir Item

        Deseja realmente excluir este item?

        Sim
        Não


text:
using System;
using System.Reflection;

[assembly: AssemblyTitle("Worms")]
[assembly: AssemblyDescription("Awaitable Synchronization Primitives Library")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Worms")]
[assembly: AssemblyCopyright("Copyright \u00a9 2015 Atif Aziz. All rights reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Debug or release configuration?

#if DEBUG
[assembly: AssemblyConfiguration("DEBUG")]
#else
[assembly: AssemblyConfiguration("RELEASE")]
#endif

[assembly: CLSCompliant(true)]


text:
package com.sixt.service.framework.util;

import com.google.protobuf.Message;

// marker interface to bypass normal reflection mechanism for
// our contract-testing infrastructure
public interface MockMethodHandler<REQ extends Message, RES extends Message> {

    Class<REQ> getRequestType();

    Class<RES> getResponseType();

    int getMethodCallCounter();

    void resetMethodCallCounter();
}


text:
package course.labs.notificationslab.test;

import course.labs.notificationslab.TestFrontEndActivity;
import com.robotium.solo.*;
import android.test.ActivityInstrumentationTestCase2;

/* Version 2 - updated 10/28/2014  */

public class OldFeedWithNotificationTest extends
		ActivityInstrumentationTestCase2<TestFrontEndActivity> {
	private Solo solo;

	public OldFeedWithNotificationTest() {
		super(TestFrontEndActivity.class);
	}

	public void setUp() throws Exception {
		solo = new Solo(getInstrumentation());
		getActivity();
	}

	@Override
	public void tearDown() throws Exception {
		solo.finishOpenedActivities();
	}

	public void testRun() {

		int longDelay = 2000;

		// Clear the Log
		solo.clearLog();

		// Wait for activity:
		// 'course.labs.notificationslab.TestFrontEndActivity'
		solo.waitForActivity(
				course.labs.notificationslab.TestFrontEndActivity.class, longDelay);

		// Click on Make Tweets Old
		solo.clickOnView(solo
				.getView(course.labs.notificationslab.R.id.age_tweets_button));

		// Click on Start Main Activity
		solo.clickOnView(solo
				.getView(course.labs.notificationslab.R.id.start_main_button));

		// Wait for activity: 'course.labs.notificationslab.MainActivity'
		assertTrue(
				"course.labs.notificationslab.MainActivity is not found!",
				solo.waitForActivity(course.labs.notificationslab.MainActivity.class));

		// Press menu back key
		solo.goBack();

		// Wait for activity:
		// 'course.labs.notificationslab.TestFrontEndActivity'
		assertTrue(
				"course.labs.notificationslab.TestFrontEndActivity is not found!",
				solo.waitForActivity(course.labs.notificationslab.TestFrontEndActivity.class));

		assertTrue("Should have seen notification sent log message",
				solo.waitForLogMessage("Notification Area Notification sent", longDelay));

	}
}


text:
/* User-specified role an environment should play in the replication group. */
typedef enum { MASTER, CLIENT, UNKNOWN } ENV_ROLE;

/* User-specified information about a replication site. */
typedef struct {
	char *host;		/* Host name. */
	u_int32_t port;		/* Port on which to connect to this site. */
	int peer;		/* Whether remote site is repmgr peer. */
	int creator;		/* Whether local site is group creator. */
} repsite_t;

/* Data used for common replication setup. */
typedef struct {
	const char *progname;
	char *home;
	int nsites;
	int remotesites;
	ENV_ROLE role;
	repsite_t self;
	repsite_t *site_list;
} SETUP_DATA;

/* Operational commands for the program. */
#define	REPCMD_INVALID	0
#define	REPCMD_EXIT	1
#define	REPCMD_GET	2
#define	REPCMD_HELP	3
#define	REPCMD_PRINT	4
#define	REPCMD_PUT	5	/* Put on master and return. */
#define	REPCMD_PUTSYNC	6	/* Put on master and wait for it
				   to be applied locally. */

/*
 * Max args for a command.  Although the API itself does not have
 * a maximum, it is simpler for the example code to just have space
 * allocated ahead of time.  We use an odd number so that we can
 * have the header DBT plus some number of key/data pairs.
 */
#define	REPCMD_MAX_DBT	33

/* Reply commands. */
#define	REPREPLY_ERROR	1
#define	REPREPLY_OK	0

#define	REPLY_ERROR_NDBT    2
#define	REPLY_TOKEN_TIMEOUT	5000000	/* 5 seconds, arbitrary */

/*
 * General program defines
 */
#define	BUFSIZE 1024
#define	CACHESIZE	(10 * 1024 * 1024)
#define	DATABASE	"quote.db"

extern const char *progname;

/* Portability macros for basic threading & timing */
#ifdef _WIN32
#define	WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#define	snprintf		_snprintf
#define	sleep(s)		Sleep(1000 * (s))

extern int getopt(int, char * const *, const char *);

typedef HANDLE thread_t;
#define	thread_create(thrp, attr, func, arg)				   \
    (((*(thrp) = CreateThread(NULL, 0,					   \
	(LPTHREAD_START_ROUTINE)(func), (arg), 0, NULL)) == NULL) ? -1 : 0)
#define	thread_join(thr, statusp)					   \
    ((WaitForSingleObject((thr), INFINITE) == WAIT_OBJECT_0) &&		   \
    GetExitCodeThread((thr), (LPDWORD)(statusp)) ? 0 : -1)

typedef HANDLE mutex_t;
#define	mutex_init(m, attr)                                                \
    (((*(m) = CreateMutex(NULL, FALSE, NULL)) != NULL) ? 0 : -1)
#define	mutex_lock(m)                                                      \
    ((WaitForSingleObject(*(m), INFINITE) == WAIT_OBJECT_0) ? 0 : -1)
#define	mutex_unlock(m)         (ReleaseMutex(*(m)) ? 0 : -1)

#else /* !_WIN32 */
#include <sys/time.h>
#include <pthread.h>

typedef pthread_t thread_t;
#define	thread_create(thrp, attr, func, arg)				   \
    pthread_create((thrp), (attr), (func), (arg))
#define	thread_join(thr, statusp) pthread_join((thr), (statusp))

typedef pthread_mutex_t mutex_t;
#define mutex_init(m, attr)     pthread_mutex_init((m), (attr))
#define mutex_lock(m)           pthread_mutex_lock(m)
#define mutex_unlock(m)         pthread_mutex_unlock(m)

#endif

/* Global data. */
typedef struct {
	DB_ENV *dbenv;
	mutex_t mutex;
	int is_master;
	int app_finished;
	int in_client_sync;
	DB_CHANNEL *channel;
	DB *dbp;
} GLOBAL;

void *checkpoint_thread __P((void *));
int create_env __P((const char *, DB_ENV **));
int env_init __P((DB_ENV *, const char *));
void event_callback __P((DB_ENV *, u_int32_t, void *));
int finish_support_threads __P((thread_t *, thread_t *));
void *log_archive_thread __P((void *));
int open_dbp __P((DB_ENV *, int, DB **));
int parse_cmd __P((char *));
void print_cmdhelp __P(());
void print_one __P((void *, u_int32_t, void *, u_int32_t, int));
int print_stocks __P((DB *));
int rep_setup __P((DB_ENV *, int, char **, SETUP_DATA *));
int start_support_threads __P((DB_ENV *, GLOBAL *, thread_t *,
    thread_t *));
void usage __P((const char *));


text:
/* Outermost container. */
.tumblr-reader-posts {
    color: #202020;
}

/* All posts. */
.tumblr-reader-post {
    padding-top: 10px;
    padding-bottom: 10px;
    border-bottom: 1px solid white;
}

.tumblr-reader-date {
    float: left;
    font-size: 11px;
    padding-bottom: 5px;
    color: #a0a0a0;
}

.tumblr-reader-tags {
    color: #a0a0a0;
    font-size: 11px;
    float: right;
}

/* Regular (text) posts. */
.tumblr-reader-post.tumblr-reader-post-regular {
}

.tumblr-reader-title {
    clear: left;
    font-size: 16px;
    padding-bottom: 5px;
}

/* Link posts. */
.tumblr-reader-post.tumblr-reader-post-link {
}

.tumblr-reader-post.tumblr-reader-post-link .tumblr-reader-date {
    display: none;
}

.tumblr-reader-post.tumblr-reader-post-link .tumblr-reader-tags {
    display: none;
}

.tumblr-reader-link {
    font-size: 16px;
}

.tumblr-reader-link:after {
    display: inline-block;
    padding-left: 5px;
    content: "»"
}

/* Quote posts. */
.tumblr-reader-post.tumblr-reader-post-quote {
}

.tumblr-reader-quote {
    padding-left: 40px;
    padding-right: 40px;
    font-style: italic;
    clear: both;
}

.tumblr-reader-source {
    padding-right: 40px;
    float: right;
    clear: both;
}

.tumblr-reader-source:before {
    content: "–"
}

/* Conversation posts. */
.tumblr-reader-post.tumblr-reader-conversation {

}

.tumblr-reader-phrase {
}

.tumblr-reader-name {
    font-weight: bold;
}

.tumblr-reader-name:after {
    content: ": "
}

/* Photo posts. */
.tumblr-reader-post.tumblr-reader-post-photo {
}

.tumblr-reader-photo {
    clear: both;
}

.tumblr-reader-photo img {
    display: block;
    max-width: 100%;
}

.tumblr-reader-caption {
    text-align: center;
}


text:
Gradle - Comsat Spring 4 MVC Hello World
========================================
Template for Comsat Spring 4 MVC + JSP view + Annotation configuration, using Gradle.

###1. Technologies used
* Cargo with Tomcat 7 or 8
* Gradle 2
* Comsat with Spring Framework 4.1.6.RELEASE (Spring controller requests will be served by more efficient Quasar fibers rather than Java threads)
* JSTL 1.2
* Logback 1.1.3
* Boostrap 3

###2. To Run this project locally
```shell
$ git clone https://github.com/circlespainter/spring4-mvc-gradle-annotation-hello-world
$ gradle [-Penv=tomcat7] cargoRunLocal
```
Access ```http://localhost:8080/spring4-mvc-gradle-annotation-hello-world/hello/<yourname>```

###4. Project Demo
Please refer to this article [Gradle - Spring 4 MVC Hello World + Annotation ](http://www.mkyong.com/spring-mvc/gradle-spring-4-mvc-hello-world-example-annotation/)


text:
<template name="interfaceStephens">

    {{#HammerTouchArea gestureMap=templateGestures}}
      <video id="interface-stephens-video" class="video-js vjs-default-skin trigger" autoplay loop preload="auto" width="1024" height="528">
        <source src="/media/stephens/interface/applelarge.mp4" type='video/mp4' />
      </video>
      T
      <svg xmlns="http://www.w3.org/2000/svg" fill="#FFFFFF" height="50" viewBox="0 0 24 24" width="50">
          <path d="M0 0h24v24H0z" fill="none"/>
          <path d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"/>
      </svg>
    {{/HammerTouchArea}}

</template>


text:
<!DOCTYPE html>

jsonrpc

  Service Type <input type="text" id="serviceType" value="echo" />

  Method <input type="text" id="method" value="echo.upper" />

  Arguments <input type="text" id="args" value='{ "text": "hello" }' />

  <input type="button" id="doIt" value="Submit" onClick="doItFunction()" />


text:
package org.semanticweb.elk.reasoner.indexing.model;

import org.semanticweb.elk.owl.interfaces.ElkAxiom;

/**
 * Represents a transformation of an {@link ElkAxiom} to an
 * {@link IndexedObjectPropertyRangeAxiom}.
 *
 * @author Yevgeny Kazakov
 *
 */
public interface IndexedObjectPropertyRangeAxiomInference
		extends
			IndexedAxiomInference {

	/**
	 * @param factory
	 *            the factory for creating conclusions
	 *
	 * @return the conclusion produced by this inference
	 */
	public IndexedObjectPropertyRangeAxiom getConclusion(
			IndexedObjectPropertyRangeAxiom.Factory factory);

	/**
	 * The visitor pattern for instances
	 *
	 * @author Yevgeny Kazakov
	 *
	 * @param <O>
	 *            the type of the output
	 */
	interface Visitor<O>
			extends
				ElkObjectPropertyRangeAxiomConversion.Visitor<O> {

		// combined interface

	}

	<O> O accept(Visitor<O> visitor);

}


text: cyber-hr-restapi


text:
package com.facebook.buck.rust;

import static org.junit.Assert.assertThat;

import com.facebook.buck.cxx.toolchain.linker.Linker;
import com.facebook.buck.io.file.FileScrubber;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.DefaultSourcePathResolver;
import com.facebook.buck.rules.FakeSourcePath;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.TestBuildRuleParams;
import com.facebook.buck.rules.TestBuildRuleResolver;
import com.facebook.buck.rules.Tool;
import com.facebook.buck.rules.args.Arg;
import com.facebook.buck.rules.args.StringArg;
import com.facebook.buck.testutil.FakeProjectFilesystem;
import com.facebook.buck.util.HumanReadableException;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import java.nio.file.Path;
import java.util.Optional;
import java.util.stream.Stream;
import org.hamcrest.Matchers;
import org.junit.Test;

public class RustCompileTest {
  @Test(expected = HumanReadableException.class)
  public void noCrateRootInSrcs() {
    RustCompileRule linkable = FakeRustCompileRule.from("//:donotcare", ImmutableSortedSet.of());
    linkable.getCrateRoot();
  }

  @Test
  public void crateRootMainInSrcs() {
    RustCompileRule linkable =
        FakeRustCompileRule.from(
            "//:donotcare", ImmutableSortedSet.of(FakeSourcePath.of("main.rs")));
    assertThat(linkable.getCrateRoot().toString(), Matchers.endsWith("main.rs"));
  }

  @Test
  public void crateRootTargetNameInSrcs() {
    RustCompileRule linkable =
        FakeRustCompileRule.from(
            "//:myname", ImmutableSortedSet.of(FakeSourcePath.of("myname.rs")));
    assertThat(linkable.getCrateRoot().toString(), Matchers.endsWith("myname.rs"));
  }

  // Test that there's only one valid candidate root source file.
  @Test(expected = HumanReadableException.class)
  public void crateRootMainAndTargetNameInSrcs() {
    RustCompileRule linkable =
        FakeRustCompileRule.from(
            "//:myname",
            ImmutableSortedSet.of(FakeSourcePath.of("main.rs"), FakeSourcePath.of("myname.rs")));
    linkable.getCrateRoot();
  }

  private static Tool fakeTool() {
    return new Tool() {
      @Override
      public ImmutableList<String> getCommandPrefix(SourcePathResolver resolver) {
        return ImmutableList.of();
      }

      @Override
      public ImmutableMap<String, String> getEnvironment(SourcePathResolver resolver) {
        return ImmutableMap.of();
      }
    };
  }

  private static Linker fakeLinker() {
    return new Linker() {
      @Override
      public ImmutableList<FileScrubber> getScrubbers(ImmutableMap<Path, Path> cellRootMap) {
        return null;
      }

      @Override
      public Iterable<Arg> linkWhole(Arg input) {
        return null;
      }

      @Override
      public Iterable<String> soname(String soname) {
        return null;
      }

      @Override
      public Iterable<Arg> fileList(Path fileListPath) {
        return null;
      }

      @Override
      public String origin() {
        return null;
      }

      @Override
      public String libOrigin() {
        return null;
      }

      @Override
      public String searchPathEnvVar() {
        return null;
      }

      @Override
      public String preloadEnvVar() {
        return null;
      }

      @Override
      public Iterable<String> getNoAsNeededSharedLibsFlags() {
        return null;
      }

      @Override
      public Iterable<String> getIgnoreUndefinedSymbolsFlags() {
        return null;
      }

      @Override
      public ImmutableList<Arg> createUndefinedSymbolsLinkerArgs(
          ProjectFilesystem projectFilesystem,
          BuildRuleParams baseParams,
          BuildRuleResolver ruleResolver,
          SourcePathRuleFinder ruleFinder,
          BuildTarget target,
          Iterable<? extends SourcePath> symbolFiles) {
        return null;
      }

      @Override
      public Iterable<Arg> getSharedLibFlag() {
        return null;
      }

      @Override
      public Iterable<String> outputArgs(String path) {
        return null;
      }

      @Override
      public boolean hasFilePathSizeLimitations() {
        return false;
      }

      @Override
      public SharedLibraryLoadingType getSharedLibraryLoadingType() {
        return SharedLibraryLoadingType.RPATH;
      }

      @Override
      public ImmutableList<String> getCommandPrefix(SourcePathResolver resolver) {
        return ImmutableList.of();
      }

      @Override
      public ImmutableMap<String, String> getEnvironment(SourcePathResolver resolver) {
        return ImmutableMap.of();
      }
    };
  }

  static class FakeRustCompileRule extends RustCompileRule {
    private FakeRustCompileRule(
        BuildTarget target, ImmutableSortedSet<SourcePath> srcs, SourcePath rootModule) {
      super(
          target,
          new FakeProjectFilesystem(),
          TestBuildRuleParams.create(),
          String.format("lib%s.rlib", target),
          fakeTool(),
          fakeLinker(),
          Stream.of("--crate-name", target.getShortName(), "--crate-type", "rlib")
              .map(StringArg::of)
              .collect(ImmutableList.toImmutableList()),
          /* depArgs */ ImmutableList.of(),
          /* linkerFlags */
          ImmutableList.of(),
          srcs,
          rootModule,
          true,
          RustBuckConfig.RemapSrcPaths.NO);
    }

    static FakeRustCompileRule from(String target, ImmutableSortedSet<SourcePath> srcs) {
      BuildTarget buildTarget = BuildTargetFactory.newInstance(target);

      SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(new TestBuildRuleResolver());

      SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);

      Optional<SourcePath> root =
          RustCompileUtils.getCrateRoot(
              pathResolver,
              buildTarget.getShortName(),
              ImmutableSet.of("main.rs", "lib.rs"),
              srcs.stream());

      if (!root.isPresent()) {
        throw new HumanReadableException("No crate root source identified");
      }
      return new FakeRustCompileRule(buildTarget, srcs, root.get());
    }
  }
}


text:
package org.jmeterplugins.repository.http;

import org.apache.http.HttpResponse;
import org.apache.http.ProtocolVersion;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicStatusLine;
import org.junit.Test;

import static org.junit.Assert.*;

public class HttpRetryStrategyTest {

    @Test
    public void testFlow() throws Exception {
        HttpRetryStrategy strategy = new HttpRetryStrategy();
        HttpResponse response = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("HTTP",1,1), 200, ""));
        assertFalse(strategy.retryRequest(response, 1, null));

        strategy = new HttpRetryStrategy(2, 3333);
        response = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("HTTP",1,1), 301, ""));
        assertTrue(strategy.retryRequest(response, 1, null));
        assertFalse(strategy.retryRequest(response, 4, null));

        assertEquals(2, strategy.getMaxRetries());
        assertEquals(3333, strategy.getRetryInterval());

        try {
            new HttpRetryStrategy(-1, 2222);
            fail();
        } catch (IllegalArgumentException ex) {
            assertEquals("MaxRetries must be greater than 1", ex.getMessage());
        }

        try {
            new HttpRetryStrategy(2, -1);
            fail();
        } catch (IllegalArgumentException ex) {
            assertEquals("Retry interval must be greater than 1", ex.getMessage());
        }

    }
}


text:
package ru.maizy.cheesecake.server

import java.util.concurrent.atomic.AtomicBoolean
import scala.util.{ Failure, Success, Try }
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import com.typesafe.config.{ Config, ConfigFactory }
import com.typesafe.scalalogging.Logger
import org.slf4j.LoggerFactory
import ru.maizy.cheesecake.server.jsonapi.JsonApi
import sun.misc.{ Signal, SignalHandler }

object ServerApp extends App with SignalHandler {
  val STATUS_BAD_OPTIONS = 2
  val STATUS_BAD_CONFIG = 3
  val STATUS_UNABLE_TO_BIND = 10

  val SIGING = "INT"
  val SIGTERM = "TERM"

  var actorSystem: Option[ActorSystem] = None

  val terminated = new AtomicBoolean(false)
  val appLogger = Logger(LoggerFactory.getLogger(s"${BuildInfo.organization}.${BuildInfo.projectName}"))

  appLogger.info("Subscribe to SIGING, SIGTERM signals")
  Signal.handle(new Signal(SIGING), this)
  Signal.handle(new Signal(SIGTERM), this)

  OptionParser.parse(args) match {
    case None =>
      appLogger.error("Wrong app options, exiting")
      System.exit(STATUS_BAD_OPTIONS)
    case Some(opts) => startUp(opts)
  }

  def loadConfig(opts: ServerAppOptions): Try[Config] = {
    val loadedConfig = ConfigFactory.load()
    val appConfig = ConfigFactory
      .parseString(
        s"""
          |akka.http.client.user-agent-header = cheesecake/${Version.literal}
          |akka.http.server.server-header = cheesecake/${Version.literal} (akka-http/$${akka.version})
        """.stripMargin
      )
      .resolveWith(loadedConfig)
      .withFallback(loadedConfig)

    opts.config match {
      case None => Success(appConfig)
      case Some(additionalConfigFile) =>
        appLogger.info(s"Load additional config from $additionalConfigFile")
        Try {
          ConfigFactory.parseFile(additionalConfigFile)
            .resolveWith(appConfig)
            .withFallback(appConfig)
        }
    }
  }

  def startUp(opts: ServerAppOptions): Unit = {
    appLogger.info("Loading configs")
    loadConfig(opts) match {

      case Failure(e) =>
        appLogger.error(s"Unable to load configs: $e")
        System.exit(STATUS_BAD_CONFIG)

      case Success(config) =>
        implicit val system = ActorSystem("cheesecake-server", config)
        actorSystem = Some(system)
        implicit val materializer = ActorMaterializer()
        implicit val ec = system.dispatcher

        appLogger.debug(s"start with settings: ${system.settings.toString}")

        val host = opts.host
        val port = opts.port

        val initializer = new Initializer(system)

        appLogger.info("Initializing APIs & web UI")
        val wsApi = new WsApi(system, materializer)
        val jsonApi = new JsonApi(system, host, port)
        val webUi = new WebUI(system)

        val routes = jsonApi.routes ~ webUi.routes ~ wsApi.routes

        appLogger.info(s"Launching a HTTP server at http://$host:$port/")
        val bindFuture = Http().bindAndHandle(routes, host, port)

        bindFuture.onFailure {
          case e: Throwable =>
            appLogger.error(s"Unable to bind HTTP server: $e")
            System.exit(STATUS_UNABLE_TO_BIND)
        }

        bindFuture.foreach { serverBinding =>
          appLogger.info("Cheesecake HTTP server started")

          appLogger.info("Initializing checking services & endpoints")
          initializer.fromConfig(config)
        }
    }
  }

  override def handle(signal: Signal): Unit = {
    appLogger.info(s"Receive signal ${signal.getName}")
    if (terminated.compareAndSet(false, true)) {
      actorSystem foreach { system =>
        if (Seq(SIGING, SIGTERM).contains(signal.getName)) {
          appLogger.debug(s"Handle signal")
          system.terminate()
        }
      }
    } else {
      appLogger.warn("Application ever terminated, skip signal")
    }
  }
}


text:
Adds a single space in between sentences that don't have spacing. Useful after stripping html from a string.

## Usage

```html
{{"This will get spaced.Isn't it nice?It is!See?" | pmkr.spaceSentences}}
<!-- This will get spaced. Isn't it nice? It is! See? -->
```


text:
import logging
from pyvisdk.exceptions import InvalidArgumentError

########################################
# Automatically generated, do not edit.
########################################

log = logging.getLogger(__name__)

def VirtualMachineNetworkShaperInfo(vim, *args, **kwargs):
    '''Network traffic shaping specification.Traffic shaping is used to configure the
    network utilization characteristics of a virtual machine.'''

    obj = vim.client.factory.create('ns0:VirtualMachineNetworkShaperInfo')

    # do some validation checking...
    if (len(args) + len(kwargs)) < 0:
        raise IndexError('Expected at least 1 arguments got: %d' % len(args))

    required = [  ]
    optional = [ 'averageBps', 'burstSize', 'enabled', 'peakBps', 'dynamicProperty',
        'dynamicType' ]

    for name, arg in zip(required+optional, args):
        setattr(obj, name, arg)

    for name, value in kwargs.items():
        if name in required + optional:
            setattr(obj, name, value)
        else:
            raise InvalidArgumentError("Invalid argument: %s.  Expected one of %s" % (name, ", ".join(required + optional)))

    return obj


text:
#include "cinder/CameraUi.h"

namespace cinder {

CameraUi::CameraUi()
	: mCamera( nullptr ), mWindowSize( 640, 480 ), mMouseWheelMultiplier( 1.2f ), mMinimumPivotDistance( 1.0f ),
		mEnabled( true ), mLastAction( ACTION_NONE )
{}

CameraUi::CameraUi( CameraPersp *camera, const app::WindowRef &window, int signalPriority )
	: mCamera( camera ), mWindowSize( 640, 480 ), mMouseWheelMultiplier( 1.2f ), mMinimumPivotDistance( 1.0f ),
		mEnabled( true )
{
	connect( window, signalPriority );
}

CameraUi::CameraUi( const CameraUi &rhs )
	: mCamera( rhs.mCamera ), mWindowSize( rhs.mWindowSize ),
		mWindow( rhs.mWindow ), mSignalPriority( rhs.mSignalPriority ),
		mMouseWheelMultiplier( rhs.mMouseWheelMultiplier ), mMinimumPivotDistance( rhs.mMinimumPivotDistance ),
		mEnabled( rhs.mEnabled )
{
	connect( mWindow, mSignalPriority );
}

CameraUi::~CameraUi()
{
	disconnect();
}

CameraUi& CameraUi::operator=( const CameraUi &rhs )
{
	mCamera = rhs.mCamera;
	mWindowSize = rhs.mWindowSize;
	mMouseWheelMultiplier = rhs.mMouseWheelMultiplier;
	mMinimumPivotDistance = rhs.mMinimumPivotDistance;
	mWindow = rhs.mWindow;
	mSignalPriority = rhs.mSignalPriority;
	mEnabled = rhs.mEnabled;
	connect( mWindow, mSignalPriority );
	return *this;
}

//! Connects to mouseDown, mouseDrag, mouseWheel and resize signals of \a window, with optional priority \a signalPriority
void CameraUi::connect( const app::WindowRef &window, int signalPriority )
{
	if( ! mMouseConnections.empty() ) {
		for( auto &conn : mMouseConnections )
			conn.disconnect();
	}

	mWindow = window;
	mSignalPriority = signalPriority;
	if( window ) {
		mMouseConnections.push_back( window->getSignalMouseDown().connect( signalPriority,
			[this]( app::MouseEvent &event ) { mouseDown( event ); } ) );
		mMouseConnections.push_back( window->getSignalMouseUp().connect( signalPriority,
			[this]( app::MouseEvent &event ) { mouseUp( event ); } ) );
		mMouseConnections.push_back( window->getSignalMouseDrag().connect( signalPriority,
			[this]( app::MouseEvent &event ) { mouseDrag( event ); } ) );
		mMouseConnections.push_back( window->getSignalMouseWheel().connect( signalPriority,
			[this]( app::MouseEvent &event ) { mouseWheel( event ); } ) );
		mMouseConnections.push_back( window->getSignalResize().connect( signalPriority,
			[this]() {
				setWindowSize( mWindow->getSize() );
				if( mCamera )
					mCamera->setAspectRatio( mWindow->getAspectRatio() );
			}
		) );
	}
	else
		disconnect();

	mLastAction = ACTION_NONE;
}

//! Disconnects all signal handlers
void CameraUi::disconnect()
{
	for( auto &conn : mMouseConnections )
		conn.disconnect();

	mWindow.reset();
}

bool CameraUi::isConnected() const
{
	return mWindow != nullptr;
}

signals::Signal<void()>& CameraUi::getSignalCameraChange()
{
	return mSignalCameraChange;
}

void CameraUi::mouseDown( app::MouseEvent &event )
{
	if( ! mEnabled )
		return;

	mouseDown( event.getPos() );
	event.setHandled();
}

void CameraUi::mouseUp( app::MouseEvent &event )
{
	if( ! mEnabled )
		return;

	mouseUp( event.getPos() );
	event.setHandled();
}

void CameraUi::mouseWheel( app::MouseEvent &event )
{
	if( ! mEnabled )
		return;

	mouseWheel( event.getWheelIncrement() );
	event.setHandled();
}

void CameraUi::mouseUp( const vec2 &mousePos )
{
	mLastAction = ACTION_NONE;
}

void CameraUi::mouseDown( const vec2 &mousePos )
{
	if( ! mCamera || ! mEnabled )
		return;

	mInitialMousePos = mousePos;
	mInitialCam = *mCamera;
	mInitialPivotDistance = mCamera->getPivotDistance();
	mLastAction = ACTION_NONE;
}

void CameraUi::mouseDrag( app::MouseEvent &event )
{
	if( ! mEnabled )
		return;

	bool isLeftDown = event.isLeftDown();
	bool isMiddleDown = event.isMiddleDown() || event.isAltDown();
	bool isRightDown = event.isRightDown() || event.isControlDown();

	if( isMiddleDown )
		isLeftDown = false;

	mouseDrag( event.getPos(), isLeftDown, isMiddleDown, isRightDown );
	event.setHandled();
}

void CameraUi::mouseDrag( const vec2 &mousePos, bool leftDown, bool middleDown, bool rightDown )
{
	if( ! mCamera || ! mEnabled )
		return;

	int action;
	if( rightDown || ( leftDown && middleDown ) )
		action = ACTION_ZOOM;
	else if( middleDown )
		action = ACTION_PAN;
	else if( leftDown )
		action = ACTION_TUMBLE;
	else
		return;

	if( action != mLastAction ) {
		mInitialCam = *mCamera;
		mInitialPivotDistance = mCamera->getPivotDistance();
		mInitialMousePos = mousePos;
	}

	mLastAction = action;

	if( action == ACTION_ZOOM ) { // zooming
		int mouseDelta = ( mousePos.x - mInitialMousePos.x ) + ( mousePos.y - mInitialMousePos.y );

		float newPivotDistance = powf( 2.71828183f, 2 * -mouseDelta / length( vec2( getWindowSize() ) ) ) * mInitialPivotDistance;
		vec3 oldTarget = mInitialCam.getEyePoint() + mInitialCam.getViewDirection() * mInitialPivotDistance;
		vec3 newEye = oldTarget - mInitialCam.getViewDirection() * newPivotDistance;
		mCamera->setEyePoint( newEye );
		mCamera->setPivotDistance( std::max<float>( newPivotDistance, mMinimumPivotDistance ) );
	}
	else if( action == ACTION_PAN ) { // panning
		float deltaX = ( mousePos.x - mInitialMousePos.x ) / (float)getWindowSize().x * mInitialPivotDistance;
		float deltaY = ( mousePos.y - mInitialMousePos.y ) / (float)getWindowSize().y * mInitialPivotDistance;
		vec3 right, up;
		mInitialCam.getBillboardVectors( &right, &up );
		mCamera->setEyePoint( mInitialCam.getEyePoint() - right * deltaX + up * deltaY );
	}
	else { // tumbling
		float deltaX = ( mousePos.x - mInitialMousePos.x ) / -100.0f;
		float deltaY = ( mousePos.y - mInitialMousePos.y ) / 100.0f;
		vec3 mW = normalize( mInitialCam.getViewDirection() );
		bool invertMotion = ( mInitialCam.getOrientation() * mInitialCam.getWorldUp() ).y < 0.0f;

		vec3 mU = normalize( cross( mInitialCam.getWorldUp(), mW ) );

		if( invertMotion ) {
			deltaX = -deltaX;
			deltaY = -deltaY;
		}

		glm::vec3 rotatedVec = glm::angleAxis( deltaY, mU ) * ( -mInitialCam.getViewDirection() * mInitialPivotDistance );
		rotatedVec = glm::angleAxis( deltaX, mInitialCam.getWorldUp() ) * rotatedVec;

		mCamera->setEyePoint( mInitialCam.getEyePoint() + mInitialCam.getViewDirection() * mInitialPivotDistance + rotatedVec );
		mCamera->setOrientation( glm::angleAxis( deltaX, mInitialCam.getWorldUp() ) * glm::angleAxis( deltaY, mU ) * mInitialCam.getOrientation() );
	}

	mSignalCameraChange.emit();
}

void CameraUi::mouseWheel( float increment )
{
	if( ! mCamera || ! mEnabled )
		return;

	// some mice issue mouseWheel events during middle-clicks; filter that out
	if( mLastAction != ACTION_NONE )
		return;

	float multiplier;
	if( mMouseWheelMultiplier > 0 )
		multiplier = powf( mMouseWheelMultiplier, increment );
	else
		multiplier = powf( -mMouseWheelMultiplier, -increment );
	vec3 newEye = mCamera->getEyePoint() + mCamera->getViewDirection() * ( mCamera->getPivotDistance() * ( 1 - multiplier ) );
	mCamera->setEyePoint( newEye );
	mCamera->setPivotDistance( std::max<float>( mCamera->getPivotDistance() * multiplier, mMinimumPivotDistance ) );

	mSignalCameraChange.emit();
}

ivec2 CameraUi::getWindowSize() const
{
	if( mWindow )
		return mWindow->getSize();
	else
		return mWindowSize;
}

}; // namespace cinder


text:
import sys
import rospkg
import rospy
import tf
import numpy as np
import moveit_commander
from geometry_msgs.msg import PoseStamped, Pose
from baxter_interface import gripper as baxter_gripper
from std_msgs.msg import String, Bool
from geometry_msgs.msg import Transform

PROJECT_PATH = rospkg.RosPack().get_path('lab3')
sys.path.append(PROJECT_PATH+'/src/lab3')
sys.path.append(PROJECT_PATH+'/src/extra')

global left_arm
global left_gripper

def move_arm(data):
    global left_arm
    #define new target pose for arm to execute
    goal_pose = PoseStamped()
    goal_pose.header.frame_id = 'base'
    goal_pose.pose = data

    print('Setting Target Pose and Current State')
    #set left arm's target pose to new goal
    left_arm.set_pose_target(goal_pose)

    #Set the start state for the left arm
    left_arm.set_start_state_to_current_state()

    print('Planning Trajectory')
    #generate trajectory for target pose
    left_trajectory = left_arm.plan()

    print('Executing Trajectory')
    #execute trajectory
    left_arm.execute(left_trajectory)

def actuate_gripper(close_bool):
    global left_gripper

    if close_bool.data:
        #Close the left gripper
        print('Closing...')
        left_gripper.close(block=True)
        rospy.sleep(1.0)
    else:
        #Open the left gripper
        print('Opening...')
        left_gripper.open(block=True)
        rospy.sleep(1.0)

def main():
    global left_arm
    global left_gripper
    #Initialize moveit_commander
    moveit_commander.roscpp_initialize(sys.argv)

    #Start a node
    rospy.init_node('moveit_interface')

    #Set up Baxter Arms
    robot = moveit_commander.RobotCommander()
    scene = moveit_commander.PlanningSceneInterface()
    left_arm = moveit_commander.MoveGroupCommander('left_arm')
    left_arm.set_planner_id('RRTConnectkConfigDefault')
    left_arm.set_planning_time(10)

    #Calibrate the end effector on the left arm
    left_gripper = baxter_gripper.Gripper('left')
    print('Calibrating...')
    left_gripper.calibrate()
    rospy.sleep(2.0)
    print('Ready to go')

    #make subscriber to position topic
    rospy.Subscriber('new_position', Pose, move_arm)

    #make subscriber to gripper topic
    rospy.Subscriber('gripper_control', Bool, actuate_gripper)

    rospy.spin()

if __name__ == '__main__':
    main()


text:
 Package	 object-lens

 Description	 ACL-like filtering of objects

 Node Version	 >= 0.10

## Usage
## Install

```
npm install object-lens --save
```

## Example

```js
var filter = require('object-lens');

var schema = {
  name: ['public', 'admin'],
  lastName: ['admin']
};

var data = {
  name: 'Todd',
  lastName: 'Johnson'
};

// Filtering a single piece of data
filter(schema, ['public'], data); // {name: 'Todd'}

// Filtering an array of data
var mapFn = filter.bind(null, schema, ['public']);
var filtered = [data, data].map(mapFn); // [{name: 'Todd'}, {name: 'Todd'}]
```

## LICENSE
(MIT License)

Copyright (c) 2015 Contra [contra@maricopa.edu](mailto:contra@maricopa.edu)

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.

[gittip-url]: https://www.gittip.com/contra/
[gittip-image]: http://img.shields.io/gittip/contra.svg
[downloads-image]: http://img.shields.io/npm/dm/object-lens.svg
[npm-url]: https://npmjs.org/package/object-lens
[npm-image]: http://img.shields.io/npm/v/object-lens.svg
[travis-url]: https://travis-ci.org/contra/object-lens
[travis-image]: https://travis-ci.org/contra/object-lens.png?branch=master
[coveralls-url]: https://coveralls.io/r/contra/object-lens
[coveralls-image]: https://coveralls.io/repos/contra/object-lens/badge.png
[depstat-url]: https://david-dm.org/contra/object-lens
[depstat-image]: https://david-dm.org/contra/object-lens.png
[david-url]: https://david-dm.org/contra/object-lens
[david-image]: https://david-dm.org/contra/object-lens.png?theme=shields.io