text:
import {Http, Response,Headers} from '@angular/http';
import {Injectable} from '@angular/core';
import {Observable, Subject} from 'rxjs/Rx';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import { URL_API } from '../entities/constants';

/**
 * Clase servicio de habilidad
 * que se conecta con el api.
 */
@Injectable()
export class HabilidadService{

    baseUrl = URL_API + "/habilidad/";

    constructor(
        private http:Http
    ){}

    /**
	 * Trae todas las habilidades personales
     * existentes
	 * @param String carrera
	 * @return Lista con las habilidades.
	 */
    getHabilidades(carrera:string){
        let url = this.baseUrl + `getHabilidades?carrera=${carrera}`;
        return this.http.get(url)
            .map((res: Response) => {
                return res.json();
            });
    }

    /**
	 * Trae todas las habilidades
     * profesionales asociadas a un carrera
	 * @param String carrera
	 * @return Lista con las habilidades.
	 */
    getHabilidadesProfesionales(carrera:string){
        let url = this.baseUrl + `getHabilidadesProfesionales?carrera=${carrera}`;
        return this.http.get(url)
            .map((res: Response) => {
                return res.json();
            });
    }

    /**
	 * Trae todas las habilidades
	 * @param
	 * @return Lista con las habilidades.
	 */
    getAll(){
        let url = this.baseUrl + "getAll";
        return this.http.get(url)
            .map((res: Response) => {
                if(res.status == 204)
                    return [];
                return res.json();
            });
    }

    /**
	 * Actualiza datos de una habilidad
	 * @param Habilidad habilidad
	 * @return true o false según el éxito de la operación.
	 */
    actualizar(habilidad) {
       let header = new Headers();
        header.append('Authorization', localStorage.getItem('token'));
        return this.http.patch(this.baseUrl, habilidad, {
            headers: header
        })
            .map((res: Response) => {
                if (res.status == 200)
                    return 'ok';
                throw Error('Error: ' + res.status);
            }).catch((err: Response) => {
                if (err.status == 401)
                    throw new Error(err.status.toString());
                throw Error(err.toString());
            });
    }

    /**
	 * Crea una habilidad
	 * @param Habilidad habilidad
	 * @return true o false según el éxito de la operación.
	 */
    crear(habilidad) {
        let header = new Headers();
        header.append('Authorization', localStorage.getItem('token'));
        let url = this.baseUrl+"create";
        return this.http.post(url, habilidad, {
            headers: header
        })
            .map((res: Response) => {
                if (res.status == 200)
                    return 'ok';
                throw Error('Error: ' + res.status);
            }).catch((err: Response) => {
                if (err.status == 401)
                    throw new Error(err.status.toString());
                throw Error(err.toString());
            });
    }

    /**
	 * Elimina una habilidad
	 * @param Habilidad habilidad
	 * @return true o false según el éxito de la operación.
	 */
    eliminar(habilidad){
        let header = new Headers();
        header.append('Authorization', localStorage.getItem('token'));
        let url = this.baseUrl+"delete";
        return this.http.post(url, habilidad.id, {
            headers: header
        })
            .map((res: Response) => {
                if (res.status == 200)
                    return 'ok';
                throw Error('Error: ' + res.status);
            }).catch((err: Response) => {
                if (err.status == 401)
                    throw new Error(err.status.toString());
                throw Error(err.toString());
            });
    }

}


text:
RLooking is an official iOS client for students in RENAI College of Tianjin University.

# Requirements
+ iOS 7.0+
+ Xcode 6.1
+ CocoaPods 0.35.0

For more information about CocoaPods, see [CocoaPods.org](http://cocoapods.org).

# How to start

	git clone https://github.com/Madimo/RLooking.git
	cd RLooking
	pod install

and use `RLooking.xcworkspace` instead of `RLooking.xcodeproj`.

# License
RLooking is released under the MIT license, see [LICENSE](https://github.com/Madimo/RLooking/blob/master/LICENSE) for details.

redpajama_set_name: RedPajamaGithub


text:
package org.zaproxy.zap.view;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableModel;
import org.parosproxy.paros.Constant;

/**
 *
 * @author yhawke (2014)
 * @param <E>
 */
public abstract class AbstractMultipleOptionsBaseTablePanel<E> extends MultipleOptionsTablePanel {

    protected static final long serialVersionUID = -7609757285865562636L;

    protected static final String ADD_BUTTON_LABEL = Constant.messages.getString("multiple.options.panel.add.button.label");
    protected static final String MODIFY_BUTTON_LABEL = Constant.messages.getString("multiple.options.panel.modify.button.label");
    protected static final String REMOVE_BUTTON_LABEL = Constant.messages.getString("multiple.options.panel.remove.button.label");
    protected static final String REMOVE_WO_CONFIRMATION_CHECKBOX_LABEL = Constant.messages.getString("multiple.options.panel.removeWithoutConfirmation.checkbox.label");

    protected JButton addButton;
    protected JButton modifyButton;
    protected JButton removeButton;

    protected AbstractMultipleOptionsBaseTableModel<E> model;
    protected GridBagConstraints gbcFooterPanel;
    protected JCheckBox removeWithoutConfirmationCheckBox;

    public AbstractMultipleOptionsBaseTablePanel(AbstractMultipleOptionsBaseTableModel<E> model) {
        this(model, true);
    }

    protected AbstractMultipleOptionsBaseTablePanel(AbstractMultipleOptionsBaseTableModel<E> model, boolean allowModification) {
        super(model);

        getFooterPanel().setLayout(new GridBagLayout());

        gbcFooterPanel = new GridBagConstraints();
        gbcFooterPanel.gridx = 0;
        gbcFooterPanel.weightx = 1.0D;
        gbcFooterPanel.weighty = 1.0D;
        gbcFooterPanel.anchor = GridBagConstraints.LINE_START;

        addFooterPanelComponent(getRemoveWithoutConfirmationCheckBox());

        this.model = model;

        addButton = new JButton(ADD_BUTTON_LABEL);
        addButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent evt) {
                E e = showAddDialogue();

                if (e != null) {
                    getMultipleOptionsModel().addElement(e);
                }
            }
        });

        if (allowModification) {
            modifyButton = new JButton(MODIFY_BUTTON_LABEL);
            modifyButton.setEnabled(false);
            modifyButton.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent evt) {
                    int row = getSelectedRow();

                    E e = showModifyDialogue(getMultipleOptionsModel().getElement(row));
                    if (e != null) {
                        getMultipleOptionsModel().modifyElement(row, e);
                    }
                }
            });
        }

        removeButton = new JButton(REMOVE_BUTTON_LABEL);
        removeButton.setEnabled(false);
        removeButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent evt) {
                int row = getSelectedRow();

                if (!isRemoveWithoutConfirmation()) {
                    if (!showRemoveDialogue(getMultipleOptionsModel().getElement(row))) {
                        return;
                    }
                }

                getMultipleOptionsModel().removeElement(row);
            }
        });

        addButton(addButton);
        if (allowModification) {
            addButton(modifyButton);
        }
        addButton(removeButton);

        getTable().getSelectionModel().addListSelectionListener(new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    selectionChanged(getTable().getSelectionModel().getMinSelectionIndex() >= 0);
                }
            }
        });
    }

    protected void selectionChanged(boolean entrySelected) {
        if (modifyButton != null) {
            modifyButton.setEnabled(entrySelected);
        }
        removeButton.setEnabled(entrySelected);
    }

    public AbstractMultipleOptionsBaseTablePanel(TableModel model) {
        super(model);
    }

    /**
     * {@inheritDoc}
     * <p>
     * Overridden to also enable/disable the added buttons ("add", "modify", "remove" and "remove without confirmation").
     * </p>
     */
    @Override
    public void setComponentEnabled(boolean enabled) {
        super.setComponentEnabled(enabled);

        addButton.setEnabled(enabled);
        removeWithoutConfirmationCheckBox.setEnabled(enabled);

        boolean enable = enabled && getTable().getSelectionModel().getMinSelectionIndex() >= 0;
        if (modifyButton != null) {
            modifyButton.setEnabled(enable);
        }
        removeButton.setEnabled(enable);
    }

    public final void addFooterPanelComponent(JComponent component) {
        getFooterPanel().add(component, gbcFooterPanel);
    }

    public boolean isRemoveWithoutConfirmation() {
        return getRemoveWithoutConfirmationCheckBox().isSelected();
    }

    public void setRemoveWithoutConfirmation(boolean enabled) {
        getRemoveWithoutConfirmationCheckBox().setSelected(enabled);
    }

    protected String getRemoveWithoutConfirmationLabel() {
        return REMOVE_WO_CONFIRMATION_CHECKBOX_LABEL;
    }

    protected final JCheckBox getRemoveWithoutConfirmationCheckBox() {
        if (removeWithoutConfirmationCheckBox == null) {
            removeWithoutConfirmationCheckBox = new JCheckBox(getRemoveWithoutConfirmationLabel());
        }
        return removeWithoutConfirmationCheckBox;
    }

    protected int getSelectedRow() {
        int selectedRow = getTable().getSelectionModel().getMinSelectionIndex();
        if (selectedRow == -1) {
            return -1;
        }
        return getTable().convertRowIndexToModel(selectedRow);
    }

    protected AbstractMultipleOptionsBaseTableModel<E> getMultipleOptionsModel() {
        return model;
    }

    public abstract E showAddDialogue();

    public abstract E showModifyDialogue(E e);

    public abstract boolean showRemoveDialogue(E e);
}


text:
package com.gmarciani.ssp.model;

import java.util.Objects;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SumSolution implements Comparable<SumSolution> {

	private float sumA;
	private float sumB;

	public SumSolution(final float sumA, final float sumB) {
		this.sumA = sumA;
		this.sumB = sumB;
	}

	public float getA() {
		return this.sumA;
	}

	public float getB() {
		return this.sumB;
	}

	public static boolean isDominated(final SumSolution sum, final Set<SumSolution> sums) {
		for (SumSolution other_sum : sums) {
			if (sum.equals(other_sum))
				continue;
			if (sum.getA() == other_sum.getA() && sum.getB() < other_sum.getB())
				return true;
			if (sum.getB() == other_sum.getB() && sum.getA() < other_sum.getA())
				return true;
		}

		return false;
	}

	public static SumSolution parse(final String str) {
		final String regex = "\\{(\\d+),(\\d+)\\}";

		Pattern ptrn = Pattern.compile(regex);
		Matcher mtcr = ptrn.matcher(str);
		mtcr.find();

		int sumA = Integer.valueOf(mtcr.group(1));
		int sumB = Integer.valueOf(mtcr.group(2));

		return new SumSolution(sumA, sumB);
	}

	@Override
	public int compareTo(SumSolution other) {
		if (this.getA() > other.getA())
			return 1;
		else if (this.getA() < other.getA())
			return -1;
		else
			return Double.compare(this.getB(), other.getB());
	}

	@Override
	public boolean equals(Object obj) {
		if (this.getClass() != obj.getClass())
			return false;
		SumSolution other = (SumSolution) obj;
		return this.getA() == other.getA() && this.getB() == other.getB();
	}

	@Override
	public int hashCode() {
		return Objects.hash(this.getA(), this.getB());
	}

	@Override
	public String toString() {
		return "{" + this.sumA + "," + this.sumB + "}";
	}

}


text:
<?php
?>

Введите сумму на которую вы хотите пополнить счет

<form id="payment" name="payment" method="post" action="https://sci.interkassa.com/" enctype="utf-8">
    <input type="text" id="interkassa-money" class="form-control" name="interkassa-money">
    <input type="hidden" name="ik_co_id" value="55a65e6e3b1eafa94b8b456a"/>
    <input type="hidden" name="ik_pm_no" value="<?= $cash_id; ?>"/>
    <input id='ik_am' type="hidden" name="ik_am" value=""/>
    <input type="hidden" name="ik_cur" value="RUB"/>
    <input type="hidden" name="ik_desc" value="Пополнить счет"/>
    <input type="submit" class="btn btn-success btn-sm" value="Пополнить">
</form>


text:
var gulp = require('gulp');
var mocha = require('gulp-mocha');

gulp.task('test', function () {
  return gulp.src('test/*.js', {read: false})
    .pipe(mocha({reporter: 'spec'}));
});


text:
/*jshint bitwise: false, asi: true, maxlen: 72, indent: 2*/
/**
 * bmAuth - BitMask Authorization (v0.1.0)
 * https://github.com/lcsd/bitmask-auth
 * https://en.wikipedia.org/wiki/bitmask
 *
 * bmAuth uses bitmasks for up to 32 named roles
 *
 * Four predefined roles ('admin,user,oper,edit')
 * Up to 28 more user roles may be defined by application
 * Roles are cumulative (ex: roles for a tech blog)
 *	user:  user is authenticated
 * 	admin: user has administrator rights
 *	oper:  user can comment or edit data
 *	edit:  user can edit or publish
 *	other roles: define sections for restricted access
 *
 * User Roles define RIGHTS | Access Roles set RESTRICTIONS
 *
 * Roles are defined by an array or comma delimited list of items
 *		ex: roles_str = 'user, edit' <=> roles_msk = 2+8 = 10
 *		ex: roles_arr = ['user','edit']   <=>  roles_msk = 10
 * Masks are bitsets representation of roles
 * 		ex: bmAuth.toMask('user,edit') => 10
 * 		ex: bmAuth.toString(10) => 'user,edit'
 * 		ex: bmAuth.toArray(10) => ['user','edit']
 *
 * Usage:
 * 1) Call bmAuth.config(usrRoles) to setup aditional user roles
 * 2) bmAuth supports conversion between Roles representations
 *        (roles_str <=> roles_arr <=> roles_mskMask)
 *
 * 3) usrMask: mask of Roles the User HAS (rights)
 * 4) accMask: mask of roles the User MUST HAVE (restrictions)
 *
 * 5) Granted access if (accMask & usrMask === accMask)
 *
 * Copyright 2015  Luiz Domingues
 * Released under the MIT license
 */
//
(function (factory) {
	if (typeof exports === 'undefined') {
		factory(this.bmAuth = {}) // Browser global (bmAuth)
	} else {
		factory(module.exports)		// Node require(./bitmask-auth)
	}
}(function ($) {
	var
		sysroles	= ['admin', 'user', 'oper', 'edit'],
		usrroles	= [],						// user defined roles (max 28)
		maxuroles = 32 - sysroles.length,
		allroles	= sysroles;			// default roles definition array
	//
	$.ALLMASK		= -1;
	$.PUBMASK		= 0;
	$.ADMMASK		= 1;
	$.USRMASK		= 2;
	$.SYSMASK		= Math.pow(2, sysroles.length) - 1;
	$.USRMASK		= ~$.SYSMASK;
	/**
	 * config user roles
	 * @param {Array|String} uroles User defined roles (array or list)
	 */
	$.config		= function(uroles) {
		if (Array.isArray(uroles)) {
			usrroles	= uroles
		} else if (typeof(uroles) === 'string') {
			uroles = uroles.replace(/\s/g, '') 		// remove spaces
			usrroles	= uroles.split(',')
		} else { usrroles = [] }
		if (usrroles.length > maxuroles) {
			usrroles.splice(maxuroles, Number.MAX_VALUE)
		}
		allroles = sysroles.concat(usrroles)
    return allroles
	}
	/**
	 * mask to array of roles
	 * @param   {Number} mask   roles bitset mask
	 * @param   {Array}  roles  roles definition array
	 * @returns {Array}  array  representation of mask
	 */
	$.toArray  = function(mask, roles) {
		mask = parseInt(mask) || 0;
		if (!mask) { return [] }
    if (!Array.isArray(roles)) { roles = allroles }
		var imask = 1, maskArr = [];
		for (var i = 0, n = roles.length; i < n; i++) {
			if (imask & mask) { maskArr.push(roles[i]) }
			imask = imask << 1
		}
		return maskArr
	}
	/**
	 * mask to string list of roles
	 * @param   {Number} mask roles bitset representation
	 * @param   {Array}  roles  roles definition array
	 * @returns {String} string list representation of roles
	 */
	$.toString = function(mask, roles) {
		return $.toArray(mask, roles).toString()
	}
	/**
	 * roles list or array to mask
	 * @param   {String|Array}  maskPrm  array or list of roles
	 * @param   {Array}  roles  roles definition array
	 * @returns {Number}	      bitmask representation of roles
	 */
	$.toMask   = function(maskPrm, roles) {
		if (typeof(maskPrm) === 'string') {
			maskPrm = maskPrm.split(',') 		// string list to array
		}
		if (!Array.isArray(maskPrm)) { return 0 }
    if (!Array.isArray(roles)) { roles = allroles }
		var mask = 0, imask = 1;
		for (var i = 0, n = roles.length; i < n; i++) {
			if (maskPrm.indexOf(roles[i]) !== -1) {
				mask = mask | imask
			}
			imask = imask << 1
		}
		return mask
	}
}))


text:
ig.module(
    'game.entities.misc.killblock'
    )
.requires(
    'impact.entity',
    'game.entities.player'
)
.defines(function(){
    EntityKillblock = ig.Entity.extend({

	health: 10000000,
    // The following properties tell Weltmeister how
    // to render the object inside the edit view.
    // The following draws a blue 8x8 box.
    _wmScalable: true,
    _wmDrawBox: true,
    _wmBoxColor: 'rgba(0,0,255,0.7)',
    size: {x: 8, y: 8},

    type: ig.Entity.TYPE.B,
    checkAgainst: ig.Entity.TYPE.BOTH,
    collides: ig.Entity.COLLIDES.ACTIVE,

	update: function(){ },

    collideWith: function(other) {
    	other.kill();
    },

    check: function( other ) {
        if(other instanceof EntityPlayer || other instanceof EntityArcher){
            other.receiveDamage( 30, this );
        }

    },

    kill: function(){
        this.parent();
    },

    });
});


text:
(function(exports) {

  // Construct-o-rama.
  function Task() {
    // Helpers.
    this._helpers = {};
    // Tasks.
    this._tasks = {};
    // Task queue.
    this._queue = [];
    // Queue placeholder (for dealing with nested tasks).
    this._placeholder = {};
    // Options.
    this._options = {};
    // Is the queue running?
    this._running = false;
    // Success status of completed tasks.
    this._success = {};
  }

  // Expose the constructor function.
  exports.Task = Task;

  // Create a new Task instance.
  exports.create = function() {
    return new Task();
  };

  // Error constructors.
  function TaskError(message) {
    this.name = 'TaskError';
    this.message = message;
  }
  TaskError.prototype = new Error();

  function HelperError(message) {
    this.name = 'HelperError';
    this.message = message;
  }
  HelperError.prototype = new Error();

  // Expose the ability to create a new taskError.
  Task.prototype.taskError = function(message, e) {
    var error = new TaskError(message);
    error.origError = e;
    return error;
  };

  // Register a new helper.
  Task.prototype.registerHelper = function(name, fn) {
    // Add task into cache.
    this._helpers[name] = fn;
    // Make chainable!
    return this;
  };

  // Rename a helper. This might be useful if you want to override the default
  // behavior of a helper, while retaining the old name (to avoid having to
  // completely recreate an already-made task just because you needed to
  // override or extend a built-in helper).
  Task.prototype.renameHelper = function(oldname, newname) {
    // Rename helper.
    this._helpers[newname] = this._helpers[oldname];
    // Remove old name.
    delete this._helpers[oldname];
    // Make chainable!
    return this;
  };

  // If the task runner is running or an error handler is not defined, throw
  // an exception. Otherwise, call the error handler directly.
  Task.prototype._throwIfRunning = function(obj) {
    if (this._running || !this._options.error) {
      // Throw an exception that the task runner will catch.
      throw obj;
    } else {
      // Not inside the task runner. Call the error handler and abort.
      this._options.error.call({name: null}, obj);
    }
  };

  // Execute a helper.
  Task.prototype.helper = function(name) {
    var helper = this._helpers[name];
    if (!helper) {
      // Helper not found.
      this._throwIfRunning(new HelperError('Helper "' + name + '" not found.'));
    } else {
      // Helper found. Invoke it with any remaining arguments and return its
      // value.
      return helper.apply(this, [].slice.call(arguments, 1));
    }
  };

  // If a <foo:bar:baz> directive is passed, return ["foo", "bar", "baz"],
  // otherwise null.
  var directiveRe = /^<(.*)>$/;
  Task.prototype.getDirectiveParts = function(str) {
    var matches = str.match(directiveRe);
    // If the string doesn't look like a directive, return null.
    if (!matches) { return null; }
    // Split the name into parts.
    var parts = matches[1].split(':');
    // If a matching helper was found, return the parts, otherwise null.
    return this._helpers[parts[0]] ? parts : null;
  };

  // If value matches the <handler:arg1:arg2> format, and the specified handler
  // exists, it's a directive. Execute the matching handler and return its
  // value. If not, but an optional callback was passed, pass the value into
  // the callback and return its result. If no callback was specified, return
  // the value.
  Task.prototype.directive = function(value, fn) {
    // Get parts if a string was passed and it looks like a directive.
    var directive = typeof value === 'string' ? this.getDirectiveParts(value) : null;

    if (directive) {
      // If it looks like a directive and a matching helper exists, call the
      // helper by applying all directive parts and return its value.
      return this.helper.apply(this, directive);
    } else if (fn) {
      // Not a directive, but a callback was passed. Pass the value into the
      // callback and return its result.
      return fn(value);
    }
    // A callback wasn't specified or a valid handler wasn't found, so just
    // return the value.
    return value;
  };

  // Register a new task.
  Task.prototype.registerTask = function(name, info, fn) {
    // If optional "info" string is omitted, shuffle arguments a bit.
    if (fn == null) {
      fn = info;
      info = '';
    }
    // String or array of strings was passed instead of fn.
    var tasks;
    if (typeof fn !== 'function') {
      // Array of task names.
      tasks = this.parseArgs([fn]);
      // This task function just runs the specified tasks.
      fn = this.run.bind(this, fn);
      fn.alias = true;
      // Generate an info string if one wasn't explicitly passed.
      if (!info) {
        info = 'Alias for "' + tasks.join(' ') + '" task' +
          (tasks.length === 1 ? '' : 's') + '.';
      }
    }
    // Add task into cache.
    this._tasks[name] = {name: name, info: info, fn: fn};
    // Make chainable!
    return this;
  };

  // Is the specified task an alias?
  Task.prototype.isTaskAlias = function(name) {
    return !!this._tasks[name].fn.alias;
  };

  // Rename a task. This might be useful if you want to override the default
  // behavior of a task, while retaining the old name. This is a billion times
  // easier to implement than some kind of in-task "super" functionality.
  Task.prototype.renameTask = function(oldname, newname) {
    // Rename helper.
    this._tasks[newname] = this._tasks[oldname];
    // Update name property of task.
    this._tasks[newname].name = newname;
    // Remove old name.
    delete this._tasks[oldname];
    // Make chainable!
    return this;
  };

  // Argument parsing helper. Supports these signatures:
  //  fn('foo')                 // ['foo']
  //  fn('foo bar baz')         // ['foo', 'bar', 'baz']
  //  fn('foo', 'bar', 'baz')   // ['foo', 'bar', 'baz']
  //  fn(['foo', 'bar', 'baz']) // ['foo', 'bar', 'baz']
  Task.prototype.parseArgs = function(_arguments) {
    // If there are multiple (or zero) arguments, convert the _arguments object
    // into an array and return that.
    return _arguments.length !== 1 ? [].slice.call(_arguments) :
      // Return the first argument if it's an Array.
      _arguments[0] instanceof Array ? _arguments[0] :
      // Split the first argument on space.
      typeof _arguments[0] === 'string' ? _arguments[0].split(/\s+/) :
      // Just return an array containing the first argument. (todo: deprecate)
      [_arguments[0]];
  };

  // Given a task name, determine which actual task will be called, and what
  // arguments will be passed into the task callback. "foo" -> task "foo", no
  // args. "foo:bar:baz" -> task "foo:bar:baz" with no args (if "foo:bar:baz"
  // task exists), otherwise task "foo:bar" with arg "baz" (if "foo:bar" task
  // exists), otherwise task "foo" with args "bar" and "baz".
  Task.prototype._taskPlusArgs = function(name) {
    // Task name / argument parts.
    var parts = name.split(':');
    // Start from the end, not the beginning!
    var i = parts.length;
    var task;
    do {
      // Get a task.
      task = this._tasks[parts.slice(0, i).join(':')];
      // If the task doesn't exist, decrement `i`, and if `i` is greater than
      // 0, repeat.
    } while (!task && --i > 0);
    // The task to run and the args to run it with.
    return {nameArgs: name, task: task, args: parts.slice(i)};
  };

  // Enqueue a task.
  Task.prototype.run = function() {
    // Parse arguments into an array, returning an array of task+args objects.
    var things = this.parseArgs(arguments).map(this._taskPlusArgs.bind(this));
    // Throw an exception if any tasks weren't found.
    var fails = things.filter(function(thing) { return !thing.task; });
    if (fails.length > 0) {
      this._throwIfRunning(new TaskError('Task "' + fails[0].nameArgs + '" not found.'));
      return this;
    }
    // Get current placeholder index.
    var index = this._queue.indexOf(this._placeholder);
    if (index === -1) {
      // No placeholder, add task+args objects to end of queue.
      this._queue = this._queue.concat(things);
    } else {
      // Placeholder exists, add task+args objects just before placeholder.
      [].splice.apply(this._queue, [index, 0].concat(things));
    }
    // Make chainable!
    return this;
  };

  // Begin task queue processing. Ie. run all tasks.
  Task.prototype.start = function() {
    // Abort if already running.
    if (this._running) { return false; }
    // Actually process the next task.
    var nextTask = function() {
      // Async flag.
      var async = false;
      // Get next task+args object from queue.
      var thing;
      // Skip any placeholders.
      do { thing = this._queue.shift(); } while (thing === this._placeholder);
      // If queue was empty, we're all done.
      if (!thing) {
        this._running = false;
        if (this._options.done) {
          this._options.done();
        }
        return;
      }
      // Add a placeholder to the front of the queue.
      this._queue.unshift(this._placeholder);
      // Update the internal status object and run the next task.
      var complete = function(status, errorObj) {
        // A task has "failed" only if it returns false (async) or if the
        // function returned by .async is passed false.
        this._success[thing.nameArgs] = status !== false;
        // If task failed, call error handler.
        if (status === false && this._options.error) {
          this._options.error.call({name: thing.task.name, nameArgs: thing.nameArgs}, errorObj ||
            new TaskError('Task "' + thing.nameArgs + '" failed.'));
        }
        // Run the next task.
        nextTask();
      }.bind(this);

      try {
        // Get the current task and run it, setting `this` inside the task
        // function to be something useful.
        var status = thing.task.fn.apply({
          // The current task name plus args, as-passed.
          nameArgs: thing.nameArgs,
          // The current task name.
          name: thing.task.name,
          // When called, sets the async flag and returns a function that can
          // be used to continue processing the queue.
          async: function() {
            async = true;
            return complete;
          }
        }, thing.args);
        // If the async flag wasn't set, process the next task in the queue.
        if (!async) {
          complete(status);
        }
      } catch (e) {
        if (e instanceof TaskError || e instanceof HelperError) {
          complete(false, e);
        } else {
          throw e;
        }
      }
    }.bind(this);
    // Update flag.
    this._running = true;
    // Process the next task.
    nextTask();
  };

  // Clear all remaining tasks from the queue, or a subset.
  Task.prototype.clearQueue = function() {
    this._queue = [];
    // Make chainable!
    return this;
  };

  // Test to see if all of the given tasks have succeeded.
  Task.prototype.requires = function() {
    this.parseArgs(arguments).forEach(function(name) {
      var success = this._success[name];
      if (!success) {
        throw new TaskError('Required task "' + name +
          '" ' + (success === false ? 'failed' : 'missing') + '.');
      }
    }.bind(this));
  };

  // Override default options.
  Task.prototype.options = function(options) {
    Object.keys(options).forEach(function(name) {
      this._options[name] = options[name];
    }.bind(this));
  };

}(typeof exports === 'object' && exports || this));


text:
package com.mmall.dao;

import com.mmall.pojo.Category;

import java.util.List;

public interface CategoryMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Category record);

    int insertSelective(Category record);

    Category selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Category record);

    int updateByPrimaryKey(Category record);

    List<Category> selectByParentId(Integer parentId);
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Traveling extends CI_Controller
{
	function __construct()
	{
		parent::__construct();

		$this->header 	= 'template/header';
		$this->footer 	= 'template/footer';

		/*VIEW*/
		$this->content_traveling = 'template/traveling/traveling';
	}

	function index()
	{
		/*if($this->session->userdata('is_logued_in') == true)
		{*/
			$header 					= $this->header;
			$content_traveling 	= $this->content_traveling;
			$footer 					= $this->footer;

			$pages=10;
			$config['base_url'] = base_url()."/traveling/index";
			$config['total_rows'] = $this->traveling_ml->filas_panel_centro();
			$config['per_page'] = $pages;
	        $config['num_links'] = 10;
	 		$config['first_link'] = 'Primera';
			$config['last_link'] = 'Última';
	        $config["uri_segment"] = 3;
			$config['next_link'] = 'Siguiente';
			$config['prev_link'] = 'Anterior';
			$this->pagination->initialize($config);
			$data["pagin"] = $this->traveling_ml->total_paginados_panel_centro($config['per_page'],$this->uri->segment(3));

			$data['listado_panel_centro_sponsors'] = $this->traveling_ml->listado_panel_centro_sponsors();

			$this->load->view($header);
			$this->load->view($content_traveling,$data);
			$this->load->view($footer);

		/*}else{

			$this->session->set_flashdata('login_usuario','Usted no se encuentra logeado');
			redirect('login', 'refresh');
		}*/
	}
}


text:
<?php

namespace Skinny\View;

class Files implements \IteratorAggregate {

    /**
     * Ścieżka do katalogu z plikami tego typu.
     * @var string
     */
    protected $_filesPath;

    /**
     * Rozszerzenie plików tego typu.
     * @var string
     */
    protected $_extension;

    /**
     * Bazowy url aplikacji - potrzebny przy metodzie pobierającej publiczny url pliku.
     * @var string
     */
    protected $_baseUrl;

    /**
     * Ścieżka aplikacji (katalog public)
     * @var string
     */
    protected $_applicationPath;

    /**
     * Tablica asocjacyjna dodanych plików.
     * @var array
     */
    protected $_items = [];

    /**
     * Umożliwia iterowanie bezpośrednio po elementach tablicy $_items.
     *
     * @return ArrayIterator
     */
    public function getIterator() {
        return new \ArrayIterator($this->_items);
    }

    /**
     * Konstruktor kolekcji plików.
     *
     * @param string $baseUrl           Bazowy url aplikacji
     * @param string $applicationPath   Ścieżka publiczna aplikacji
     * @param string $filesPath         Ścieżka do katalogu głównego z plikami
     * @param string $extension         Rozszerzenie plików (np. ".js")
     * @throws Exception
     *
     * @todo Czy należy sprawdzać istnienie ścieżek? applicationPath i/lub filesPAth?
     */
    public function __construct($baseUrl, $applicationPath, $filesPath, $extension) {
        if (!is_string($baseUrl)) {
            throw new Exception('Argument $baseUrl (' . $baseUrl . ') is invalid');
        }
        if (!is_string($applicationPath)) {
            throw new Exception('Argument $applicationPath (' . $applicationPath . ') is invalid');
        }
        if (!is_string($filesPath)) {
            throw new Exception('Argument $path (' . $filesPath . ') is invalid');
        }
        if (!is_string($extension)) {
            throw new Exception('Argument $extension (' . $extension . ') is invalid');
        }

        $this->_baseUrl         = $baseUrl;
        $this->_applicationPath = $applicationPath;
        $this->_filesPath       = $filesPath;
        $this->_extension       = $extension;
    }

    /**
     * Dodaje plik do kolekcji.
     * Plik może być adresem url - wtedy od razu dodawany jest do kolekcji.
     * Może być również ścieżką bezwzględną - wtedy ścieżka tworzona jest od katalogu
     * "public" aplikacji (np. "file" = "/js/file")
     *
     * @param string    $file
     * @param boolean   $requireFileExistance Wymusza sprawdzenie istnienia pliku
     *                                      oraz zrzucenie exceptiona gdy nie istnieje
     * @return \Skinny\View\Files
     * @throws Exception
     */
    public function add($file, $requireFileExistance = true) {
        if (!$this->fileExists(($filePath = $this->_getFilePath($file)))) {
            if ($requireFileExistance) {
                throw new Exception("File '$filePath' doesn't exist.");
            }
        } else {
            $url                = $this->_getFileUrl($file);
            $this->_items[$url] = $url;
        }

        return $this;
    }

    /**
     * Dodaje plik na początku.
     * @param string $file
     * @param voolean $requireFileExistance
     * @return \Skinny\View\Files
     * @throws Exception
     */
    public function addFirst($file, $requireFileExistance = true) {
        if (!$this->fileExists(($filePath = $this->_getFilePath($file)))) {
            if ($requireFileExistance) {
                throw new Exception("File '$filePath' doesn't exist.");
            }
        } else {
            // dodanie elementu na początek tablicy asocjacyjnej
            $url          = $this->_getFileUrl($file);
            $this->_items = [$url => $url] + $this->_items;
        }

        return $this;
    }

    /**
     * Sprawdza istnienie pliku pod podaną ścieżką.
     * UWAGA - w przypadku adresu URL funkcja zwraca TRUE.
     *
     * @param string $filePath
     * @return boolean
     */
    public function fileExists($filePath) {
        if (\Skinny\Url::hasProtocol($filePath)) {
            return true; // TODO ewentualne sprawdzanie istnienia pliku pod adresem URL
        } else {
            return file_exists($filePath);
        }
    }

    /**
     * Konfiguruje i zwraca ścieżkę (względną lub url) do wybranego pliku.
     *
     * @param string $file
     * @return string|false
     */
    protected function _getFilePath($file) {
        if (\Skinny\Url::hasProtocol($file)) {
            return $file;
        } else {
            // jeżeli ścieżka nie jest absolutna to należy do ścieżki dodać
            // na początku lokalizację katalogu z plikami tego typu
            if (!\Skinny\Path::isAbsolute($file)) {
                $file = \Skinny\Path::combine($this->_applicationPath, $this->_filesPath, $file);
            } else {
                // Jeżeli ścieżka jest absolutna należy zwrócić ścieżkę liczoną od
                // katalogu publicznego aplikacji
                $file = $this->_applicationPath . $file;
            }
            // dołączenie odpowiedniego rozszerzenia jeśli nie ustawione
            if (!$this->hasExtensionAlready($file)) {
                $file .= $this->_extension;
            }

            return $file;
        }
    }

    /**
     * Konfiguruje i zwraca url względny pliku lub wartość argumentu $file jeżeli jest URL'em.
     *
     * @param string $file
     * @return string
     */
    protected function _getFileUrl($file) {
        if (\Skinny\Url::hasProtocol($file)) {
            return $file;
        } else {
            // jeżeli nie podano ścieżki bezwzględnej należy ją dokleić
            if (!\Skinny\Path::isAbsolute($file)) {
                $file = \Skinny\Path::combine($this->_baseUrl, $this->_filesPath, $file);
            }

            // dołączenie odpowiedniego rozszerzenia jeśli nie ustawione
            if (!$this->hasExtensionAlready($file)) {
                $file .= $this->_extension;
            }

            return $file;
        }
    }

    /**
     * Usuwa wybrany plik z kolekcji.
     *
     * @param string $file
     * @return \Skinny\View\Files
     */
    public function remove($file) {
        $url = $this->_getFileUrl($file);
        if (isset($this->_items[$url])) {
            unset($this->_items[$url]);
        }
        return $this;
    }

    /**
     * Sprawdza czy podana nazwa pliku ma już w sobie żądane rozszerzenie.
     * @param string $file
     * @return boolean
     */
    public function hasExtensionAlready($file) {
        return false !== strrpos($file, $this->_extension);
    }

    public function clear() {
        $this->_items = [];
    }

}


text:
<?php

class Google_Service_RemoteBuildExecution_GoogleDevtoolsRemoteexecutionV1testExecuteOperationMetadata extends Google_Model
{
  protected $actionDigestType = 'Google_Service_RemoteBuildExecution_GoogleDevtoolsRemoteexecutionV1testDigest';
  protected $actionDigestDataType = '';
  public $stage;
  public $stderrStreamName;
  public $stdoutStreamName;

  /**
   * @param Google_Service_RemoteBuildExecution_GoogleDevtoolsRemoteexecutionV1testDigest
   */
  public function setActionDigest(Google_Service_RemoteBuildExecution_GoogleDevtoolsRemoteexecutionV1testDigest $actionDigest)
  {
    $this->actionDigest = $actionDigest;
  }
  /**
   * @return Google_Service_RemoteBuildExecution_GoogleDevtoolsRemoteexecutionV1testDigest
   */
  public function getActionDigest()
  {
    return $this->actionDigest;
  }
  public function setStage($stage)
  {
    $this->stage = $stage;
  }
  public function getStage()
  {
    return $this->stage;
  }
  public function setStderrStreamName($stderrStreamName)
  {
    $this->stderrStreamName = $stderrStreamName;
  }
  public function getStderrStreamName()
  {
    return $this->stderrStreamName;
  }
  public function setStdoutStreamName($stdoutStreamName)
  {
    $this->stdoutStreamName = $stdoutStreamName;
  }
  public function getStdoutStreamName()
  {
    return $this->stdoutStreamName;
  }
}


text:
/* ========================================
 * CORS Planner - App Main
 *
 * Load all app components required
 *
 * Author: Wang Zhuochun
 * Last Edit: 16/Jul/2013 12:25 AM
 * ========================================
 * <License>
 * ======================================== */

define(function(require, exports) {

    "use strict";
    /*jshint jquery:true, laxcomma:true, maxerr:50*/
    /*globals planner*/

    var store = require("util/store")
      , reserved = ["key", "user", "status"];

    // expose a planner variable in global namespace
    //
    // Taken from: (in case window is not the point to the global object)
    //   http://stackoverflow.com/questions/3277182/how-to-get-the-global-object-in-javascript
    (function _initGlobalPlanner() {
        var Fn = Function, global = (new Fn("return this"))();
        // declare global
        if (!global.planner) {
            global.planner = {};
        }

        // assign CORS Planner Version number
        planner.version = "0.8.0";
        // CORS Planner for schools
        planner.school = store.get("app:school") || null;
        // default module lists
        planner.list = {
            modules  : "modules"
          , previews : "previews"
        };
        // week days
        planner.weekDays = ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"];
        // enable or disable popover on slot
        planner.slotPopover = store.get("app:slotPopover") || true;
        // slot type, e.g. location, week, group
        planner.slotType = store.get("app:slotType") || "location";

        // planner set and get
        planner.get = function(key) { return this[key]; };
        planner.set = function(key, val) {
            if ($.inArray(key, reserved) === -1) {
                this[key] = val;
                // save to localStorage
                store.set("app:" + key, val);
                // publish it
                $.publish("app:" + key, [val]);
            }
        };
        // load css
        planner.loadCss = function(href) {
            var link = document.createElement("link");
            link.type = "text/css";
            link.rel = "stylesheet";
            link.href = href;
            document.getElementsByTagName("head")[0].appendChild(link);
            planner.trackEvent("load-css", href);
        };
        // track usages and events using google analytics
        // https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide
        planner.analytics = function() {
            if (global._gaq) {
                global._gaq.push($.makeArray(arguments));
            }
        };
        // some help functions
        planner.trackEvent = function(category, action) {
            planner.analytics("_trackEvent", category, action, planner.school);
        };
        planner.trackPageView = function(url, prefix) {
            planner.analytics("_trackPageview", prefix ? prefix + "=" + url : url);
        };

    })();

});


text:
// Copyright 2017 Secure Decisions, a division of Applied Visions, Inc.
// 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.
//
// This material is based on research sponsored by the Department of Homeland
// Security (DHS) Science and Technology Directorate, Cyber Security Division
// (DHS S&T/CSD) via contract number HHSP233201600058C.

using System;
using System.IO;
using System.Text;

namespace CodePulse.Client.Util
{
    public static class BinaryWriterExtensions
    {
        public static void FlushAndLog(this BinaryWriter writer, string description)
        {
            writer.Flush();
        }

        public static void WriteBigEndian(this BinaryWriter writer, int value)
        {
            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer), "Expected non-null BinaryWriter");
            }

            if (!BitConverter.IsLittleEndian)
            {
                writer.Write(value);
                return;
            }
            WriteBytesBigEndian(writer, BitConverter.GetBytes(value));
        }

        public static void WriteBigEndian(this BinaryWriter writer, long value)
        {
            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer), "Expected non-null BinaryWriter");
            }

            if (!BitConverter.IsLittleEndian)
            {
                writer.Write(value);
                return;
            }
            WriteBytesBigEndian(writer, BitConverter.GetBytes(value));
        }

        public static void WriteUtfBigEndian(this BinaryWriter writer, string value)
        {
            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer), "Expected non-null BinaryWriter");
            }

            var bytes = Encoding.UTF8.GetBytes(value);

            writer.WriteBigEndian(Convert.ToInt16(bytes.Length));
            writer.Write(bytes);
        }

        public static void WriteBigEndian(this BinaryWriter writer, short value)
        {
            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer), "Expected non-null BinaryWriter");
            }

            if (!BitConverter.IsLittleEndian)
            {
                writer.Write(value);
                return;
            }
            WriteBytesBigEndian(writer, BitConverter.GetBytes(value));
        }

        public static void WriteBigEndian(this BinaryWriter writer, ushort value)
        {
            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer), "Expected non-null BinaryWriter");
            }

            if (!BitConverter.IsLittleEndian)
            {
                writer.Write(value);
                return;
            }
            WriteBytesBigEndian(writer, BitConverter.GetBytes(value));
        }

        private static void WriteBytesBigEndian(BinaryWriter writer, byte[] bytes)
        {
            Array.Reverse(bytes);
            writer.Write(bytes);
        }
    }
}


text:
function s = char(tpl)
%TEMPLATE Convert a template object in a one line description string
%  S = CHAR(TPL) is a class convertor from Template to a string, used
%  in online display.
%
%  See also DISPLAY

%  Copyright (C) 2003 Guillaume Flandin <Guillaume@artefact.tk>
%  $Revision: 1.0 $Date: 2003/05/05 22:19:51 $

s = ['Template Object: root ''',...
		tpl.root,''', ',...
		num2str(length(tpl.file)), ' files, ',...
		num2str(length(tpl.varkeys)), ' keys, ',...
		tpl.unknowns, ' unknowns.'];


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycotaxon 78: 251 (2001)

#### Original name
Tyromyces mexicanus Ryvarden & Guzmán, 2001

### Remarks
null


text:
NSString * const kYelpConsumerKey = @"vxKwwcR_NMQ7WaEiQBK_CA";
NSString * const kYelpConsumerSecret = @"33QCvh5bIF5jIHR5klQr7RtBDhQ";
NSString * const kYelpToken = @"uRcRswHFYa1VkDrGV6LAW2F8clGh5JHV";
NSString * const kYelpTokenSecret = @"mqtKIxMIR4iBtBPZCmCLEb-Dz3Y";

@interface ViewController () <UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) YelpClient *client;
@property (nonatomic, strong) NSArray *businesses;

@end

@implementation ViewController

- (void)loadPlaces
{
    self.client = [[YelpClient alloc] initWithConsumerKey:kYelpConsumerKey consumerSecret:kYelpConsumerSecret accessToken:kYelpToken accessSecret:kYelpTokenSecret];

    [self.client searchWithTerm:@"Thai" success:^(AFHTTPRequestOperation *operation, id response) {
        NSLog(@"response: %@", response);
        NSArray *businessDictionaries = response[@"businesses"];

        self.businesses = [Business businessesWithDictionaries:businessDictionaries];

        [self.tableView reloadData];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error: %@", [error description]);
    }];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.tableView.delegate = self;
    self.tableView.dataSource = self;

    [self.tableView registerNib:[UINib nibWithNibName:@"BusinessCell" bundle:nil] forCellReuseIdentifier:@"BusinessCell"];
    self.tableView.estimatedRowHeight = 100;
    self.tableView.rowHeight = UITableViewAutomaticDimension;

    self.title = @"Yelp";

    [self loadPlaces];
}

#pragma mark - Table view methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.businesses.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BusinessCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BusinessCell"];
    cell.business = self.businesses[indexPath.row];
    return cell;
}
@end


text:
"""Support for MQTT sensors."""
from datetime import timedelta
import functools
from typing import Optional

import voluptuous as vol

from homeassistant.components import sensor
from homeassistant.components.sensor import DEVICE_CLASSES_SCHEMA
from homeassistant.const import (
    CONF_DEVICE,
    CONF_DEVICE_CLASS,
    CONF_FORCE_UPDATE,
    CONF_ICON,
    CONF_NAME,
    CONF_UNIQUE_ID,
    CONF_UNIT_OF_MEASUREMENT,
    CONF_VALUE_TEMPLATE,
)
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import async_track_point_in_utc_time
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.typing import ConfigType, HomeAssistantType
from homeassistant.util import dt as dt_util

from . import CONF_QOS, CONF_STATE_TOPIC, DOMAIN, PLATFORMS, subscription
from .. import mqtt
from .debug_info import log_messages
from .mixins import (
    MQTT_AVAILABILITY_SCHEMA,
    MQTT_ENTITY_DEVICE_INFO_SCHEMA,
    MQTT_JSON_ATTRS_SCHEMA,
    MqttAvailability,
    MqttEntity,
    async_setup_entry_helper,
)

CONF_EXPIRE_AFTER = "expire_after"

DEFAULT_NAME = "MQTT Sensor"
DEFAULT_FORCE_UPDATE = False
PLATFORM_SCHEMA = (
    mqtt.MQTT_RO_PLATFORM_SCHEMA.extend(
        {
            vol.Optional(CONF_DEVICE): MQTT_ENTITY_DEVICE_INFO_SCHEMA,
            vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,
            vol.Optional(CONF_EXPIRE_AFTER): cv.positive_int,
            vol.Optional(CONF_FORCE_UPDATE, default=DEFAULT_FORCE_UPDATE): cv.boolean,
            vol.Optional(CONF_ICON): cv.icon,
            vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
            vol.Optional(CONF_UNIQUE_ID): cv.string,
            vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string,
        }
    )
    .extend(MQTT_AVAILABILITY_SCHEMA.schema)
    .extend(MQTT_JSON_ATTRS_SCHEMA.schema)
)

async def async_setup_platform(
    hass: HomeAssistantType, config: ConfigType, async_add_entities, discovery_info=None
):
    """Set up MQTT sensors through configuration.yaml."""
    await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
    await _async_setup_entity(hass, async_add_entities, config)

async def async_setup_entry(hass, config_entry, async_add_entities):
    """Set up MQTT sensors dynamically through MQTT discovery."""
    setup = functools.partial(
        _async_setup_entity, hass, async_add_entities, config_entry=config_entry
    )
    await async_setup_entry_helper(hass, sensor.DOMAIN, setup, PLATFORM_SCHEMA)

async def _async_setup_entity(
    hass, async_add_entities, config: ConfigType, config_entry=None, discovery_data=None
):
    """Set up MQTT sensor."""
    async_add_entities([MqttSensor(hass, config, config_entry, discovery_data)])

class MqttSensor(MqttEntity, Entity):
    """Representation of a sensor that can be updated using MQTT."""

    def __init__(self, hass, config, config_entry, discovery_data):
        """Initialize the sensor."""
        self._state = None
        self._expiration_trigger = None

        expire_after = config.get(CONF_EXPIRE_AFTER)
        if expire_after is not None and expire_after > 0:
            self._expired = True
        else:
            self._expired = None

        MqttEntity.__init__(self, hass, config, config_entry, discovery_data)

    @staticmethod
    def config_schema():
        """Return the config schema."""
        return PLATFORM_SCHEMA

    def _setup_from_config(self, config):
        """(Re)Setup the entity."""
        self._config = config
        template = self._config.get(CONF_VALUE_TEMPLATE)
        if template is not None:
            template.hass = self.hass

    async def _subscribe_topics(self):
        """(Re)Subscribe to topics."""

        @callback
        @log_messages(self.hass, self.entity_id)
        def message_received(msg):
            """Handle new MQTT messages."""
            payload = msg.payload
            # auto-expire enabled?
            expire_after = self._config.get(CONF_EXPIRE_AFTER)
            if expire_after is not None and expire_after > 0:
                # When expire_after is set, and we receive a message, assume device is not expired since it has to be to receive the message
                self._expired = False

                # Reset old trigger
                if self._expiration_trigger:
                    self._expiration_trigger()
                    self._expiration_trigger = None

                # Set new trigger
                expiration_at = dt_util.utcnow() + timedelta(seconds=expire_after)

                self._expiration_trigger = async_track_point_in_utc_time(
                    self.hass, self._value_is_expired, expiration_at
                )

            template = self._config.get(CONF_VALUE_TEMPLATE)
            if template is not None:
                payload = template.async_render_with_possible_json_value(
                    payload, self._state
                )
            self._state = payload
            self.async_write_ha_state()

        self._sub_state = await subscription.async_subscribe_topics(
            self.hass,
            self._sub_state,
            {
                "state_topic": {
                    "topic": self._config[CONF_STATE_TOPIC],
                    "msg_callback": message_received,
                    "qos": self._config[CONF_QOS],
                }
            },
        )

    @callback
    def _value_is_expired(self, *_):
        """Triggered when value is expired."""
        self._expiration_trigger = None
        self._expired = True
        self.async_write_ha_state()

    @property
    def name(self):
        """Return the name of the sensor."""
        return self._config[CONF_NAME]

    @property
    def unit_of_measurement(self):
        """Return the unit this state is expressed in."""
        return self._config.get(CONF_UNIT_OF_MEASUREMENT)

    @property
    def force_update(self):
        """Force update."""
        return self._config[CONF_FORCE_UPDATE]

    @property
    def state(self):
        """Return the state of the entity."""
        return self._state

    @property
    def icon(self):
        """Return the icon."""
        return self._config.get(CONF_ICON)

    @property
    def device_class(self) -> Optional[str]:
        """Return the device class of the sensor."""
        return self._config.get(CONF_DEVICE_CLASS)

    @property
    def available(self) -> bool:
        """Return true if the device is available and value has not expired."""
        expire_after = self._config.get(CONF_EXPIRE_AFTER)
        return MqttAvailability.available.fget(self) and (
            expire_after is None or not self._expired
        )


text:
//-----------------------------------------------------------------------
// <copyright file="ISemantics.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com>
//     Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System;
using Akka.Actor;

namespace Akka.Dispatch
{
    /// <summary>
    ///
    /// </summary>
    public interface ISemantics
    {
    }

    /// <summary>
    /// Semantics for message queues that support multiple consumers
    /// </summary>
    public interface IMultipleConsumerSemantics : ISemantics
    {
    }

    /// <summary>
    /// Semantics for message queues that have an unbounded size
    /// </summary>
    public interface IUnboundedMessageQueueSemantics : ISemantics
    {
    }

    /// <summary>
    /// Semantics for message queues that have a bounded size
    /// </summary>
    public interface IBoundedMessageQueueSemantics : ISemantics
    {
        /// <summary>
        /// The enqueue time to wait until message is dropped to deadletters if the message queue is full
        /// </summary>
        TimeSpan PushTimeOut { get; set; }
    }

    /// <summary>
    /// Semantics for message queues that are blocking
    /// </summary>
    public interface IBlockingMessageQueueSemantics : IMultipleConsumerSemantics
    {
        /// <summary>
        /// The time to wait on a lock before throwing an timeout exception.
        /// </summary>
        TimeSpan BlockTimeOut { get; set; }
    }

    /// <summary>
    /// Semantics for message queues that are Double-Ended.
    /// </summary>
    public interface IDequeBasedMessageQueueSemantics : ISemantics
    {
        void EnqueueFirst(Envelope envelope);
    }

    /// <summary>
    /// Semantics for message queues that are Double-Ended and unbounded
    /// </summary>
    public interface IUnboundedDequeBasedMessageQueueSemantics : IDequeBasedMessageQueueSemantics,
        IUnboundedMessageQueueSemantics
    {
    }

    /// <summary>
    /// Semantics for message queues that are Double-Ended and bounded
    /// </summary>
    public interface IBoundedDequeBasedMessageQueueSemantics : IDequeBasedMessageQueueSemantics,
        IUnboundedMessageQueueSemantics //TODO: make this Bounded once we have BoundedMessageQueues
    {
    }
}


text:
package ca.uhnresearch.pughlab.tracker.dao;

/**
 * An exception that gets thrown where there's a failure to find
 * an expected object.
 *
 * @author stuartw
 */
public class NotFoundException extends RepositoryException {

	/**
	 * Serialization identity.
	 */
	private static final long serialVersionUID = 2897006812479253183L;

	/**
	 * Constructs a new {@link NotFoundException} with a given message.
	 * @param message the message string
	 */
	public NotFoundException(String message) {
		super(message);
	}

}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Orchard.OutputCache.Models;

namespace Orchard.OutputCache.ViewModels {
    public class IndexViewModel {
        public List<CacheRouteConfig> RouteConfigs { get; set; }
        [Range(0, Int32.MaxValue), Required] public int DefaultCacheDuration { get; set; }
        [Range(0, Int32.MaxValue), Required] public int DefaultCacheGraceTime { get; set; }
        [Range(0, Int32.MaxValue), Required] public int DefaultMaxAge { get; set; }
        public bool VaryByQueryStringIsExclusive { get; set; }
        public string VaryByQueryStringParameters { get; set; }
        public string VaryByRequestHeaders { get; set; }
        public string VaryByRequestCookies { get; set; }
        public string IgnoredUrls { get; set; }
        public bool IgnoreNoCache { get; set; }
        public bool VaryByCulture { get; set; }
        public bool CacheAuthenticatedRequests { get; set; }
        public bool VaryByAuthenticationState { get; set; }
        public bool DebugMode { get; set; }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Olstats</title>

    <link href="css/bootstrap.min.css" rel="stylesheet" />
    <link href="css/main.css" rel="stylesheet" />

                QjeX olstats

Списки

            Неверное имя пользователя или пароль

            <form th:action="@{/login}" method="post">

                    Имя пользователя
                    <input type="text" name="username" class="form-control" id="inputUsername" />

                    Пароль
                    <input type="password" name="password" class="form-control" id="inputPass" />

                <input type="submit" class="btn btn-default" value="Войти" />
            </form>


text:
/*  Title:      Pure/Thy/html.scala
    Author:     Makarius

HTML presentation elements.
*/

package isabelle

object HTML
{
  /* output text with control symbols */

  private val control =
    Map(
      Symbol.sub -> "sub", Symbol.sub_decoded -> "sub",
      Symbol.sup -> "sup", Symbol.sup_decoded -> "sup",
      Symbol.bold -> "b", Symbol.bold_decoded -> "b")

  private val control_block =
    Map(
      Symbol.bsub -> "", Symbol.bsub_decoded -> "",
      Symbol.esub -> "", Symbol.esub_decoded -> "",
      Symbol.bsup -> "", Symbol.bsup_decoded -> "",
      Symbol.esup -> "", Symbol.esup_decoded -> "")

  def is_control(sym: Symbol.Symbol): Boolean = control.isDefinedAt(sym)

  def output_char_permissive(c: Char, s: StringBuilder)
  {
    c match {
      case '<' => s ++= "<"
      case '>' => s ++= ">"
      case '&' => s ++= "&"
      case _ => s += c
    }
  }

  def output(text: String, s: StringBuilder, hidden: Boolean, permissive: Boolean)
  {
    def output_char(c: Char): Unit =
      if (permissive) output_char_permissive(c, s)
      else XML.output_char(c, s)

    def output_string(str: String): Unit =
      str.iterator.foreach(output_char)

    def output_hidden(body: => Unit): Unit =
      if (hidden) { s ++= ""; body; s ++= "" }

    def output_symbol(sym: Symbol.Symbol): Unit =
      if (sym != "") {
        control_block.get(sym) match {
          case Some(html) if html.startsWith("</") =>
            s ++= html; output_hidden(output_string(sym))
          case Some(html) =>
            output_hidden(output_string(sym)); s ++= html
          case None =>
            if (hidden && Symbol.is_control_encoded(sym)) {
              output_hidden(output_string(Symbol.control_prefix))
              s ++= ""
              output_string(Symbol.control_name(sym).get)
              s ++= ""
              output_hidden(output_string(Symbol.control_suffix))
            }
            else output_string(sym)
        }
      }

    var ctrl = ""
    for (sym <- Symbol.iterator(text)) {
      if (is_control(sym)) { output_symbol(ctrl); ctrl = sym }
      else {
        control.get(ctrl) match {
          case Some(elem) if Symbol.is_controllable(sym) =>
            output_hidden(output_symbol(ctrl))
            s += '<'; s ++= elem; s += '>'
            output_symbol(sym)
            s ++= "</"; s ++= elem; s += '>'
          case _ =>
            output_symbol(ctrl)
            output_symbol(sym)
        }
        ctrl = ""
      }
    }
    output_symbol(ctrl)
  }

  def output(text: String): String =
    Library.make_string(output(text, _, hidden = false, permissive = true))

  /* output XML as HTML */

  private val structural_elements =
    Set("head", "body", "meta", "div", "pre", "p", "title", "h1", "h2", "h3", "h4", "h5", "h6",
      "ul", "ol", "dl", "li", "dt", "dd")

  def output(body: XML.Body, s: StringBuilder, hidden: Boolean, structural: Boolean)
  {
    def elem(markup: Markup)
    {
      s ++= markup.name
      for ((a, b) <- markup.properties) {
        s += ' '
        s ++= a
        s += '='
        s += '"'
        output(b, s, hidden = hidden, permissive = false)
        s += '"'
      }
    }
    def tree(t: XML.Tree): Unit =
      t match {
        case XML.Elem(markup, Nil) =>
          s += '<'; elem(markup); s ++= "/>"
        case XML.Elem(markup, ts) =>
          if (structural && structural_elements(markup.name)) s += '\n'
          s += '<'; elem(markup); s += '>'
          ts.foreach(tree)
          s ++= "</"; s ++= markup.name; s += '>'
          if (structural && structural_elements(markup.name)) s += '\n'
        case XML.Text(txt) =>
          output(txt, s, hidden = hidden, permissive = true)
      }
    body.foreach(tree)
  }

  def output(body: XML.Body, hidden: Boolean, structural: Boolean): String =
    Library.make_string(output(body, _, hidden, structural))

  def output(tree: XML.Tree, hidden: Boolean, structural: Boolean): String =
    output(List(tree), hidden, structural)

  /* attributes */

  class Attribute(val name: String, value: String)
  {
    def xml: XML.Attribute = name -> value
    def apply(elem: XML.Elem): XML.Elem = elem + xml
  }

  def id(s: String): Attribute = new Attribute("id", s)
  def class_(name: String): Attribute = new Attribute("class", name)

  def width(w: Int): Attribute = new Attribute("width", w.toString)
  def height(h: Int): Attribute = new Attribute("height", h.toString)
  def size(w: Int, h: Int)(elem: XML.Elem): XML.Elem = width(w)(height(h)(elem))

  /* structured markup operators */

  def text(txt: String): XML.Body = if (txt.isEmpty) Nil else List(XML.Text(txt))
  val no_text: XML.Tree = XML.Text("")
  val break: XML.Body = List(XML.elem("br"))

  class Operator(val name: String)
  {
    def apply(body: XML.Body): XML.Elem = XML.elem(name, body)
    def apply(att: Attribute, body: XML.Body): XML.Elem = att(apply(body))
    def apply(c: String, body: XML.Body): XML.Elem = apply(class_(c), body)
  }

  class Heading(name: String) extends Operator(name)
  {
    def apply(txt: String): XML.Elem = super.apply(text(txt))
    def apply(att: Attribute, txt: String): XML.Elem = super.apply(att, text(txt))
    def apply(c: String, txt: String): XML.Elem = super.apply(c, text(txt))
  }

  val div = new Operator("div")
  val span = new Operator("span")
  val pre = new Operator("pre")
  val par = new Operator("p")
  val emph = new Operator("em")
  val bold = new Operator("b")
  val code = new Operator("code")
  val item = new Operator("li")
  val list = new Operator("ul")
  val enum = new Operator("ol")
  val descr = new Operator("dl")
  val dt = new Operator("dt")
  val dd = new Operator("dd")

  val title = new Heading("title")
  val chapter = new Heading("h1")
  val section = new Heading("h2")
  val subsection = new Heading("h3")
  val subsubsection = new Heading("h4")
  val paragraph = new Heading("h5")
  val subparagraph = new Heading("h6")

  def itemize(items: List[XML.Body]): XML.Elem = list(items.map(item(_)))
  def enumerate(items: List[XML.Body]): XML.Elem = enum(items.map(item(_)))
  def description(items: List[(XML.Body, XML.Body)]): XML.Elem =
    descr(items.flatMap({ case (x, y) => List(dt(x), dd(y)) }))

  def link(href: String, body: XML.Body = Nil): XML.Elem =
    XML.Elem(Markup("a", List("href" -> href)), if (body.isEmpty) text(href) else body)

  def image(src: String, alt: String = ""): XML.Elem =
    XML.Elem(Markup("img", List("src" -> src) ::: proper_string(alt).map("alt" -> _).toList), Nil)

  def source(body: XML.Body): XML.Elem = pre("source", body)
  def source(src: String): XML.Elem = source(text(src))

  def style(s: String): XML.Elem = XML.elem("style", text(s))
  def style_file(href: String): XML.Elem =
    XML.Elem(Markup("link", List("rel" -> "stylesheet", "type" -> "text/css", "href" -> href)), Nil)
  def style_file(path: Path): XML.Elem = style_file(Url.print_file(path.file))

  def script(s: String): XML.Elem = XML.elem("script", text(s))
  def script_file(href: String): XML.Elem = XML.Elem(Markup("script", List("src" -> href)), Nil)
  def script_file(path: Path): XML.Elem = script_file(Url.print_file(path.file))

  /* messages */

  // background
  val writeln_message: Attribute = class_("writeln_message")
  val warning_message: Attribute = class_("warning_message")
  val error_message: Attribute = class_("error_message")

  // underline
  val writeln: Attribute = class_("writeln")
  val warning: Attribute = class_("warning")
  val error: Attribute = class_("error")

  /* tooltips */

  def tooltip(item: XML.Body, tip: XML.Body): XML.Elem =
    span(item ::: List(div("tooltip", tip)))

  def tooltip_errors(item: XML.Body, msgs: List[XML.Body]): XML.Elem =
    HTML.error(tooltip(item, msgs.map(msg => error_message(pre(msg)))))

  /* GUI elements */

  object GUI
  {
    private def optional_value(text: String): XML.Attributes =
      proper_string(text).map(a => "value" -> a).toList

    private def optional_name(name: String): XML.Attributes =
      proper_string(name).map(a => "name" -> a).toList

    private def optional_title(tooltip: String): XML.Attributes =
      proper_string(tooltip).map(a => "title" -> a).toList

    private def optional_submit(submit: Boolean): XML.Attributes =
      if (submit) List("onChange" -> "this.form.submit()") else Nil

    private def optional_checked(selected: Boolean): XML.Attributes =
      if (selected) List("checked" -> "") else Nil

    private def optional_action(action: String): XML.Attributes =
      proper_string(action).map(a => "action" -> a).toList

    private def optional_onclick(script: String): XML.Attributes =
      proper_string(script).map(a => "onclick" -> a).toList

    private def optional_onchange(script: String): XML.Attributes =
      proper_string(script).map(a => "onchange" -> a).toList

    def button(body: XML.Body, name: String = "", tooltip: String = "", submit: Boolean = false,
        script: String = ""): XML.Elem =
      XML.Elem(
        Markup("button",
          List("type" -> (if (submit) "submit" else "button"), "value" -> "true") :::
          optional_name(name) ::: optional_title(tooltip) ::: optional_onclick(script)), body)

    def checkbox(body: XML.Body, name: String = "", tooltip: String = "", submit: Boolean = false,
        selected: Boolean = false, script: String = ""): XML.Elem =
      XML.elem("label",
        XML.elem(
          Markup("input",
            List("type" -> "checkbox", "value" -> "true") ::: optional_name(name) :::
              optional_title(tooltip) ::: optional_submit(submit) :::
              optional_checked(selected) ::: optional_onchange(script))) :: body)

    def text_field(columns: Int = 0, text: String = "", name: String = "", tooltip: String = "",
        submit: Boolean = false, script: String = ""): XML.Elem =
      XML.elem(Markup("input",
        List("type" -> "text") :::
          (if (columns > 0) List("size" -> columns.toString) else Nil) :::
          optional_value(text) ::: optional_name(name) ::: optional_title(tooltip) :::
          optional_submit(submit) ::: optional_onchange(script)))

    def parameter(text: String = "", name: String = ""): XML.Elem =
      XML.elem(
        Markup("input", List("type" -> "hidden") ::: optional_value(text) ::: optional_name(name)))

    def form(body: XML.Body, name: String = "", action: String = "", http_post: Boolean = false)
        : XML.Elem =
      XML.Elem(
        Markup("form", optional_name(name) ::: optional_action(action) :::
          (if (http_post) List("method" -> "post") else Nil)), body)
  }

  /* GUI layout */

  object Wrap_Panel
  {
    object Alignment extends Enumeration
    {
      val left, right, center = Value
    }

    def apply(contents: List[XML.Elem], name: String = "", action: String = "",
      alignment: Alignment.Value = Alignment.right): XML.Elem =
    {
      val body = Library.separate(XML.Text(" "), contents)
      GUI.form(List(div(body) + ("style" -> ("text-align: " + alignment))),
        name = name, action = action)
    }
  }

  /* document */

  val header: String =
    XML.header +
    """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
"""

  val head_meta: XML.Elem =
    XML.Elem(Markup("meta",
      List("http-equiv" -> "Content-Type", "content" -> "text/html; charset=utf-8")), Nil)

  def output_document(head: XML.Body, body: XML.Body,
    css: String = "isabelle.css",
    hidden: Boolean = true,
    structural: Boolean = true): String =
  {
    cat_lines(
      List(header,
        output(
          XML.elem("head", head_meta :: (if (css == "") Nil else List(style_file(css))) ::: head),
          hidden = hidden, structural = structural),
        output(XML.elem("body", body),
          hidden = hidden, structural = structural)))
  }

  /* fonts */

  def fonts_url(): String => String =
    (for (entry <- Isabelle_Fonts.fonts(hidden = true))
     yield (entry.name -> Url.print_file(entry.path.file))).toMap

  def fonts_dir(prefix: String)(ttf_name: String): String =
    prefix + "/" + ttf_name

  def fonts_css(make_url: String => String = fonts_url()): String =
  {
    def font_face(entry: Isabelle_Fonts.Entry): String =
      cat_lines(
        List(
          "@font-face {",
          "  font-family: '" + entry.family + "';",
          "  src: url('" + make_url(entry.path.file_name) + "') format('truetype');") :::
        (if (entry.is_bold) List("  font-weight: bold;") else Nil) :::
        (if (entry.is_italic) List("  font-style: italic;") else Nil) :::
        List("}"))

    ("/* Isabelle fonts */" :: Isabelle_Fonts.fonts(hidden = true).map(font_face(_)))
      .mkString("", "\n\n", "\n")
  }

  /* document directory */

  def isabelle_css: Path = Path.explode("~~/etc/isabelle.css")

  def write_isabelle_css(dir: Path, make_url: String => String = fonts_dir("fonts"))
  {
    File.write(dir + isabelle_css.base,
      fonts_css(make_url) + "\n\n" + File.read(isabelle_css))
  }

  def init_dir(dir: Path)
  {
    Isabelle_System.mkdirs(dir)
    write_isabelle_css(dir)
  }

  def write_document(dir: Path, name: String, head: XML.Body, body: XML.Body,
    css: String = isabelle_css.file_name,
    hidden: Boolean = true,
    structural: Boolean = true)
  {
    init_dir(dir)
    File.write(dir + Path.basic(name),
      output_document(head, body, css = css, hidden = hidden, structural = structural))
  }
}


text:
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)setjmperr.c	8.1 (Berkeley) 6/4/93";
#endif /* LIBC_SCCS and not lint */
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: soc2013/dpl/head/lib/libc/gen/setjmperr.c 165946 2007-01-09 00:28:16Z imp $");

/*
 * This routine is called from longjmp() when an error occurs.
 * Programs that wish to exit gracefully from this error may
 * write their own versions.
 * If this routine returns, the program is aborted.
 */

#include "namespace.h"
#include <setjmp.h>
#include <unistd.h>
#include "un-namespace.h"

void
longjmperror()
{
#define	ERRMSG	"longjmp botch.\n"
	(void)_write(STDERR_FILENO, ERRMSG, sizeof(ERRMSG) - 1);
}


text:
var expect = require('expect.js')
  , del = require('del')
  , fs = require('graceful-fs')
  , path = require('path')
  , Task = require('../lib/task')
  , voyager = require('../voyager');

describe('voyager', function () {

  it('is exported as an object', function () {
    expect(voyager).to.be.ok();
    expect(voyager).to.be.an('object');
    expect(Object.keys(voyager).length).to.be.above(0);
    expect(voyager).to.only.have.keys(
      'build'
    , 'cancelWatch'
    , 'clean'
    , 'run'
    , 'task'
    , 'start'
    , 'watch'
    );
  });

  describe('#build()', function () {

    it('exists within voyager as a function', function () {
      expect(voyager).to.have.property('build');
      expect(voyager.build).to.be.a('function');
    });

    it('returns a promise', function (done) {
      var result = voyager.build().then(function () {
        del([__dirname + '/project/.dev', __dirname + '/project/build'], done);
      });
      expect(result).to.be.ok();
      expect(result).to.have.property('then');
      expect(result.then).to.be.a('function');
    });
  });

  describe('#clean()', function () {

    it('exists within voyager as a function', function () {
      expect(voyager).to.have.property('clean');
      expect(voyager.clean).to.be.a('function');
      expect(voyager.clean.length).to.be(0);
    });

    it('returns a promise', function () {
      var result = voyager.clean();
      expect(result).to.have.property('then');
      expect(result.then).to.be.a('function');
    });

    xit('removes the DEV and BLD directories in a project', function (done) {
      process.chdir(path.join(__dirname, 'project'));

      fs.mkdirSync('.dev');
      fs.mkdirSync('build');

      expect(fs.existsSync(process.cwd() + '/.dev')).to.be(true);
      expect(fs.existsSync(process.cwd() + '/build')).to.be(true);
      voyager.clean()
        .then(function () {
          expect(fs.existsSync(process.cwd() + '/.dev')).to.be(false);
          expect(fs.existsSync(process.cwd() + '/build')).to.be(false);
          process.chdir(path.join(__dirname, '../'));
          done();
        });
    });
  });

  describe('#run()', function () {
    var flipped = false;
    before(function () {
      voyager.task('read', 'test', function (done) {
        flipped = true;
        done();
      });
    });
    afterEach(function () {
      flipped = false;
    });

    it('exists within voyager as a function', function () {
      expect(voyager).to.have.property('run');
      expect(voyager.run).to.be.a('function');
      expect(voyager.run.length).to.be(1);
    });

    it('returns a promise', function () {
      var result = voyager.run('test');
      expect(result).to.have.property('then');
      expect(result.then).to.be.a('function');
    });

    it('runs a given task', function () {
      expect(flipped).to.be(false);
      voyager.run('test').then(function () {
        expect(flipped).to.be(true);
        done();
      });
    });
  });

  describe('#start()', function () {

    it('write some tests');
  });

  describe('#task()', function () {
    afterEach(function () {
      Task.collection.splice(0, Task.collection.length);
    });

    it('exists within voyager as a function', function () {
      expect(voyager).to.have.property('task');
      expect(voyager.task).to.be.a('function');
      expect(voyager.task.length).to.be(3);
    });

    it('adds a Task instance to the tasks array', function () {
      expect(Task.collection.length).to.be(0);
      voyager.task('read', 'test', function (done) { done(); });
      expect(Task.collection.length).to.be(1);
      expect(Task.collection[0] instanceof Task).to.be(true);
    });

    it('replaces an existing task with the same name and phase', function () {
      expect(Task.collection.length).to.be(0);
      voyager.task('read', 'test', function (done) { done(); });
      expect(Task.collection.length).to.be(1);
      voyager.task('read', 'test', function (done) { done(); });
      expect(Task.collection.length).to.not.be(2);
      expect(Task.collection.length).to.be(1);
    });
  });

  describe('#watch()', function () {

    it('write some tests');
  });
});


text:
/**
 * @fileoverview Validation rules with bem-naming tech from Yandex
 * @author Ivan Sobolev
 */

"use strict";

var allRules = {
    /**
     * dublicate classes found
     * @type {Object}
     */
    dublicate: {
        isBlock: true,
        isElem: true,
        isBlockMod: true,
        isElemMod: true,
        /**
         * Can be function or string
         * @method
         * @param  {Object} options
         * @return {String}
         */
        message: 'Dublicate classes found',
        valid: (bemNaming, input, source) => {

            // compare input with itself in source
            if ( source && source[0] == input ) {
                return true;
            }

            return source.indexOf(input) < 0;
        }
    },

    /**
     * Block and his element cannot be in one place, wrong => class="b-block b-block__element"
     * @type {Object}
     */
    isBlockElementInBlock: {
        isBlock: true,
        isElem: true,
        message: (options) => 'block' + options.elem + 'element cannot be in place with it`s block',

        valid: function(bemNaming, input, source) {
            var valid = true,
                bemObj = bemNaming.parse(input) || {};

            for (var i = source.length - 1; i >= 0; i--) {
                var className = source[i],
                currentbemObj = bemNaming.parse(className) || {};

                if ( currentbemObj && currentbemObj.block == bemObj.block &&
                    (
                        !bemObj.elem && currentbemObj.elem ||
                        bemObj.elem  && !currentbemObj.elem
                    )) {
                    valid = false;
                    break;
                }
            }

            return valid;
        }
    },

    /**
     * Block mod should be only with it's block, wrong => class="b-block_mod_val"
     * @type {Object}
     */
    isBlockModNoBlock: {
        isBlockMod: true,
        message: (options) => 'A block' + options.mod + 'mod' + options.mod + 'val specified, but block not found',

        valid: function(bemNaming, input, source) {
            var valid = true,
                bemObj = bemNaming.parse(input) || {};

            for (var i = source.length - 1; i >= 0; i--) {
                var className = source[i],
                currentbemObj = bemNaming.parse(className);

                if ( currentbemObj ) {
                    if ( currentbemObj.block == bemObj.block && !currentbemObj.mod ) {
                        valid = true;
                        break;
                    } else {
                        valid = false;
                    }
                }
            }

            return valid;
        }
    },

    /**
     * Element mod should be only with it's element, wrong => class="b-block__element_mod"
     * @type {Object}
     */
    isElemModNoElement: {
        isElemMod: true,
        message: (options) => 'An element' + options.elem + 'mod' + options.mod + 'val specified, but element not found',
        valid: function(bemNaming, input, source) {
            var valid = true,
                bemObj = bemNaming.parse(input) || {};

            for (var i = source.length - 1; i >= 0; i--) {
                var className = source[i],
                currentbemObj = bemNaming.parse(className);

                if ( currentbemObj ) {
                    if ( currentbemObj.block == bemObj.block && currentbemObj.elem && !currentbemObj.elem.mod ) {
                        valid = true;
                        break;
                    } else {
                        valid = false;
                    }
                }
            }

            return valid;
        }

    },
    /**
     * Element should be nested in it's block
     * @type {Object}
     */
    isBlockWrapElement: {
        isElem: true,
        message: (options) => 'Block of the element did not found',
        valid: function(bemNaming, input, source, $, bemlintId) {
            var valid = true,
                bemObj = bemNaming.parse(input);

                return !!$('#' + bemlintId).parents('.' + bemObj.block).length;
        }
    }
};

module.exports = allRules;


text:
package com.cadyyan.lockAndKey.handler;

import com.cadyyan.lockAndKey.LockAndKey;
import com.cadyyan.lockAndKey.Settings;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.client.event.ConfigChangedEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;

import java.io.File;
import java.util.HashSet;
import java.util.Set;

public class ConfigurationHandler
{
	public static Configuration config;

	public static void init(File configFile)
	{
		config = new Configuration(configFile);

		loadConfiguration();
	}

	public static void loadConfiguration()
	{
		Settings.Locks.whitelistEnabled = config.getBoolean("locks.whitelist.enable", Configuration.CATEGORY_GENERAL, false, "Enable or disable the block whitelist for locks");
		Settings.Locks.blockWhitelist = getBlockList(
				config.getStringList(
						"locks.whitelist.blocks",
						Configuration.CATEGORY_GENERAL,
						new String[] {GameRegistry.findUniqueIdentifierFor(Blocks.chest).toString()},
						"The list of blocks that are allowed to have locks added to them"
				)
		);

		Settings.Locks.blacklistEnabled = config.getBoolean("locks.blacklist.enable", Configuration.CATEGORY_GENERAL, false, "Enable or disable the block blacklist for locks");
		Settings.Locks.blockBlacklist = getBlockList(
				config.getStringList(
						"locks.blacklist.blocks",
						Configuration.CATEGORY_GENERAL,
						new String[] {},
						"The list of blocks that are not allowed to have locks added to them"
				)
		);

		if (config.hasChanged())
			config.save();
	}

	@SuppressWarnings("unused")
	@SubscribeEvent
	public void onConfigurationChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event)
	{
		if (event.modID.equalsIgnoreCase(LockAndKey.MODID))
			ConfigurationHandler.loadConfiguration();
	}

	private static Set<Block> getBlockList(String[] blockList)
	{
		Set<Block> blocks = new HashSet<Block>();

		for (String blockName : blockList)
		{
			Block block = Block.getBlockFromName(blockName);

			if (block == null)
			{
				LockAndKey.LOG.warn("Invalid block name {}, skipping", blockName);
				continue;
			}

			blocks.add(block);
		}

		return blocks;
	}
}


text:
//
//  Copyright (c) 2016 Google Inc.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import <UIKit/UIKit.h>

/** @class FUIAuthTableHeaderView
    @brief A table header view that contains a title label and a detail label.
 */
@interface FUIAuthTableHeaderView : UIView

/** @property titleLabel
    @brief The title label in this table header view.
 */
@property(nonatomic, strong) UILabel *titleLabel;

/** @property detailLabel
    @brief The detail label in this table header view.
 */
@property(nonatomic, strong) UILabel *detailLabel;

@end


text:
package system.proxies;

public enum RuntimeMode
{
	Testing(new String[][] { new String[] { "en_US", "Testing" }, new String[] { "nl_NL", "Test" } }),
	Acceptance(new String[][] { new String[] { "en_US", "Acceptance" }, new String[] { "nl_NL", "Acceptatie" } }),
	Production(new String[][] { new String[] { "en_US", "Production" }, new String[] { "nl_NL", "Productie" } });

	private java.util.Map<String,String> captions;

	private RuntimeMode(String[][] captionStrings)
	{
		this.captions = new java.util.HashMap<String,String>();
		for (String[] captionString : captionStrings)
			captions.put(captionString[0], captionString[1]);
	}

	public String getCaption(String languageCode)
	{
		if (captions.containsKey(languageCode))
			return captions.get(languageCode);
		return captions.get("en_US");
	}

	public String getCaption()
	{
		return captions.get("en_US");
	}
}


text:
<?xml version="1.0"?>
<config>
  <!--
	  support multi service address, can be either domain or ip
	  address:port is where the service actually listens, it is ok in another server, as long as can be reached from this server instance
	  service_port is the port our r-nat-s listens at, change the port if a port is used by other r-nat-c
  -->
  <service>
    <node address="127.0.0.1" port="80" service_port="10080"/>
    <node address="127.0.0.1" port="8080" service_port="18080"/>
    <node address="127.0.0.1" port="21" service_port="10021"/>
    <node address="127.0.0.1" port="4018" service_port="14018"/>
    <node address="127.0.0.1" port="4019" service_port="14019"/>
    <node address="127.0.0.1" port="3389" service_port="13389"/>
    <node address="127.0.0.1" port="1025" service_port="11025"/>
    <node address="127.0.0.1" port="5900" service_port="15900"/>
   </service>

  <remote>
  <!--
	  support multi address, can be either domain or ip
	  here are all r-nat-s addresses, final user can reach service at these addresses: service_port
  -->
    <node address="1.1.1.1" port="443" concurrency="10"/>
  </remote>
<!--
recv_buf: should be smaller than max_packet_size, no need to be larger than 64K
packet_defragment: re-assemble packet for less packets
tcp_send_no_delay: control tcp:nolay
-->
<system
load_policy="seq"
max_packet_size="11264000"
recv_buf_size="4096"
queue_limit="10"
tcp_send_no_delay="1"
tcp_connect_timeout="30"
packet_defragment="1"/>
</config>


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2010 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<resources>

    <!-- Used to color the switch bar controls -->
    <style name="ThemeOverlay.SwitchBar" parent="@android:style/ThemeOverlay">
        <!-- Used by controls, e.g. CheckBox, ProgressBar, etc. -->
        <item name="android:colorAccent">@color/switch_accent_color</item>
    </style>

</resources>


text:
Vagrant files to setup a local EventStore cluster using OpsCode Chef Cookbook

    > This is a work in progress.
    > Cluster and gossip seem to be setup correctly now, but having issues with Projections.

## Usage

### Install Vagrant

Download and install [Vagrant](http://downloads.vagrantup.com/).

### Install Vagrant plugins

``` bash
vagrant plugin install vagrant-berkshelf
vagrant plugin install vagrant-omnibus
vagrant plugin install vagrant-cachier
```

### Clone this repository

``` bash
git clone https://github.com/seif/vagrant-eventstore-cluster.git
cd vagrant-eventstore-cluster
```

### Start the cluster

``` bash
vagrant up
```

Wait for all operations to complete, the cluster nodes should now be available at the address 33.33.33.10, 33.33.33.20 and 33.33.33.30

## Customising

### Vagrant configuration

There are some variables at the top of the file which you can use to customise the cluster:

* **NODE_COUNT:** The number of nodes in the cluster.
* **IP_INCREMENT:** How much to increment the ip of each node by.
* **BASE_IP:** The first 3 octects that will make up the ip, the last octet is made up of the IP_INCREMENT * node index.

### EventStore configuration

The [Event Store cookbook](http://community.opscode.com/cookbooks/eventstore) is used to provision the machines.

EventStore configuration parameters can be passed in by modifying the Vagrantfile and adding some keys/values to the eventstore/config hash. Any added keys will be put into the /etc/eventstore/config.json file.


text:
package com.all.rest.mc;

import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

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

import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;

import com.all.messengine.Message;
import com.all.messengine.MessageListener;
import com.all.messengine.impl.StubMessEngine;
import com.all.messengine.support.MessEngineConfigurator;
import com.all.rest.web.RestService;
import com.all.shared.messages.MessEngineConstants;
import com.all.shared.model.AllMessage;
import com.all.shared.model.Category;

public class TestRestTopPlaylistService {
	@Mock
	private RestService restService;

	@Spy
	private StubMessEngine messEngine = new StubMessEngine();

	@InjectMocks
	private TopHundredRestService topService = new TopHundredRestService();

	@Before
	public void setup() {
		MockitoAnnotations.initMocks(this);
	}

	@SuppressWarnings("unchecked")
	@Test
	public void shouldSetTheMessengineListeningMessages() throws Exception {
		new MessEngineConfigurator(messEngine).setupMessEngine(topService);
		verify(messEngine).addMessageListener(eq(MessEngineConstants.TOP_HUNDRED_CATEGORY_LIST_REQUEST),
				any(MessageListener.class));
	}

	@Test
	public void shouldGetPlaylistsForCategory() throws Exception {
		shouldSetTheMessengineListeningMessages();

		List<Category> list = new ArrayList<Category>();
		when(restService.findTopCategories()).thenReturn(list);
		messEngine.send(new AllMessage<Void>(MessEngineConstants.TOP_HUNDRED_CATEGORY_LIST_REQUEST, null));
		Message<?> message = messEngine.getCurrentMessage();
		assertEquals(list, message.getBody());
		assertEquals(MessEngineConstants.TOP_HUNDRED_CATEGORY_LIST_RESPONSE, message.getType());
	}

}


text:
@interface CLUPnPAVPositionInfo : NSObject

@property (nonatomic, assign) float trackDuration;
@property (nonatomic, assign) float absTime;
@property (nonatomic, assign) float relTime;

- (void)setArray:(NSArray *)array;

@end

@interface CLUPnPTransportInfo : NSObject

@property (nonatomic, copy) NSString *currentTransportState;
@property (nonatomic, copy) NSString *currentTransportStatus;
@property (nonatomic, copy) NSString *currentSpeed;

- (void)setArray:(NSArray *)array;

@end

@interface NSString(UPnP)

+(NSString *)stringWithDurationTime:(float)timeValue;
- (float)durationTime;

@end


text:
package fr.fscf.contacts.client.ui.widget.popup;

import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import fr.fscf.contacts.client.event.ClosePopupHandler;
import fr.fscf.contacts.client.ui.view.base.HasPageMessage;
import fr.fscf.contacts.client.ui.widget.Loadable;

/**
 * Interface implemented by all popup widgets.
 *
 * @author Denis
 */
public interface IsPopupWidget extends IsWidget, HasPageMessage, Loadable {

    /**
     * Displays and centers the popup widget.
     */
    void center();

    /**
     * Shows the popup widget.
     */
    void show();

    /**
     * Hides the popup widget.
     */
    void hide();

    /**
     * Sets the popup widget style name.
     *
     * @param styleName
     *         The popup widget style name.
     */
    void setStyleName(String styleName);

    /**
     * Adds a style name to the popup widget.
     *
     * @param styleName
     *         The popup widget style name added.
     */
    void addStyleName(String styleName);

    /**
     * Removes a style name from the popup widget.
     *
     * @param styleName
     *         The popup widget style name removed.
     */
    void removeStyleName(String styleName);

    /**
     * Sets the new popup title.
     *
     * @param title
     *         The new popup title.
     */
    void setTitle(String title);

    /**
     * Sets the new popup content with the given {@code widget} (if a previous content was set, it is overridden).
     *
     * @param widget
     *         The new popup content widget.
     */
    void setContent(Widget widget);

    /**
     * Sets the popup widget's width.
     *
     * @param width
     *         The popup width ({@code null} to set auto width).
     */
    void setWidth(String width);

    /**
     * Sets the popup widget's height.
     *
     * @param height
     *         The popup height ({@code null} to set auto height).
     */
    void setHeight(String height);

    /**
     * Sets popup and glasspane z-index;
     *
     * @param zIndex
     *         The z-index value.
     */
    void setZIndex(int zIndex);

    /**
     * Sets the close handler.
     *
     * @param handler
     *         The handler.
     */
    void setClosePopupHandler(ClosePopupHandler handler);

}