code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php /** * @package Joomla.Site * @subpackage mod_articles_news * * @copyright Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; ?> <ul class="newsflash-vert<?php echo $params->get('moduleclass_sfx'); ?>"> <?php for ($i = 0, $n = count($list); $i < $n; $i ++) : ?> <?php $item = $list[$i]; ?> <li class="newsflash-item"> <?php require JModuleHelper::getLayoutPath('mod_articles_news', '_item'); ?> <?php if ($n > 1 && (($i < $n - 1) || $params->get('showLastSeparator'))) : ?> <span class="article-separator">&#160;</span> <?php endif; ?> </li> <?php endfor; ?> </ul>
yaelduckwen/lo_imaginario
web2/modules/mod_articles_news/tmpl/vertical.php
PHP
mit
735
// ramda.js // https://github.com/CrossEye/ramda // (c) 2013-2014 Scott Sauyet and Michael Hurley // Ramda may be freely distributed under the MIT license. // Ramda // ----- // A practical functional library for Javascript programmers. Ramda is a collection of tools to make it easier to // use Javascript as a functional programming language. (The name is just a silly play on `lambda`.) // Basic Setup // ----------- // Uses a technique from the [Universal Module Definition][umd] to wrap this up for use in Node.js or in the browser, // with or without an AMD-style loader. // // [umd]: https://github.com/umdjs/umd/blob/master/returnExports.js (function(factory) { if (typeof exports === 'object') { module.exports = factory(this); } else if (typeof define === 'function' && define.amd) { define(factory); } else { this.R = this.ramda = factory(this); } }(function() { 'use strict'; // This object is what is actually returned, with all the exposed functions attached as properties. /** * A practical functional library for Javascript programmers. * * @namespace R */ // jscs:disable disallowQuotedKeysInObjects var R = {'version': '0.5.0'}; // jscs:enable disallowQuotedKeysInObjects // Internal Functions and Properties // --------------------------------- /** * An optimized, private array `slice` implementation. * * @private * @category Internal * @param {Arguments|Array} args The array or arguments object to consider. * @param {number} [from=0] The array index to slice from, inclusive. * @param {number} [to=args.length] The array index to slice to, exclusive. * @return {Array} A new, sliced array. * @example * * _slice([1, 2, 3, 4, 5], 1, 3); //=> [2, 3] * * var firstThreeArgs = function(a, b, c, d) { * return _slice(arguments, 0, 3); * }; * firstThreeArgs(1, 2, 3, 4); //=> [1, 2, 3] */ function _slice(args, from, to) { switch (arguments.length) { case 0: throw NO_ARGS_EXCEPTION; case 1: return _slice(args, 0, args.length); case 2: return _slice(args, from, args.length); default: var length = to - from, list = new Array(length), idx = -1; while (++idx < length) { list[idx] = args[from + idx]; } return list; } } /** * Private `concat` function to merge two array-like objects. * * @private * @category Internal * @param {Array|Arguments} [set1=[]] An array-like object. * @param {Array|Arguments} [set2=[]] An array-like object. * @return {Array} A new, merged array. * @example * * concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3] */ var concat = function _concat(set1, set2) { set1 = set1 || []; set2 = set2 || []; var length1 = set1.length, length2 = set2.length, result = new Array(length1 + length2); for (var idx = 0; idx < length1; idx++) { result[idx] = set1[idx]; } for (idx = 0; idx < length2; idx++) { result[idx + length1] = set2[idx]; } return result; }; // Private reference to toString function. var toString = Object.prototype.toString; /** * Tests whether or not an object is an array. * * @private * @category Internal * @param {*} val The object to test. * @return {boolean} `true` if `val` is an array, `false` otherwise. * @example * * isArray([]); //=> true * isArray(true); //=> false * isArray({}); //=> false */ var isArray = Array.isArray || function _isArray(val) { return val && val.length >= 0 && toString.call(val) === '[object Array]'; }; /** * Tests whether or not an object is similar to an array. * * @func * @category Type * @category List * @param {*} val The object to test. * @return {boolean} `true` if `val` has a numeric length property; `false` otherwise. * @example * * R.isArrayLike([]); //=> true * R.isArrayLike(true); //=> false * R.isArrayLike({}); //=> false * R.isArrayLike({length: 10}); //=> true */ R.isArrayLike = function isArrayLike(x) { return isArray(x) || ( !!x && typeof x === 'object' && !(x instanceof String) && ( !!(x.nodeType === 1 && x.length) || x.length >= 0 ) ); }; var NO_ARGS_EXCEPTION = new TypeError('Function called with no arguments'); /** * Optimized internal two-arity curry function. * * @private * @category Function * @param {Function} fn The function to curry. * @return {Function} curried function * @example * * var addTwo = function(a, b) { * return a + b; * }; * * var curriedAddTwo = curry2(addTwo); */ function curry2(fn) { return function(a, b) { switch (arguments.length) { case 0: throw NO_ARGS_EXCEPTION; case 1: return function(b) { return fn(a, b); }; default: return fn(a, b); } }; } /** * Optimized internal three-arity curry function. * * @private * @category Function * @param {Function} fn The function to curry. * @return {Function} curried function * @example * * var addThree = function(a, b, c) { * return a + b + c; * }; * * var curriedAddThree = curry3(addThree); */ function curry3(fn) { return function(a, b, c) { switch (arguments.length) { case 0: throw NO_ARGS_EXCEPTION; case 1: return curry2(function(b, c) { return fn(a, b, c); }); case 2: return function(c) { return fn(a, b, c); }; default: return fn(a, b, c); } }; } if (typeof Object.defineProperty === 'function') { try { Object.defineProperty(R, '_', {writable: false, value: void 0}); } catch (e) {} } var _ = R._; void _;// This intentionally left `undefined`. /** * Converts a function into something like an infix operation, meaning that * when called with a single argument, that argument is applied to the * second position, sort of a curry-right. This allows for more natural * processing of functions which are really binary operators. * * @memberOf R * @category Functions * @param {function} fn The operation to adjust * @return {function} A new function that acts somewhat like an infix operator. * @example * * var div = R.op(function (a, b) { * return a / b; * }); * * div(6, 3); //=> 2 * div(6, _)(3); //=> 2 // note: `_` here is just an `undefined` value. You could use `void 0` instead * div(3)(6); //=> 2 */ var op = R.op = function op(fn) { var length = fn.length; if (length < 2) {throw new Error('Expected binary function.');} var left = curry(fn), right = curry(R.flip(fn)); return function(a, b) { switch (arguments.length) { case 0: throw NO_ARGS_EXCEPTION; case 1: return right(a); case 2: return (b === R._) ? left(a) : left.apply(null, arguments); default: return left.apply(null, arguments); } }; }; /** * Creates a new version of `fn` with given arity that, when invoked, * will return either: * - A new function ready to accept one or more of `fn`'s remaining arguments, if all of * `fn`'s expected arguments have not yet been provided * - `fn`'s result if all of its expected arguments have been provided * * This function is useful in place of `curry`, when the arity of the * function to curry cannot be determined from its signature, e.g. if it's * a variadic function. * * @func * @memberOf R * @category Function * @sig Number -> (* -> a) -> (* -> a) * @param {number} fnArity The arity for the returned function. * @param {Function} fn The function to curry. * @return {Function} A new, curried function. * @see R.curry * @example * * var addFourNumbers = function() { * return R.sum([].slice.call(arguments, 0, 4)); * }; * * var curriedAddFourNumbers = R.curryN(4, addFourNumbers); * var f = curriedAddFourNumbers(1, 2); * var g = f(3); * g(4);//=> 10 */ var curryN = R.curryN = function curryN(length, fn) { return (function recurry(args) { return arity(Math.max(length - (args && args.length || 0), 0), function() { if (arguments.length === 0) { throw NO_ARGS_EXCEPTION; } var newArgs = concat(args, arguments); if (newArgs.length >= length) { return fn.apply(this, newArgs); } else { return recurry(newArgs); } }); }([])); }; /** * Creates a new version of `fn` that, when invoked, will return either: * - A new function ready to accept one or more of `fn`'s remaining arguments, if all of * `fn`'s expected arguments have not yet been provided * - `fn`'s result if all of its expected arguments have been provided * * @func * @memberOf R * @category Function * @sig (* -> a) -> (* -> a) * @param {Function} fn The function to curry. * @return {Function} A new, curried function. * @see R.curryN * @example * * var addFourNumbers = function(a, b, c, d) { * return a + b + c + d; * }; * * var curriedAddFourNumbers = R.curry(addFourNumbers); * var f = curriedAddFourNumbers(1, 2); * var g = f(3); * g(4);//=> 10 */ var curry = R.curry = function curry(fn) { return curryN(fn.length, fn); }; /** * Private function that determines whether or not a provided object has a given method. * Does not ignore methods stored on the object's prototype chain. Used for dynamically * dispatching Ramda methods to non-Array objects. * * @private * @category Internal * @param {string} methodName The name of the method to check for. * @param {Object} obj The object to test. * @return {boolean} `true` has a given method, `false` otherwise. * @example * * var person = { name: 'John' }; * person.shout = function() { alert(this.name); }; * * hasMethod('shout', person); //=> true * hasMethod('foo', person); //=> false */ var hasMethod = function _hasMethod(methodName, obj) { return obj && !isArray(obj) && typeof obj[methodName] === 'function'; }; /** * Similar to hasMethod, this checks whether a function has a [methodname] * function. If it isn't an array it will execute that function otherwise it will * default to the ramda implementation. * * @private * @category Internal * @param {Function} fn ramda implemtation * @param {String} methodname property to check for a custom implementation * @return {Object} whatever the return value of the method is */ function checkForMethod(methodname, fn) { return function(a, b, c) { var length = arguments.length; var obj = arguments[length - 1], callBound = obj && !isArray(obj) && typeof obj[methodname] === 'function'; switch (arguments.length) { case 0: return fn(); case 1: return callBound ? obj[methodname]() : fn(a); case 2: return callBound ? obj[methodname](a) : fn(a, b); case 3: return callBound ? obj[methodname](a, b) : fn(a, b, c); } }; } /** * Wraps a function of any arity (including nullary) in a function that accepts exactly `n` * parameters. Any extraneous parameters will not be passed to the supplied function. * * @func * @memberOf R * @category Function * @sig Number -> (* -> a) -> (* -> a) * @param {number} n The desired arity of the new function. * @param {Function} fn The function to wrap. * @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of * arity `n`. * @example * * var takesTwoArgs = function(a, b) { * return [a, b]; * }; * takesTwoArgs.length; //=> 2 * takesTwoArgs(1, 2); //=> [1, 2] * * var takesOneArg = R.nAry(1, takesTwoArgs); * takesOneArg.length; //=> 1 * // Only `n` arguments are passed to the wrapped function * takesOneArg(1, 2); //=> [1, undefined] */ var nAry = R.nAry = function(n, fn) { switch (n) { case 0: return function() {return fn.call(this);}; case 1: return function(a0) {return fn.call(this, a0);}; case 2: return function(a0, a1) {return fn.call(this, a0, a1);}; case 3: return function(a0, a1, a2) {return fn.call(this, a0, a1, a2);}; case 4: return function(a0, a1, a2, a3) {return fn.call(this, a0, a1, a2, a3);}; case 5: return function(a0, a1, a2, a3, a4) {return fn.call(this, a0, a1, a2, a3, a4);}; case 6: return function(a0, a1, a2, a3, a4, a5) {return fn.call(this, a0, a1, a2, a3, a4, a5);}; case 7: return function(a0, a1, a2, a3, a4, a5, a6) {return fn.call(this, a0, a1, a2, a3, a4, a5, a6);}; case 8: return function(a0, a1, a2, a3, a4, a5, a6, a7) {return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7);}; case 9: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8) {return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7, a8);}; case 10: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9);}; default: return fn; // TODO: or throw? } }; /** * Wraps a function of any arity (including nullary) in a function that accepts exactly 1 * parameter. Any extraneous parameters will not be passed to the supplied function. * * @func * @memberOf R * @category Function * @sig (* -> b) -> (a -> b) * @param {Function} fn The function to wrap. * @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of * arity 1. * @example * * var takesTwoArgs = function(a, b) { * return [a, b]; * }; * takesTwoArgs.length; //=> 2 * takesTwoArgs(1, 2); //=> [1, 2] * * var takesOneArg = R.unary(takesTwoArgs); * takesOneArg.length; //=> 1 * // Only 1 argument is passed to the wrapped function * takesOneArg(1, 2); //=> [1, undefined] */ R.unary = function _unary(fn) { return nAry(1, fn); }; /** * Wraps a function of any arity (including nullary) in a function that accepts exactly 2 * parameters. Any extraneous parameters will not be passed to the supplied function. * * @func * @memberOf R * @category Function * @sig (* -> c) -> (a, b -> c) * @param {Function} fn The function to wrap. * @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of * arity 2. * @example * * var takesThreeArgs = function(a, b, c) { * return [a, b, c]; * }; * takesThreeArgs.length; //=> 3 * takesThreeArgs(1, 2, 3); //=> [1, 2, 3] * * var takesTwoArgs = R.binary(takesThreeArgs); * takesTwoArgs.length; //=> 2 * // Only 2 arguments are passed to the wrapped function * takesTwoArgs(1, 2, 3); //=> [1, 2, undefined] */ var binary = R.binary = function _binary(fn) { return nAry(2, fn); }; /** * Wraps a function of any arity (including nullary) in a function that accepts exactly `n` * parameters. Unlike `nAry`, which passes only `n` arguments to the wrapped function, * functions produced by `arity` will pass all provided arguments to the wrapped function. * * @func * @memberOf R * @sig (Number, (* -> *)) -> (* -> *) * @category Function * @param {number} n The desired arity of the returned function. * @param {Function} fn The function to wrap. * @return {Function} A new function wrapping `fn`. The new function is * guaranteed to be of arity `n`. * @example * * var takesTwoArgs = function(a, b) { * return [a, b]; * }; * takesTwoArgs.length; //=> 2 * takesTwoArgs(1, 2); //=> [1, 2] * * var takesOneArg = R.arity(1, takesTwoArgs); * takesOneArg.length; //=> 1 * // All arguments are passed through to the wrapped function * takesOneArg(1, 2); //=> [1, 2] */ var arity = R.arity = function(n, fn) { switch (n) { case 0: return function() {return fn.apply(this, arguments);}; case 1: return function(a0) {void a0; return fn.apply(this, arguments);}; case 2: return function(a0, a1) {void a1; return fn.apply(this, arguments);}; case 3: return function(a0, a1, a2) {void a2; return fn.apply(this, arguments);}; case 4: return function(a0, a1, a2, a3) {void a3; return fn.apply(this, arguments);}; case 5: return function(a0, a1, a2, a3, a4) {void a4; return fn.apply(this, arguments);}; case 6: return function(a0, a1, a2, a3, a4, a5) {void a5; return fn.apply(this, arguments);}; case 7: return function(a0, a1, a2, a3, a4, a5, a6) {void a6; return fn.apply(this, arguments);}; case 8: return function(a0, a1, a2, a3, a4, a5, a6, a7) {void a7; return fn.apply(this, arguments);}; case 9: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8) {void a8; return fn.apply(this, arguments);}; case 10: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {void a9; return fn.apply(this, arguments);}; default: return fn; // TODO: or throw? } }; /** * Turns a named method of an object (or object prototype) into a function that can be * called directly. Passing the optional `len` parameter restricts the returned function to * the initial `len` parameters of the method. * * The returned function is curried and accepts `len + 1` parameters (or `method.length + 1` * when `len` is not specified), and the final parameter is the target object. * * @func * @memberOf R * @category Function * @sig (String, Object, Number) -> (* -> *) * @param {string} name The name of the method to wrap. * @param {Object} obj The object to search for the `name` method. * @param [len] The desired arity of the wrapped method. * @return {Function} A new function or `undefined` if the specified method is not found. * @example * * var charAt = R.invoker('charAt', String.prototype); * charAt(6, 'abcdefghijklm'); //=> 'g' * * var join = R.invoker('join', Array.prototype); * var firstChar = charAt(0); * join('', R.map(firstChar, ['light', 'ampliifed', 'stimulated', 'emission', 'radiation'])); * //=> 'laser' */ var invoker = R.invoker = function _invoker(name, obj, len) { var method = obj[name]; var length = len === void 0 ? method.length : len; return method && curryN(length + 1, function() { if (arguments.length) { var target = Array.prototype.pop.call(arguments); var targetMethod = target[name]; if (targetMethod == method) { return targetMethod.apply(target, arguments); } } }); }; /** * Accepts a function `fn` and any number of transformer functions and returns a new * function. When the new function is invoked, it calls the function `fn` with parameters * consisting of the result of calling each supplied handler on successive arguments to the * new function. For example: * * ```javascript * var useWithExample = R.useWith(someFn, transformerFn1, transformerFn2); * * // This invocation: * useWithExample('x', 'y'); * // Is functionally equivalent to: * someFn(transformerFn1('x'), transformerFn2('y')) * ``` * * If more arguments are passed to the returned function than transformer functions, those * arguments are passed directly to `fn` as additional parameters. If you expect additional * arguments that don't need to be transformed, although you can ignore them, it's best to * pass an identity function so that the new function reports the correct arity. * * @func * @memberOf R * @category Function * @sig ((* -> *), (* -> *)...) -> (* -> *) * @param {Function} fn The function to wrap. * @param {...Function} transformers A variable number of transformer functions * @return {Function} The wrapped function. * @example * * var double = function(y) { return y * 2; }; * var square = function(x) { return x * x; }; * var add = function(a, b) { return a + b; }; * // Adds any number of arguments together * var addAll = function() { * return R.reduce(add, 0, arguments); * }; * * // Basic example * var addDoubleAndSquare = R.useWith(addAll, double, square); * * //≅ addAll(double(10), square(5)); * addDoubleAndSquare(10, 5); //=> 45 * * // Example of passing more arguments than transformers * //≅ addAll(double(10), square(5), 100); * addDoubleAndSquare(10, 5, 100); //=> 145 * * // But if you're expecting additional arguments that don't need transformation, it's best * // to pass transformer functions so the resulting function has the correct arity * var addDoubleAndSquareWithExtraParams = R.useWith(addAll, double, square, R.identity); * //≅ addAll(double(10), square(5), R.identity(100)); * addDoubleAndSquare(10, 5, 100); //=> 145 */ var useWith = R.useWith = function _useWith(fn /*, transformers */) { var transformers = _slice(arguments, 1); var tlen = transformers.length; return curry(arity(tlen, function() { var args = [], idx = -1; while (++idx < tlen) { args.push(transformers[idx](arguments[idx])); } return fn.apply(this, args.concat(_slice(arguments, tlen))); })); }; /** * Iterate over an input `list`, calling a provided function `fn` for each element in the * list. * * `fn` receives one argument: *(value)*. * * Note: `R.forEach` does not skip deleted or unassigned indices (sparse arrays), unlike * the native `Array.prototype.forEach` method. For more details on this behavior, see: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description * * Also note that, unlike `Array.prototype.forEach`, Ramda's `forEach` returns the original * array. In some libraries this function is named `each`. * * @func * @memberOf R * @category List * @sig (a -> *) -> [a] -> [a] * @param {Function} fn The function to invoke. Receives one argument, `value`. * @param {Array} list The list to iterate over. * @return {Array} The original list. * @example * * var printXPlusFive = function(x) { console.log(x + 5); }; * R.forEach(printXPlusFive, [1, 2, 3]); //=> [1, 2, 3] * //-> 6 * //-> 7 * //-> 8 */ function forEach(fn, list) { var idx = -1, len = list.length; while (++idx < len) { fn(list[idx]); } // i can't bear not to return *something* return list; } R.forEach = curry2(forEach); /** * Like `forEach`, but but passes additional parameters to the predicate function. * * `fn` receives three arguments: *(value, index, list)*. * * Note: `R.forEach.idx` does not skip deleted or unassigned indices (sparse arrays), * unlike the native `Array.prototype.forEach` method. For more details on this behavior, * see: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description * * Also note that, unlike `Array.prototype.forEach`, Ramda's `forEach` returns the original * array. In some libraries this function is named `each`. * * @func * @memberOf R * @category List * @sig (a, i, [a] -> ) -> [a] -> [a] * @param {Function} fn The function to invoke. Receives three arguments: * (`value`, `index`, `list`). * @param {Array} list The list to iterate over. * @return {Array} The original list. * @alias forEach.idx * @example * * // Note that having access to the original `list` allows for * // mutation. While you *can* do this, it's very un-functional behavior: * var plusFive = function(num, idx, list) { list[idx] = num + 5 }; * R.forEach.idx(plusFive, [1, 2, 3]); //=> [6, 7, 8] */ R.forEach.idx = curry2(function forEachIdx(fn, list) { var idx = -1, len = list.length; while (++idx < len) { fn(list[idx], idx, list); } // i can't bear not to return *something* return list; }); /** * Creates a shallow copy of an array. * * @func * @memberOf R * @category Array * @sig [a] -> [a] * @param {Array} list The list to clone. * @return {Array} A new copy of the original list. * @example * * var numbers = [1, 2, 3]; * var numbersClone = R.clone(numbers); //=> [1, 2, 3] * numbers === numbersClone; //=> false * * // Note that this is a shallow clone--it does not clone complex values: * var objects = [{}, {}, {}]; * var objectsClone = R.clone(objects); * objects[0] === objectsClone[0]; //=> true */ var clone = R.clone = function _clone(list) { return _slice(list); }; // Core Functions // -------------- // /** * Reports whether an array is empty. * * @func * @memberOf R * @category Array * @sig [a] -> Boolean * @param {Array} list The array to consider. * @return {boolean} `true` if the `list` argument has a length of 0 or * if `list` is a falsy value (e.g. undefined). * @example * * R.isEmpty([1, 2, 3]); //=> false * R.isEmpty([]); //=> true * R.isEmpty(); //=> true * R.isEmpty(null); //=> true */ function isEmpty(list) { return !list || !list.length; } R.isEmpty = isEmpty; /** * Returns a new list with the given element at the front, followed by the contents of the * list. * * @func * @memberOf R * @category Array * @sig a -> [a] -> [a] * @param {*} el The item to add to the head of the output list. * @param {Array} list The array to add to the tail of the output list. * @return {Array} A new array. * @example * * R.prepend('fee', ['fi', 'fo', 'fum']); //=> ['fee', 'fi', 'fo', 'fum'] */ R.prepend = curry2(function prepend(el, list) { return concat([el], list); }); /** * @func * @memberOf R * @category Array * @see R.prepend */ R.cons = R.prepend; /** * Returns the first element in a list. * In some libraries this function is named `first`. * * @func * @memberOf R * @category Array * @sig [a] -> a * @param {Array} [list=[]] The array to consider. * @return {*} The first element of the list, or `undefined` if the list is empty. * @example * * R.head(['fi', 'fo', 'fum']); //=> 'fi' */ R.head = function head(list) { list = list || []; return list[0]; }; /** * @func * @memberOf R * @category Array * @see R.head */ R.car = R.head; /** * Returns the last element from a list. * * @func * @memberOf R * @category Array * @sig [a] -> a * @param {Array} [list=[]] The array to consider. * @return {*} The last element of the list, or `undefined` if the list is empty. * @example * * R.last(['fi', 'fo', 'fum']); //=> 'fum' */ R.last = function _last(list) { list = list || []; return list[list.length - 1]; }; /** * Returns all but the first element of a list. If the list provided has the `tail` method, * it will instead return `list.tail()`. * * @func * @memberOf R * @category Array * @sig [a] -> [a] * @param {Array} [list=[]] The array to consider. * @return {Array} A new array containing all but the first element of the input list, or an * empty list if the input list is a falsy value (e.g. `undefined`). * @example * * R.tail(['fi', 'fo', 'fum']); //=> ['fo', 'fum'] */ R.tail = checkForMethod('tail', function(list) { list = list || []; return (list.length > 1) ? _slice(list, 1) : []; }); /** * @func * @memberOf R * @category Array * @see R.tail */ R.cdr = R.tail; /** * Returns a new list containing the contents of the given list, followed by the given * element. * * @func * @memberOf R * @category Array * @sig a -> [a] -> [a] * @param {*} el The element to add to the end of the new list. * @param {Array} list The list whose contents will be added to the beginning of the output * list. * @return {Array} A new list containing the contents of the old list followed by `el`. * @example * * R.append('tests', ['write', 'more']); //=> ['write', 'more', 'tests'] * R.append('tests', []); //=> ['tests'] * R.append(['tests'], ['write', 'more']); //=> ['write', 'more', ['tests']] */ var append = R.append = curry2(function _append(el, list) { return concat(list, [el]); }); /** * @func * @memberOf R * @category Array * @see R.append */ R.push = R.append; /** * Returns a new list consisting of the elements of the first list followed by the elements * of the second. * * @func * @memberOf R * @category Array * @sig [a] -> [a] -> [a] * @param {Array} list1 The first list to merge. * @param {Array} list2 The second set to merge. * @return {Array} A new array consisting of the contents of `list1` followed by the * contents of `list2`. If, instead of an {Array} for `list1`, you pass an * object with a `concat` method on it, `concat` will call `list1.concat` * and it the value of `list2`. * @example * * R.concat([], []); //=> [] * R.concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3] * R.concat('ABC', 'DEF'); // 'ABCDEF' */ R.concat = curry2(function(set1, set2) { if (isArray(set2)) { return concat(set1, set2); } else if (R.is(String, set1)) { return set1.concat(set2); } else if (hasMethod('concat', set2)) { return set2.concat(set1); } else { throw new TypeError("can't concat " + typeof set2); } }); /** * A function that does nothing but return the parameter supplied to it. Good as a default * or placeholder function. * * @func * @memberOf R * @category Core * @sig a -> a * @param {*} x The value to return. * @return {*} The input value, `x`. * @example * * R.identity(1); //=> 1 * * var obj = {}; * R.identity(obj) === obj; //=> true */ var identity = R.identity = function _I(x) { return x; }; /** * @func * @memberOf R * @category Core * @see R.identity */ R.I = R.identity; /** * Calls an input function `n` times, returning an array containing the results of those * function calls. * * `fn` is passed one argument: The current value of `n`, which begins at `0` and is * gradually incremented to `n - 1`. * * @func * @memberOf R * @category List * @sig (i -> a) -> i -> [a] * @param {Function} fn The function to invoke. Passed one argument, the current value of `n`. * @param {number} n A value between `0` and `n - 1`. Increments after each function call. * @return {Array} An array containing the return values of all calls to `fn`. * @example * * R.times(R.identity, 5); //=> [0, 1, 2, 3, 4] */ R.times = curry2(function _times(fn, n) { var list = new Array(n); var idx = -1; while (++idx < n) { list[idx] = fn(idx); } return list; }); /** * Returns a fixed list of size `n` containing a specified identical value. * * @func * @memberOf R * @category Array * @sig a -> n -> [a] * @param {*} value The value to repeat. * @param {number} n The desired size of the output list. * @return {Array} A new array containing `n` `value`s. * @example * * R.repeatN('hi', 5); //=> ['hi', 'hi', 'hi', 'hi', 'hi'] * * var obj = {}; * var repeatedObjs = R.repeatN(obj, 5); //=> [{}, {}, {}, {}, {}] * repeatedObjs[0] === repeatedObjs[1]; //=> true */ R.repeatN = curry2(function _repeatN(value, n) { return R.times(R.always(value), n); }); // Function functions :-) // ---------------------- // // These functions make new functions out of old ones. // -------- /** * Basic, right-associative composition function. Accepts two functions and returns the * composite function; this composite function represents the operation `var h = f(g(x))`, * where `f` is the first argument, `g` is the second argument, and `x` is whatever * argument(s) are passed to `h`. * * This function's main use is to build the more general `compose` function, which accepts * any number of functions. * * @private * @category Function * @param {Function} f A function. * @param {Function} g A function. * @return {Function} A new function that is the equivalent of `f(g(x))`. * @example * * var double = function(x) { return x * 2; }; * var square = function(x) { return x * x; }; * var squareThenDouble = internalCompose(double, square); * * squareThenDouble(5); //≅ double(square(5)) => 50 */ function internalCompose(f, g) { return function() { return f.call(this, g.apply(this, arguments)); }; } /** * Creates a new function that runs each of the functions supplied as parameters in turn, * passing the return value of each function invocation to the next function invocation, * beginning with whatever arguments were passed to the initial invocation. * * Note that `compose` is a right-associative function, which means the functions provided * will be invoked in order from right to left. In the example `var h = compose(f, g)`, * the function `h` is equivalent to `f( g(x) )`, where `x` represents the arguments * originally passed to `h`. * * @func * @memberOf R * @category Function * @sig ((y -> z), (x -> y), ..., (b -> c), (a... -> b)) -> (a... -> z) * @param {...Function} functions A variable number of functions. * @return {Function} A new function which represents the result of calling each of the * input `functions`, passing the result of each function call to the next, from * right to left. * @example * * var triple = function(x) { return x * 3; }; * var double = function(x) { return x * 2; }; * var square = function(x) { return x * x; }; * var squareThenDoubleThenTriple = R.compose(triple, double, square); * * //≅ triple(double(square(5))) * squareThenDoubleThenTriple(5); //=> 150 */ var compose = R.compose = function _compose() { switch (arguments.length) { case 0: throw NO_ARGS_EXCEPTION; case 1: return arguments[0]; default: var idx = arguments.length - 1, fn = arguments[idx], length = fn.length; while (idx--) { fn = internalCompose(arguments[idx], fn); } return arity(length, fn); } }; /** * Creates a new function that runs each of the functions supplied as parameters in turn, * passing the return value of each function invocation to the next function invocation, * beginning with whatever arguments were passed to the initial invocation. * * `pipe` is the mirror version of `compose`. `pipe` is left-associative, which means that * each of the functions provided is executed in order from left to right. * * In some libraries this function is named `sequence`. * @func * @memberOf R * @category Function * @sig ((a... -> b), (b -> c), ..., (x -> y), (y -> z)) -> (a... -> z) * @param {...Function} functions A variable number of functions. * @return {Function} A new function which represents the result of calling each of the * input `functions`, passing the result of each function call to the next, from * right to left. * @example * * var triple = function(x) { return x * 3; }; * var double = function(x) { return x * 2; }; * var square = function(x) { return x * x; }; * var squareThenDoubleThenTriple = R.pipe(square, double, triple); * * //≅ triple(double(square(5))) * squareThenDoubleThenTriple(5); //=> 150 */ R.pipe = function _pipe() { return compose.apply(this, _slice(arguments).reverse()); }; /** * Returns a new function much like the supplied one, except that the first two arguments' * order is reversed. * * @func * @memberOf R * @category Function * @sig (a -> b -> c -> ... -> z) -> (b -> a -> c -> ... -> z) * @param {Function} fn The function to invoke with its first two parameters reversed. * @return {*} The result of invoking `fn` with its first two parameters' order reversed. * @example * * var mergeThree = function(a, b, c) { * return ([]).concat(a, b, c); * }; * * mergeThree(1, 2, 3); //=> [1, 2, 3] * * R.flip(mergeThree)(1, 2, 3); //=> [2, 1, 3] */ var flip = R.flip = function _flip(fn) { return function(a, b) { switch (arguments.length) { case 0: throw NO_ARGS_EXCEPTION; case 1: return function(b) { return fn.apply(this, [b, a].concat(_slice(arguments, 1))); }; default: return fn.apply(this, concat([b, a], _slice(arguments, 2))); } }; }; /** * Accepts as its arguments a function and any number of values and returns a function that, * when invoked, calls the original function with all of the values prepended to the * original function's arguments list. In some libraries this function is named `applyLeft`. * * @func * @memberOf R * @category Function * @sig (a -> b -> ... -> i -> j -> ... -> m -> n) -> a -> b-> ... -> i -> (j -> ... -> m -> n) * @param {Function} fn The function to invoke. * @param {...*} [args] Arguments to prepend to `fn` when the returned function is invoked. * @return {Function} A new function wrapping `fn`. When invoked, it will call `fn` * with `args` prepended to `fn`'s arguments list. * @example * * var multiply = function(a, b) { return a * b; }; * var double = R.lPartial(multiply, 2); * double(2); //=> 4 * * var greet = function(salutation, title, firstName, lastName) { * return salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!'; * }; * var sayHello = R.lPartial(greet, 'Hello'); * var sayHelloToMs = R.lPartial(sayHello, 'Ms.'); * sayHelloToMs('Jane', 'Jones'); //=> 'Hello, Ms. Jane Jones!' */ R.lPartial = function _lPartial(fn /*, args */) { var args = _slice(arguments, 1); return arity(Math.max(fn.length - args.length, 0), function() { return fn.apply(this, concat(args, arguments)); }); }; /** * Accepts as its arguments a function and any number of values and returns a function that, * when invoked, calls the original function with all of the values appended to the original * function's arguments list. * * Note that `rPartial` is the opposite of `lPartial`: `rPartial` fills `fn`'s arguments * from the right to the left. In some libraries this function is named `applyRight`. * * @func * @memberOf R * @category Function * @sig (a -> b-> ... -> i -> j -> ... -> m -> n) -> j -> ... -> m -> n -> (a -> b-> ... -> i) * @param {Function} fn The function to invoke. * @param {...*} [args] Arguments to append to `fn` when the returned function is invoked. * @return {Function} A new function wrapping `fn`. When invoked, it will call `fn` with * `args` appended to `fn`'s arguments list. * @example * * var greet = function(salutation, title, firstName, lastName) { * return salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!'; * }; * var greetMsJaneJones = R.rPartial(greet, 'Ms.', 'Jane', 'Jones'); * * greetMsJaneJones('Hello'); //=> 'Hello, Ms. Jane Jones!' */ R.rPartial = function _rPartial(fn) { var args = _slice(arguments, 1); return arity(Math.max(fn.length - args.length, 0), function() { return fn.apply(this, concat(arguments, args)); }); }; /** * Creates a new function that, when invoked, caches the result of calling `fn` for a given * argument set and returns the result. Subsequent calls to the memoized `fn` with the same * argument set will not result in an additional call to `fn`; instead, the cached result * for that set of arguments will be returned. * * Note that this version of `memoize` effectively handles only string and number * parameters. Also note that it does not work on variadic functions. * * @func * @memberOf R * @category Function * @sig (a... -> b) -> (a... -> b) * @param {Function} fn The function to be wrapped by `memoize`. * @return {Function} Returns a memoized version of `fn`. * @example * * var numberOfCalls = 0; * var trackedAdd = function(a, b) { * numberOfCalls += 1; * return a + b; * }; * var memoTrackedAdd = R.memoize(trackedAdd); * * memoTrackedAdd(1, 2); //=> 3 * numberOfCalls; //=> 1 * memoTrackedAdd(1, 2); //=> 3 * numberOfCalls; //=> 1 * memoTrackedAdd(2, 3); //=> 5 * numberOfCalls; //=> 2 * * // Note that argument order matters * memoTrackedAdd(2, 1); //=> 3 * numberOfCalls; //=> 3 */ R.memoize = function _memoize(fn) { if (!fn.length) { return once(fn); } var cache = {}; return function() { if (!arguments.length) {return;} var position = foldl(function(cache, arg) { return cache[arg] || (cache[arg] = {}); }, cache, _slice(arguments, 0, arguments.length - 1)); var arg = arguments[arguments.length - 1]; return (position[arg] || (position[arg] = fn.apply(this, arguments))); }; }; /** * Accepts a function `fn` and returns a function that guards invocation of `fn` such that * `fn` can only ever be called once, no matter how many times the returned function is * invoked. * * @func * @memberOf R * @category Function * @sig (a... -> b) -> (a... -> b) * @param {Function} fn The function to wrap in a call-only-once wrapper. * @return {Function} The wrapped function. * @example * * var addOneOnce = R.once(function(x){ return x + 1; }); * addOneOnce(10); //=> 11 * addOneOnce(addOneOnce(50)); //=> 11 */ var once = R.once = function _once(fn) { var called = false, result; return function() { if (called) { return result; } called = true; result = fn.apply(this, arguments); return result; }; }; /** * Wrap a function inside another to allow you to make adjustments to the parameters, or do * other processing either before the internal function is called or with its results. * * @func * @memberOf R * @category Function * ((* -> *) -> ((* -> *), a...) -> (*, a... -> *) * @param {Function} fn The function to wrap. * @param {Function} wrapper The wrapper function. * @return {Function} The wrapped function. * @example * * var slashify = R.wrap(R.flip(add)('/'), function(f, x) { * return R.match(/\/$/, x) ? x : f(x); * }); * * slashify('a'); //=> 'a/' * slashify('a/'); //=> 'a/' */ R.wrap = function _wrap(fn, wrapper) { return function() { return wrapper.apply(this, concat([fn], arguments)); }; }; /** * Wraps a constructor function inside a curried function that can be called with the same * arguments and returns the same type. The arity of the function returned is specified * to allow using variadic constructor functions. * * NOTE: Does not work with some built-in objects such as Date. * * @func * @memberOf R * @category Function * @sig Number -> (* -> {*}) -> (* -> {*}) * @param {number} n The arity of the constructor function. * @param {Function} Fn The constructor function to wrap. * @return {Function} A wrapped, curried constructor function. * @example * * // Variadic constructor function * var Widget = function() { * this.children = Array.prototype.slice.call(arguments); * // ... * }; * Widget.prototype = { * // ... * }; * var allConfigs = { * // ... * }; * R.map(R.constructN(1, Widget), allConfigs); // a list of Widgets */ var constructN = R.constructN = curry2(function _constructN(n, Fn) { var f = function() { var Temp = function() {}, inst, ret; Temp.prototype = Fn.prototype; inst = new Temp(); ret = Fn.apply(inst, arguments); return Object(ret) === ret ? ret : inst; }; return n > 1 ? curry(nAry(n, f)) : f; }); /** * Wraps a constructor function inside a curried function that can be called with the same * arguments and returns the same type. * * NOTE: Does not work with some built-in objects such as Date. * * @func * @memberOf R * @category Function * @sig (* -> {*}) -> (* -> {*}) * @param {Function} Fn The constructor function to wrap. * @return {Function} A wrapped, curried constructor function. * @example * * // Constructor function * var Widget = function(config) { * // ... * }; * Widget.prototype = { * // ... * }; * var allConfigs = { * // ... * }; * R.map(R.construct(Widget), allConfigs); // a list of Widgets */ R.construct = function _construct(Fn) { return constructN(Fn.length, Fn); }; /** * Accepts three functions and returns a new function. When invoked, this new function will * invoke the first function, `after`, passing as its arguments the results of invoking the * second and third functions with whatever arguments are passed to the new function. * * For example, a function produced by `converge` is equivalent to: * * ```javascript * var h = R.converge(e, f, g); * h(1, 2); //≅ e( f(1, 2), g(1, 2) ) * ``` * * @func * @memberOf R * @category Function * @sig ((a, b -> c) -> (((* -> a), (* -> b), ...) -> c) * @param {Function} after A function. `after` will be invoked with the return values of * `fn1` and `fn2` as its arguments. * @param {Function} fn1 A function. It will be invoked with the arguments passed to the * returned function. Afterward, its resulting value will be passed to `after` as * its first argument. * @param {Function} fn2 A function. It will be invoked with the arguments passed to the * returned function. Afterward, its resulting value will be passed to `after` as * its second argument. * @return {Function} A new function. * @example * * var add = function(a, b) { return a + b; }; * var multiply = function(a, b) { return a * b; }; * var subtract = function(a, b) { return a - b; }; * * //≅ multiply( add(1, 2), subtract(1, 2) ); * R.converge(multiply, add, subtract)(1, 2); //=> -3 */ R.converge = function(after) { var fns = _slice(arguments, 1); return function() { var args = arguments; return after.apply(this, map(function(fn) { return fn.apply(this, args); }, fns)); }; }; // List Functions // -------------- // // These functions operate on logical lists, here plain arrays. Almost all of these are curried, and the list // parameter comes last, so you can create a new function by supplying the preceding arguments, leaving the // list parameter off. For instance: // // // skip third parameter // var checkAllPredicates = reduce(andFn, alwaysTrue); // // ... given suitable definitions of odd, lt20, gt5 // var test = checkAllPredicates([odd, lt20, gt5]); // // test(7) => true, test(9) => true, test(10) => false, // // test(3) => false, test(21) => false, // -------- /** * Returns a single item by iterating through the list, successively calling the iterator * function and passing it an accumulator value and the current value from the array, and * then passing the result to the next call. * * The iterator function receives two values: *(acc, value)* * * Note: `R.reduce` does not skip deleted or unassigned indices (sparse arrays), unlike * the native `Array.prototype.reduce` method. For more details on this behavior, see: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description * * @func * @memberOf R * @category List * @sig (a,b -> a) -> a -> [b] -> a * @param {Function} fn The iterator function. Receives two values, the accumulator and the * current element from the array. * @param {*} acc The accumulator value. * @param {Array} list The list to iterate over. * @return {*} The final, accumulated value. * @example * * var numbers = [1, 2, 3]; * var add = function(a, b) { * return a + b; * }; * * R.reduce(add, 10, numbers); //=> 16 */ R.reduce = curry3(function _reduce(fn, acc, list) { var idx = -1, len = list.length; while (++idx < len) { acc = fn(acc, list[idx]); } return acc; }); /** * @func * @memberOf R * @category List * @see R.reduce */ var foldl = R.foldl = R.reduce; /** * Like `reduce`, but passes additional parameters to the predicate function. * * The iterator function receives four values: *(acc, value, index, list)* * * Note: `R.reduce.idx` does not skip deleted or unassigned indices (sparse arrays), * unlike the native `Array.prototype.reduce` method. For more details on this behavior, * see: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description * * @func * @memberOf R * @category List * @sig (a,b,i,[b] -> a) -> a -> [b] -> a * @param {Function} fn The iterator function. Receives four values: the accumulator, the * current element from `list`, that element's index, and the entire `list` itself. * @param {*} acc The accumulator value. * @param {Array} list The list to iterate over. * @return {*} The final, accumulated value. * @alias reduce.idx * @example * * var letters = ['a', 'b', 'c']; * var objectify = function(accObject, elem, idx, list) { * accObject[elem] = idx; * return accObject; * }; * * R.reduce.idx(objectify, {}, letters); //=> { 'a': 0, 'b': 1, 'c': 2 } */ R.reduce.idx = curry3(function _reduceIdx(fn, acc, list) { var idx = -1, len = list.length; while (++idx < len) { acc = fn(acc, list[idx], idx, list); } return acc; }); /** * @func * @memberOf R * @category List * @alias foldl.idx * @see R.reduce.idx */ R.foldl.idx = R.reduce.idx; /** * Returns a single item by iterating through the list, successively calling the iterator * function and passing it an accumulator value and the current value from the array, and * then passing the result to the next call. * * Similar to `reduce`, except moves through the input list from the right to the left. * * The iterator function receives two values: *(acc, value)* * * Note: `R.reduce` does not skip deleted or unassigned indices (sparse arrays), unlike * the native `Array.prototype.reduce` method. For more details on this behavior, see: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description * * @func * @memberOf R * @category List * @sig (a,b -> a) -> a -> [b] -> a * @param {Function} fn The iterator function. Receives two values, the accumulator and the * current element from the array. * @param {*} acc The accumulator value. * @param {Array} list The list to iterate over. * @return {*} The final, accumulated value. * @example * * var pairs = [ ['a', 1], ['b', 2], ['c', 3] ]; * var flattenPairs = function(acc, pair) { * return acc.concat(pair); * }; * * R.reduceRight(flattenPairs, [], pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ] */ R.reduceRight = curry3(checkForMethod('reduceRight', function _reduceRight(fn, acc, list) { var idx = list.length; while (idx--) { acc = fn(acc, list[idx]); } return acc; })); /** * @func * @memberOf R * @category List * @see R.reduceRight */ R.foldr = R.reduceRight; /** * Like `reduceRight`, but passes additional parameters to the predicate function. Moves through * the input list from the right to the left. * * The iterator function receives four values: *(acc, value, index, list)*. * * Note: `R.reduceRight.idx` does not skip deleted or unassigned indices (sparse arrays), * unlike the native `Array.prototype.reduce` method. For more details on this behavior, * see: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description * * @func * @memberOf R * @category List * @sig (a,b,i,[b] -> a -> [b] -> a * @param {Function} fn The iterator function. Receives four values: the accumulator, the * current element from `list`, that element's index, and the entire `list` itself. * @param {*} acc The accumulator value. * @param {Array} list The list to iterate over. * @return {*} The final, accumulated value. * @alias reduceRight.idx * @example * * var letters = ['a', 'b', 'c']; * var objectify = function(accObject, elem, idx, list) { * accObject[elem] = idx; * return accObject; * }; * * R.reduceRight.idx(objectify, {}, letters); //=> { 'c': 2, 'b': 1, 'a': 0 } */ R.reduceRight.idx = curry3(function _reduceRightIdx(fn, acc, list) { var idx = list.length; while (idx--) { acc = fn(acc, list[idx], idx, list); } return acc; }); /** * @func * @memberOf R * @category List * @alias foldr.idx * @see R.reduceRight.idx */ R.foldr.idx = R.reduceRight.idx; /** * Builds a list from a seed value. Accepts an iterator function, which returns either false * to stop iteration or an array of length 2 containing the value to add to the resulting * list and the seed to be used in the next call to the iterator function. * * The iterator function receives one argument: *(seed)*. * * @func * @memberOf R * @category List * @sig (a -> [b]) -> * -> [b] * @param {Function} fn The iterator function. receives one argument, `seed`, and returns * either false to quit iteration or an array of length two to proceed. The element * at index 0 of this array will be added to the resulting array, and the element * at index 1 will be passed to the next call to `fn`. * @param {*} seed The seed value. * @return {Array} The final list. * @example * * var f = function(n) { return n > 50 ? false : [-n, n + 10] }; * R.unfoldr(f, 10); //=> [-10, -20, -30, -40, -50] */ R.unfoldr = curry2(function _unfoldr(fn, seed) { var pair = fn(seed); var result = []; while (pair && pair.length) { result.push(pair[0]); pair = fn(pair[1]); } return result; }); /** * Returns a new list, constructed by applying the supplied function to every element of the * supplied list. * * Note: `R.map` does not skip deleted or unassigned indices (sparse arrays), unlike the * native `Array.prototype.map` method. For more details on this behavior, see: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Description * * @func * @memberOf R * @category List * @sig (a -> b) -> [a] -> [b] * @param {Function} fn The function to be called on every element of the input `list`. * @param {Array} list The list to be iterated over. * @return {Array} The new list. * @example * * var double = function(x) { * return x * 2; * }; * * R.map(double, [1, 2, 3]); //=> [2, 4, 6] */ function map(fn, list) { var idx = -1, len = list.length, result = new Array(len); while (++idx < len) { result[idx] = fn(list[idx]); } return result; } R.map = curry2(checkForMethod('map', map)); /** * Like `map`, but but passes additional parameters to the mapping function. * `fn` receives three arguments: *(value, index, list)*. * * Note: `R.map.idx` does not skip deleted or unassigned indices (sparse arrays), unlike * the native `Array.prototype.map` method. For more details on this behavior, see: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Description * * @func * @memberOf R * @category List * @sig (a,i,[b] -> b) -> [a] -> [b] * @param {Function} fn The function to be called on every element of the input `list`. * @param {Array} list The list to be iterated over. * @return {Array} The new list. * @alias map.idx * @example * * var squareEnds = function(elt, idx, list) { * if (idx === 0 || idx === list.length - 1) { * return elt * elt; * } * return elt; * }; * * R.map.idx(squareEnds, [8, 5, 3, 0, 9]); //=> [64, 5, 3, 0, 81] */ R.map.idx = curry2(function _mapIdx(fn, list) { var idx = -1, len = list.length, result = new Array(len); while (++idx < len) { result[idx] = fn(list[idx], idx, list); } return result; }); /** * Map, but for objects. Creates an object with the same keys as `obj` and values * generated by running each property of `obj` through `fn`. `fn` is passed one argument: * *(value)*. * * @func * @memberOf R * @category List * @sig (v -> v) -> {k: v} -> {k: v} * @param {Function} fn A function called for each property in `obj`. Its return value will * become a new property on the return object. * @param {Object} obj The object to iterate over. * @return {Object} A new object with the same keys as `obj` and values that are the result * of running each property through `fn`. * @example * * var values = { x: 1, y: 2, z: 3 }; * var double = function(num) { * return num * 2; * }; * * R.mapObj(double, values); //=> { x: 2, y: 4, z: 6 } */ // TODO: consider mapObj.key in parallel with mapObj.idx. Also consider folding together with `map` implementation. R.mapObj = curry2(function _mapObject(fn, obj) { return foldl(function(acc, key) { acc[key] = fn(obj[key]); return acc; }, {}, keys(obj)); }); /** * Like `mapObj`, but but passes additional arguments to the predicate function. The * predicate function is passed three arguments: *(value, key, obj)*. * * @func * @memberOf R * @category List * @sig (v, k, {k: v} -> v) -> {k: v} -> {k: v} * @param {Function} fn A function called for each property in `obj`. Its return value will * become a new property on the return object. * @param {Object} obj The object to iterate over. * @return {Object} A new object with the same keys as `obj` and values that are the result * of running each property through `fn`. * @alias mapObj.idx * @example * * var values = { x: 1, y: 2, z: 3 }; * var prependKeyAndDouble = function(num, key, obj) { * return key + (num * 2); * }; * * R.mapObj.idx(prependKeyAndDouble, values); //=> { x: 'x2', y: 'y4', z: 'z6' } */ R.mapObj.idx = curry2(function mapObjectIdx(fn, obj) { return foldl(function(acc, key) { acc[key] = fn(obj[key], key, obj); return acc; }, {}, keys(obj)); }); /** * ap applies a list of functions to a list of values. * * @func * @memberOf R * @category Function * @sig [f] -> [a] -> [f a] * @param {Array} fns An array of functions * @param {Array} vs An array of values * @return the value of applying each the function `fns` to each value in `vs` * @example * * R.ap([R.multiply(2), R.add(3)], [1,2,3]); //=> [2, 4, 6, 4, 5, 6] */ R.ap = curry2(function _ap(fns, vs) { return hasMethod('ap', fns) ? fns.ap(vs) : foldl(function(acc, fn) { return concat(acc, map(fn, vs)); }, [], fns); }); /** * * `of` wraps any object in an Array. This implementation is compatible with the * Fantasy-land Applicative spec, and will work with types that implement that spec. * Note this `of` is different from the ES6 `of`; See * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/of * * @func * @memberOf R * @category Function * @sig a -> [a] * @param {*} x any value * @return [x] * @example * * R.of(1); //=> [1] * R.of([2]); //=> [[2]] * R.of({}); //=> [{}] */ R.of = function _of(x, container) { return (hasMethod('of', container)) ? container.of(x) : [x]; }; /** * `empty` wraps any object in an array. This implementation is compatible with the * Fantasy-land Monoid spec, and will work with types that implement that spec. * * @func * @memberOf R * @category Function * @sig * -> [] * @return {Array} an empty array * @example * * R.empty([1,2,3,4,5]); //=> [] */ R.empty = function _empty(x) { return (hasMethod('empty', x)) ? x.empty() : []; }; /** * `chain` maps a function over a list and concatenates the results. * This implementation is compatible with the * Fantasy-land Chain spec, and will work with types that implement that spec. * `chain` is also known as `flatMap` in some libraries * * @func * @memberOf R * @category List * @sig (a -> [b]) -> [a] -> [b] * @param {Function} fn * @param {Array} list * @return {Array} * @example * * var duplicate = function(n) { * return [n, n]; * }; * R.chain(duplicate, [1, 2, 3]); //=> [1, 1, 2, 2, 3, 3] * */ R.chain = curry2(checkForMethod('chain', function _chain(f, list) { return unnest(map(f, list)); })); /** * Returns the number of elements in the array by returning `list.length`. * * @func * @memberOf R * @category List * @sig [a] -> Number * @param {Array} list The array to inspect. * @return {number} The size of the array. * @example * * R.size([]); //=> 0 * R.size([1, 2, 3]); //=> 3 */ R.size = function _size(list) { return list.length; }; /** * @func * @memberOf R * @category List * @see R.size */ R.length = R.size; /** * Returns a new list containing only those items that match a given predicate function. * The predicate function is passed one argument: *(value)*. * * Note that `R.filter` does not skip deleted or unassigned indices, unlike the native * `Array.prototype.filter` method. For more details on this behavior, see: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Description * * @func * @memberOf R * @category List * @sig (a -> Boolean) -> [a] -> [a] * @param {Function} fn The function called per iteration. * @param {Array} list The collection to iterate over. * @return {Array} The new filtered array. * @example * * var isEven = function(n) { * return n % 2 === 0; * }; * R.filter(isEven, [1, 2, 3, 4]); //=> [2, 4] */ var filter = function _filter(fn, list) { var idx = -1, len = list.length, result = []; while (++idx < len) { if (fn(list[idx])) { result.push(list[idx]); } } return result; }; R.filter = curry2(checkForMethod('filter', filter)); /** * Like `filter`, but passes additional parameters to the predicate function. The predicate * function is passed three arguments: *(value, index, list)*. * * @func * @memberOf R * @category List * @sig (a, i, [a] -> Boolean) -> [a] -> [a] * @param {Function} fn The function called per iteration. * @param {Array} list The collection to iterate over. * @return {Array} The new filtered array. * @alias filter.idx * @example * * var lastTwo = function(val, idx, list) { * return list.length - idx <= 2; * }; * R.filter.idx(lastTwo, [8, 6, 7, 5, 3, 0, 9]); //=> [0, 9] */ function filterIdx(fn, list) { var idx = -1, len = list.length, result = []; while (++idx < len) { if (fn(list[idx], idx, list)) { result.push(list[idx]); } } return result; } R.filter.idx = curry2(filterIdx); /** * Similar to `filter`, except that it keeps only values for which the given predicate * function returns falsy. The predicate function is passed one argument: *(value)*. * * @func * @memberOf R * @category List * @sig (a -> Boolean) -> [a] -> [a] * @param {Function} fn The function called per iteration. * @param {Array} list The collection to iterate over. * @return {Array} The new filtered array. * @example * * var isOdd = function(n) { * return n % 2 === 1; * }; * R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4] */ var reject = function _reject(fn, list) { return filter(not(fn), list); }; R.reject = curry2(reject); /** * Like `reject`, but passes additional parameters to the predicate function. The predicate * function is passed three arguments: *(value, index, list)*. * * @func * @memberOf R * @category List * @sig (a, i, [a] -> Boolean) -> [a] -> [a] * @param {Function} fn The function called per iteration. * @param {Array} list The collection to iterate over. * @return {Array} The new filtered array. * @alias reject.idx * @example * * var lastTwo = function(val, idx, list) { * return list.length - idx <= 2; * }; * * R.reject.idx(lastTwo, [8, 6, 7, 5, 3, 0, 9]); //=> [8, 6, 7, 5, 3] */ R.reject.idx = curry2(function _rejectIdx(fn, list) { return filterIdx(not(fn), list); }); /** * Returns a new list containing the first `n` elements of a given list, passing each value * to the supplied predicate function, and terminating when the predicate function returns * `false`. Excludes the element that caused the predicate function to fail. The predicate * function is passed one argument: *(value)*. * * @func * @memberOf R * @category List * @sig (a -> Boolean) -> [a] -> [a] * @param {Function} fn The function called per iteration. * @param {Array} list The collection to iterate over. * @return {Array} A new array. * @example * * var isNotFour = function(x) { * return !(x === 4); * }; * * R.takeWhile(isNotFour, [1, 2, 3, 4]); //=> [1, 2, 3] */ R.takeWhile = curry2(checkForMethod('takeWhile', function(fn, list) { var idx = -1, len = list.length; while (++idx < len && fn(list[idx])) {} return _slice(list, 0, idx); })); /** * Returns a new list containing the first `n` elements of the given list. If * `n > * list.length`, returns a list of `list.length` elements. * * @func * @memberOf R * @category List * @sig Number -> [a] -> [a] * @param {number} n The number of elements to return. * @param {Array} list The array to query. * @return {Array} A new array containing the first elements of `list`. */ R.take = curry2(checkForMethod('take', function(n, list) { return _slice(list, 0, Math.min(n, list.length)); })); /** * Returns a new list containing the last `n` elements of a given list, passing each value * to the supplied predicate function, beginning when the predicate function returns * `true`. Excludes the element that caused the predicate function to fail. The predicate * function is passed one argument: *(value)*. * * @func * @memberOf R * @category List * @sig (a -> Boolean) -> [a] -> [a] * @param {Function} fn The function called per iteration. * @param {Array} list The collection to iterate over. * @return {Array} A new array. * @example * * var isTwo = function(x) { * return x === 2; * }; * * R.skipUntil(isTwo, [1, 2, 3, 4]); //=> [2, 3, 4] */ R.skipUntil = curry2(function _skipUntil(fn, list) { var idx = -1, len = list.length; while (++idx < len && !fn(list[idx])) {} return _slice(list, idx); }); /** * Returns a new list containing all but the first `n` elements of the given `list`. * * @func * @memberOf R * @category List * @sig Number -> [a] -> [a] * @param {number} n The number of elements of `list` to skip. * @param {Array} list The array to consider. * @return {Array} The last `n` elements of `list`. * @example * * R.skip(3, [1,2,3,4,5,6,7]); //=> [4,5,6,7] */ R.skip = curry2(checkForMethod('skip', function _skip(n, list) { if (n < list.length) { return _slice(list, n); } else { return []; } })); /** * Returns the first element of the list which matches the predicate, or `undefined` if no * element matches. * * @func * @memberOf R * @category List * @sig (a -> Boolean) -> [a] -> a | undefined * @param {Function} fn The predicate function used to determine if the element is the * desired one. * @param {Array} list The array to consider. * @return {Object} The element found, or `undefined`. * @example * * var xs = [{a: 1}, {a: 2}, {a: 3}]; * R.find(R.propEq('a', 2))(xs); //=> {a: 2} * R.find(R.propEq('a', 4))(xs); //=> undefined */ R.find = curry2(function find(fn, list) { var idx = -1; var len = list.length; while (++idx < len) { if (fn(list[idx])) { return list[idx]; } } }); /** * Returns the index of the first element of the list which matches the predicate, or `-1` * if no element matches. * * @func * @memberOf R * @category List * @sig (a -> Boolean) -> [a] -> Number * @param {Function} fn The predicate function used to determine if the element is the * desired one. * @param {Array} list The array to consider. * @return {number} The index of the element found, or `-1`. * @example * * var xs = [{a: 1}, {a: 2}, {a: 3}]; * R.findIndex(R.propEq('a', 2))(xs); //=> 1 * R.findIndex(R.propEq('a', 4))(xs); //=> -1 */ R.findIndex = curry2(function _findIndex(fn, list) { var idx = -1; var len = list.length; while (++idx < len) { if (fn(list[idx])) { return idx; } } return -1; }); /** * Returns the last element of the list which matches the predicate, or `undefined` if no * element matches. * * @func * @memberOf R * @category List * @sig (a -> Boolean) -> [a] -> a | undefined * @param {Function} fn The predicate function used to determine if the element is the * desired one. * @param {Array} list The array to consider. * @return {Object} The element found, or `undefined`. * @example * * var xs = [{a: 1, b: 0}, {a:1, b: 1}]; * R.findLast(R.propEq('a', 1))(xs); //=> {a: 1, b: 1} * R.findLast(R.propEq('a', 4))(xs); //=> undefined */ R.findLast = curry2(function _findLast(fn, list) { var idx = list.length; while (idx--) { if (fn(list[idx])) { return list[idx]; } } }); /** * Returns the index of the last element of the list which matches the predicate, or * `-1` if no element matches. * * @func * @memberOf R * @category List * @sig (a -> Boolean) -> [a] -> Number * @param {Function} fn The predicate function used to determine if the element is the * desired one. * @param {Array} list The array to consider. * @return {number} The index of the element found, or `-1`. * @example * * var xs = [{a: 1, b: 0}, {a:1, b: 1}]; * R.findLastIndex(R.propEq('a', 1))(xs); //=> 1 * R.findLastIndex(R.propEq('a', 4))(xs); //=> -1 */ R.findLastIndex = curry2(function _findLastIndex(fn, list) { var idx = list.length; while (idx--) { if (fn(list[idx])) { return idx; } } return -1; }); /** * Returns `true` if all elements of the list match the predicate, `false` if there are any * that don't. * * @func * @memberOf R * @category List * @sig (a -> Boolean) -> [a] -> Boolean * @param {Function} fn The predicate function. * @param {Array} list The array to consider. * @return {boolean} `true` if the predicate is satisfied by every element, `false` * otherwise * @example * * var lessThan2 = R.flip(R.lt)(2); * var lessThan3 = R.flip(R.lt)(3); * var xs = R.range(1, 3); * xs; //=> [1, 2] * R.every(lessThan2)(xs); //=> false * R.every(lessThan3)(xs); //=> true */ function every(fn, list) { var idx = -1; while (++idx < list.length) { if (!fn(list[idx])) { return false; } } return true; } R.every = curry2(every); /** * Returns `true` if at least one of elements of the list match the predicate, `false` * otherwise. * * @func * @memberOf R * @category List * @sig (a -> Boolean) -> [a] -> Boolean * @param {Function} fn The predicate function. * @param {Array} list The array to consider. * @return {boolean} `true` if the predicate is satisfied by at least one element, `false` * otherwise * @example * * var lessThan0 = R.flip(R.lt)(0); * var lessThan2 = R.flip(R.lt)(2); * var xs = R.range(1, 3); * xs; //=> [1, 2] * R.some(lessThan0)(xs); //=> false * R.some(lessThan2)(xs); //=> true */ function some(fn, list) { var idx = -1; while (++idx < list.length) { if (fn(list[idx])) { return true; } } return false; } R.some = curry2(some); /** * Internal implementation of `indexOf`. * Returns the position of the first occurrence of an item in an array * (by strict equality), * or -1 if the item is not included in the array. * * @private * @category Internal * @param {Array} The array to search * @param {*} item the item to find in the Array * @param {Number} from (optional) the index to start searching the Array * @return {Number} the index of the found item, or -1 * */ var indexOf = function _indexOf(list, item, from) { var idx = 0, length = list.length; if (typeof from == 'number') { idx = from < 0 ? Math.max(0, length + from) : from; } for (; idx < length; idx++) { if (list[idx] === item) { return idx; } } return -1; }; /** * Internal implementation of `lastIndexOf`. * Returns the position of the last occurrence of an item in an array * (by strict equality), * or -1 if the item is not included in the array. * * @private * @category Internal * @param {Array} The array to search * @param {*} item the item to find in the Array * @param {Number} from (optional) the index to start searching the Array * @return {Number} the index of the found item, or -1 * */ var lastIndexOf = function _lastIndexOf(list, item, from) { var idx = list.length; if (typeof from == 'number') { idx = from < 0 ? idx + from + 1 : Math.min(idx, from + 1); } while (--idx >= 0) { if (list[idx] === item) { return idx; } } return -1; }; /** * Returns the position of the first occurrence of an item in an array * (by strict equality), * or -1 if the item is not included in the array. * * @func * @memberOf R * @category List * @sig a -> [a] -> Number * @param {*} target The item to find. * @param {Array} list The array to search in. * @return {Number} the index of the target, or -1 if the target is not found. * * @example * * R.indexOf(3, [1,2,3,4]); //=> 2 * R.indexOf(10, [1,2,3,4]); //=> -1 */ R.indexOf = curry2(function _indexOf(target, list) { return indexOf(list, target); }); /** * Returns the position of the first occurrence of an item (by strict equality) in * an array, or -1 if the item is not included in the array. However, * `indexOf.from` will only search the tail of the array, starting from the * `fromIdx` parameter. * * @func * @memberOf R * @category List * @sig a -> Number -> [a] -> Number * @param {*} target The item to find. * @param {Array} list The array to search in. * @param {Number} fromIdx the index to start searching from * @return {Number} the index of the target, or -1 if the target is not found. * * @example * * R.indexOf.from(3, 2, [-1,0,1,2,3,4]); //=> 4 * R.indexOf.from(10, 2, [1,2,3,4]); //=> -1 */ R.indexOf.from = curry3(function indexOfFrom(target, fromIdx, list) { return indexOf(list, target, fromIdx); }); /** * Returns the position of the last occurrence of an item (by strict equality) in * an array, or -1 if the item is not included in the array. * * @func * @memberOf R * @category List * @sig a -> [a] -> Number * @param {*} target The item to find. * @param {Array} list The array to search in. * @return {Number} the index of the target, or -1 if the target is not found. * * @example * * R.lastIndexOf(3, [-1,3,3,0,1,2,3,4]); //=> 6 * R.lastIndexOf(10, [1,2,3,4]); //=> -1 */ R.lastIndexOf = curry2(function _lastIndexOf(target, list) { return lastIndexOf(list, target); }); /** * Returns the position of the last occurrence of an item (by strict equality) in * an array, or -1 if the item is not included in the array. However, * `lastIndexOf.from` will only search the tail of the array, starting from the * `fromIdx` parameter. * * @func * @memberOf R * @category List * @sig a -> Number -> [a] -> Number * @param {*} target The item to find. * @param {Array} list The array to search in. * @param {Number} fromIdx the index to start searching from * @return {Number} the index of the target, or -1 if the target is not found. * * @example * * R.lastIndexOf.from(3, 2, [-1,3,3,0,1,2,3,4]); //=> 2 * R.lastIndexOf.from(10, 2, [1,2,3,4]); //=> -1 */ R.lastIndexOf.from = curry3(function lastIndexOfFrom(target, fromIdx, list) { return lastIndexOf(list, target, fromIdx); }); /** * Returns `true` if the specified item is somewhere in the list, `false` otherwise. * Equivalent to `indexOf(a)(list) > -1`. Uses strict (`===`) equality checking. * * @func * @memberOf R * @category List * @sig a -> [a] -> Boolean * @param {Object} a The item to compare against. * @param {Array} list The array to consider. * @return {boolean} `true` if the item is in the list, `false` otherwise. * @example * * R.contains(3)([1, 2, 3]); //=> true * R.contains(4)([1, 2, 3]); //=> false * R.contains({})([{}, {}]); //=> false * var obj = {}; * R.contains(obj)([{}, obj, {}]); //=> true */ function contains(a, list) { return indexOf(list, a) > -1; } R.contains = curry2(contains); /** * Returns `true` if the `x` is found in the `list`, using `pred` as an * equality predicate for `x`. * * @func * @memberOf R * @category List * @sig (x, a -> Boolean) -> x -> [a] -> Boolean * @param {Function} pred :: x -> x -> Bool * @param {*} x the item to find * @param {Array} list the list to iterate over * @return {Boolean} `true` if `x` is in `list`, else `false` * @example * * var xs = [{x: 12}, {x: 11}, {x: 10}]; * R.containsWith(function(a, b) { return a.x === b.x; }, {x: 10}, xs); //=> true * R.containsWith(function(a, b) { return a.x === b.x; }, {x: 1}, xs); //=> false */ function containsWith(pred, x, list) { var idx = -1, len = list.length; while (++idx < len) { if (pred(x, list[idx])) { return true; } } return false; } R.containsWith = curry3(containsWith); /** * Returns a new list containing only one copy of each element in the original list. * Equality is strict here, meaning reference equality for objects and non-coercing equality * for primitives. * * @func * @memberOf R * @category List * @sig [a] -> [a] * @param {Array} list The array to consider. * @return {Array} The list of unique items. * @example * * R.uniq([1, 1, 2, 1]); //=> [1, 2] * R.uniq([{}, {}]); //=> [{}, {}] * R.uniq([1, '1']); //=> [1, '1'] */ var uniq = R.uniq = function uniq(list) { var idx = -1, len = list.length; var result = [], item; while (++idx < len) { item = list[idx]; if (!contains(item, result)) { result.push(item); } } return result; }; /** * Returns `true` if all elements are unique, otherwise `false`. * Uniqueness is determined using strict equality (`===`). * * @func * @memberOf R * @category List * @sig [a] -> Boolean * @param {Array} list The array to consider. * @return {boolean} `true` if all elements are unique, else `false`. * @example * * R.isSet(['1', 1]); //=> true * R.isSet([1, 1]); //=> false * R.isSet([{}, {}]); //=> true */ R.isSet = function _isSet(list) { var len = list.length; var idx = -1; while (++idx < len) { if (indexOf(list, list[idx], idx + 1) >= 0) { return false; } } return true; }; /** * Returns a new list containing only one copy of each element in the original list, based * upon the value returned by applying the supplied predicate to two list elements. Prefers * the first item if two items compare equal based on the predicate. * * @func * @memberOf R * @category List * @sig (x, a -> Boolean) -> [a] -> [a] * @param {Function} pred :: x -> x -> Bool * @param {Array} list The array to consider. * @return {Array} The list of unique items. * @example * * var strEq = function(a, b) { return ('' + a) === ('' + b) }; * R.uniqWith(strEq)([1, '1', 2, 1]); //=> [1, 2] * R.uniqWith(strEq)([{}, {}]); //=> [{}] * R.uniqWith(strEq)([1, '1', 1]); //=> [1] * R.uniqWith(strEq)(['1', 1, 1]); //=> ['1'] */ var uniqWith = R.uniqWith = curry2(function _uniqWith(pred, list) { var idx = -1, len = list.length; var result = [], item; while (++idx < len) { item = list[idx]; if (!containsWith(pred, item, result)) { result.push(item); } } return result; }); /** * Returns a new list by plucking the same named property off all objects in the list supplied. * * @func * @memberOf R * @category List * @sig String -> {*} -> [*] * @param {string|number} key The key name to pluck off of each object. * @param {Array} list The array to consider. * @return {Array} The list of values for the given key. * @example * * R.pluck('a')([{a: 1}, {a: 2}]); //=> [1, 2] * R.pluck(0)([[1, 2], [3, 4]]); //=> [1, 3] */ var pluck = R.pluck = curry2(function _pluck(p, list) { return map(prop(p), list); }); /** * `makeFlat` is a helper function that returns a one-level or fully recursive function * based on the flag passed in. * * @private */ // TODO: document, even for internals... var makeFlat = function _makeFlat(recursive) { return function __flatt(list) { var value, result = [], idx = -1, j, ilen = list.length, jlen; while (++idx < ilen) { if (R.isArrayLike(list[idx])) { value = (recursive) ? __flatt(list[idx]) : list[idx]; j = -1; jlen = value.length; while (++j < jlen) { result.push(value[j]); } } else { result.push(list[idx]); } } return result; }; }; /** * Returns a new list by pulling every item out of it (and all its sub-arrays) and putting * them in a new array, depth-first. * * @func * @memberOf R * @category List * @sig [a] -> [b] * @param {Array} list The array to consider. * @return {Array} The flattened list. * @example * * R.flatten([1, 2, [3, 4], 5, [6, [7, 8, [9, [10, 11], 12]]]]); * //=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] */ R.flatten = makeFlat(true); /** * Returns a new list by pulling every item at the first level of nesting out, and putting * them in a new array. * * @func * @memberOf R * @category List * @sig [a] -> [b] * @param {Array} list The array to consider. * @return {Array} The flattened list. * @example * * R.unnest([1, [2], [[3]]]); //=> [1, 2, [3]] * R.unnest([[1, 2], [3, 4], [5, 6]]); //=> [1, 2, 3, 4, 5, 6] */ var unnest = R.unnest = makeFlat(false); /** * Creates a new list out of the two supplied by applying the function to * each equally-positioned pair in the lists. The returned list is * truncated to the length of the shorter of the two input lists. * * @function * @memberOf R * @category List * @sig (a,b -> c) -> a -> b -> [c] * @param {Function} fn The function used to combine the two elements into one value. * @param {Array} list1 The first array to consider. * @param {Array} list2 The second array to consider. * @return {Array} The list made by combining same-indexed elements of `list1` and `list2` * using `fn`. * @example * * var f = function(x, y) { * // ... * }; * R.zipWith(f, [1, 2, 3], ['a', 'b', 'c']); * //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')] */ R.zipWith = curry3(function _zipWith(fn, a, b) { var rv = [], idx = -1, len = Math.min(a.length, b.length); while (++idx < len) { rv[idx] = fn(a[idx], b[idx]); } return rv; }); /** * Creates a new list out of the two supplied by pairing up * equally-positioned items from both lists. The returned list is * truncated to the length of the shorter of the two input lists. * Note: `zip` is equivalent to `zipWith(function(a, b) { return [a, b] })`. * * @func * @memberOf R * @category List * @sig a -> b -> [[a,b]] * @param {Array} list1 The first array to consider. * @param {Array} list2 The second array to consider. * @return {Array} The list made by pairing up same-indexed elements of `list1` and `list2`. * @example * * R.zip([1, 2, 3], ['a', 'b', 'c']); //=> [[1, 'a'], [2, 'b'], [3, 'c']] */ R.zip = curry2(function _zip(a, b) { var rv = []; var idx = -1; var len = Math.min(a.length, b.length); while (++idx < len) { rv[idx] = [a[idx], b[idx]]; } return rv; }); /** * Creates a new object out of a list of keys and a list of values. * * @func * @memberOf R * @category List * @sig k -> v -> {k: v} * @param {Array} keys The array that will be properties on the output object. * @param {Array} values The list of values on the output object. * @return {Object} The object made by pairing up same-indexed elements of `keys` and `values`. * @example * * R.zipObj(['a', 'b', 'c'], [1, 2, 3]); //=> {a: 1, b: 2, c: 3} */ R.zipObj = curry2(function _zipObj(keys, values) { var idx = -1, len = keys.length, out = {}; while (++idx < len) { out[keys[idx]] = values[idx]; } return out; }); /** * Creates a new object out of a list key-value pairs. * * @func * @memberOf R * @category List * @sig [[k,v]] -> {k: v} * @param {Array} An array of two-element arrays that will be the keys and values of the ouput object. * @return {Object} The object made by pairing up `keys` and `values`. * @example * * R.fromPairs([['a', 1], ['b', 2], ['c', 3]]); //=> {a: 1, b: 2, c: 3} */ R.fromPairs = function _fromPairs(pairs) { var idx = -1, len = pairs.length, out = {}; while (++idx < len) { if (isArray(pairs[idx]) && pairs[idx].length) { out[pairs[idx][0]] = pairs[idx][1]; } } return out; }; /** * Creates a new list out of the two supplied by applying the function * to each possible pair in the lists. * * @see R.xprod * @func * @memberOf R * @category List * @sig (a,b -> c) -> a -> b -> [c] * @param {Function} fn The function to join pairs with. * @param {Array} as The first list. * @param {Array} bs The second list. * @return {Array} The list made by combining each possible pair from * `as` and `bs` using `fn`. * @example * * var f = function(x, y) { * // ... * }; * R.xprodWith(f, [1, 2], ['a', 'b']); * // [f(1, 'a'), f(1, 'b'), f(2, 'a'), f(2, 'b')]; */ R.xprodWith = curry3(function _xprodWith(fn, a, b) { if (isEmpty(a) || isEmpty(b)) { return []; } // Better to push them all or to do `new Array(ilen * jlen)` and // calculate indices? var idx = -1, ilen = a.length, j, jlen = b.length, result = []; while (++idx < ilen) { j = -1; while (++j < jlen) { result.push(fn(a[idx], b[j])); } } return result; }); /** * Creates a new list out of the two supplied by creating each possible * pair from the lists. * * @func * @memberOf R * @category List * @sig a -> b -> [[a,b]] * @param {Array} as The first list. * @param {Array} bs The second list. * @return {Array} The list made by combining each possible pair from * `as` and `bs` into pairs (`[a, b]`). * @example * * R.xprod([1, 2], ['a', 'b']); //=> [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']] */ R.xprod = curry2(function _xprod(a, b) { // = xprodWith(prepend); (takes about 3 times as long...) if (isEmpty(a) || isEmpty(b)) { return []; } var idx = -1; var ilen = a.length; var j; var jlen = b.length; // Better to push them all or to do `new Array(ilen * jlen)` and calculate indices? var result = []; while (++idx < ilen) { j = -1; while (++j < jlen) { result.push([a[idx], b[j]]); } } return result; }); /** * Returns a new list with the same elements as the original list, just * in the reverse order. * * @func * @memberOf R * @category List * @sig [a] -> [a] * @param {Array} list The list to reverse. * @return {Array} A copy of the list in reverse order. * @example * * R.reverse([1, 2, 3]); //=> [3, 2, 1] * R.reverse([1, 2]); //=> [2, 1] * R.reverse([1]); //=> [1] * R.reverse([]); //=> [] */ R.reverse = function _reverse(list) { return clone(list || []).reverse(); }; /** * Returns a list of numbers from `from` (inclusive) to `to` * (exclusive). * * @func * @memberOf R * @category List * @sig Number -> Number -> [Number] * @param {number} from The first number in the list. * @param {number} to One more than the last number in the list. * @return {Array} The list of numbers in tthe set `[a, b)`. * @example * * R.range(1, 5); //=> [1, 2, 3, 4] * R.range(50, 53); //=> [50, 51, 52] */ R.range = curry2(function _range(from, to) { if (from >= to) { return []; } var idx = 0, result = new Array(Math.floor(to) - Math.ceil(from)); for (; from < to; idx++, from++) { result[idx] = from; } return result; }); /** * Returns a string made by inserting the `separator` between each * element and concatenating all the elements into a single string. * * @func * @memberOf R * @category List * @sig String -> [a] -> String * @param {string|number} separator The string used to separate the elements. * @param {Array} xs The elements to join into a string. * @return {string} The string made by concatenating `xs` with `separator`. * @example * * var spacer = R.join(' '); * spacer(['a', 2, 3.4]); //=> 'a 2 3.4' * R.join('|', [1, 2, 3]); //=> '1|2|3' */ R.join = invoker('join', Array.prototype); /** * Returns the elements from `xs` starting at `a` and ending at `b - 1`. * * @func * @memberOf R * @category List * @sig Number -> Number -> [a] -> [a] * @param {number} a The starting index. * @param {number} b One more than the ending index. * @param {Array} xs The list to take elements from. * @return {Array} The items from `a` to `b - 1` from `xs`. * @example * * var xs = R.range(0, 10); * R.slice(2, 5)(xs); //=> [2, 3, 4] */ R.slice = invoker('slice', Array.prototype); /** * Returns the elements from `xs` starting at `a` going to the end of `xs`. * * @func * @memberOf R * @category List * @sig Number -> [a] -> [a] * @param {number} a The starting index. * @param {Array} xs The list to take elements from. * @return {Array} The items from `a` to the end of `xs`. * @example * * var xs = R.range(0, 10); * R.slice.from(2)(xs); //=> [2, 3, 4, 5, 6, 7, 8, 9] * * var ys = R.range(4, 8); * var tail = R.slice.from(1); * tail(ys); //=> [5, 6, 7] */ R.slice.from = curry2(function(a, xs) { return xs.slice(a, xs.length); }); /** * Removes the sub-list of `list` starting at index `start` and containing * `count` elements. _Note that this is not destructive_: it returns a * copy of the list with the changes. * <small>No lists have been harmed in the application of this function.</small> * * @func * @memberOf R * @category List * @sig Number -> Number -> [a] -> [a] * @param {Number} start The position to start removing elements * @param {Number} count The number of elements to remove * @param {Array} list The list to remove from * @return {Array} a new Array with `count` elements from `start` removed * @example * * R.remove(2, 3, [1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8] */ R.remove = curry3(function _remove(start, count, list) { return concat(_slice(list, 0, Math.min(start, list.length)), _slice(list, Math.min(list.length, start + count))); }); /** * Inserts the supplied element into the list, at index `index`. _Note * that this is not destructive_: it returns a copy of the list with the changes. * <small>No lists have been harmed in the application of this function.</small> * * @func * @memberOf R * @category List * @sig Number -> a -> [a] -> [a] * @param {Number} index The position to insert the element * @param {*} elt The element to insert into the Array * @param {Array} list The list to insert into * @return {Array} a new Array with `elt` inserted at `index` * @example * * R.insert(2, 'x', [1,2,3,4]); //=> [1,2,'x',3,4] */ R.insert = curry3(function _insert(idx, elt, list) { idx = idx < list.length && idx >= 0 ? idx : list.length; return concat(append(elt, _slice(list, 0, idx)), _slice(list, idx)); }); /** * Inserts the sub-list into the list, at index `index`. _Note that this * is not destructive_: it returns a copy of the list with the changes. * <small>No lists have been harmed in the application of this function.</small> * * @func * @memberOf R * @category List * @sig Number -> [a] -> [a] -> [a] * @param {Number} index The position to insert the sublist * @param {Array} elts The sub-list to insert into the Array * @param {Array} list The list to insert the sub-list into * @return {Array} a new Array with `elts` inserted starting at `index` * @example * * R.insert.all(2, ['x','y','z'], [1,2,3,4]); //=> [1,2,'x','y','z',3,4] */ R.insert.all = curry3(function _insertAll(idx, elts, list) { idx = idx < list.length && idx >= 0 ? idx : list.length; return concat(concat(_slice(list, 0, idx), elts), _slice(list, idx)); }); /** * Makes a comparator function out of a function that reports whether the first element is less than the second. * * @func * @memberOf R * @category Function * @sig (a, b -> Boolean) -> (a, b -> Number) * @param {Function} pred A predicate function of arity two. * @return {Function} a Function :: a -> b -> Int that returns `-1` if a < b, `1` if b < a, otherwise `0` * @example * * var cmp = R.comparator(function(a, b) { * return a.age < b.age; * }); * var people = [ * // ... * ]; * R.sort(cmp, people); */ var comparator = R.comparator = function _comparator(pred) { return function(a, b) { return pred(a, b) ? -1 : pred(b, a) ? 1 : 0; }; }; /** * Returns a copy of the list, sorted according to the comparator function, which should accept two values at a * time and return a negative number if the first value is smaller, a positive number if it's larger, and zero * if they are equal. Please note that this is a **copy** of the list. It does not modify the original. * * @func * @memberOf R * @category List * @sig (a,a -> Number) -> [a] -> [a] * @param {Function} comparator A sorting function :: a -> b -> Int * @param {Array} list The list to sort * @return {Array} a new array with its elements sorted by the comparator function. * @example * * var diff = function(a, b) { return a - b; }; * R.sort(diff, [4,2,7,5]); //=> [2, 4, 5, 7] */ R.sort = curry2(function sort(comparator, list) { return clone(list).sort(comparator); }); /** * Splits a list into sublists stored in an object, based on the result of calling a String-returning function * on each element, and grouping the results according to values returned. * * @func * @memberOf R * @category List * @sig (a -> s) -> [a] -> {s: a} * @param {Function} fn Function :: a -> String * @param {Array} list The array to group * @return {Object} An object with the output of `fn` for keys, mapped to arrays of elements * that produced that key when passed to `fn`. * @example * * var byGrade = R.groupBy(function(student) { * var score = student.score; * return (score < 65) ? 'F' : (score < 70) ? 'D' : * (score < 80) ? 'C' : (score < 90) ? 'B' : 'A'; * }); * var students = [{name: 'Abby', score: 84}, * {name: 'Eddy', score: 58}, * // ... * {name: 'Jack', score: 69}]; * byGrade(students); * // { * // 'A': [{name: 'Dianne', score: 99}], * // 'B': [{name: 'Abby', score: 84}] * // // ..., * // 'F': [{name: 'Eddy', score: 58}] * // } */ R.groupBy = curry2(function _groupBy(fn, list) { return foldl(function(acc, elt) { var key = fn(elt); acc[key] = append(elt, acc[key] || (acc[key] = [])); return acc; }, {}, list); }); /** * Takes a predicate and a list and returns the pair of lists of * elements which do and do not satisfy the predicate, respectively. * * @func * @memberOf R * @category List * @sig (a -> Boolean) -> [a] -> [[a],[a]] * @param {Function} pred Function :: a -> Boolean * @param {Array} list The array to partition * @return {Array} A nested array, containing first an array of elements that satisfied the predicate, * and second an array of elements that did not satisfy. * @example * * R.partition(R.contains('s'), ['sss', 'ttt', 'foo', 'bars']); * //=> [ [ 'sss', 'bars' ], [ 'ttt', 'foo' ] ] */ R.partition = curry2(function _partition(pred, list) { return foldl(function(acc, elt) { acc[pred(elt) ? 0 : 1].push(elt); return acc; }, [[], []], list); }); // Object Functions // ---------------- // // These functions operate on plain Javascript object, adding simple functions to test properties on these // objects. Many of these are of most use in conjunction with the list functions, operating on lists of // objects. // -------- /** * Runs the given function with the supplied object, then returns the object. * * @func * @memberOf R * @category Function * @sig a -> (a -> *) -> a * @param {*} x * @param {Function} fn The function to call with `x`. The return value of `fn` will be thrown away. * @return {*} x * @example * * var sayX = function(x) { console.log('x is ' + x); }; * R.tap(100, sayX); //=> 100 * //-> 'x is 100') */ R.tap = curry2(function _tap(x, fn) { if (typeof fn === 'function') { fn(x); } return x; }); /** * Tests if two items are equal. Equality is strict here, meaning reference equality for objects and * non-coercing equality for primitives. * * @func * @memberOf R * @category Relation * @sig a -> b -> Boolean * @param {*} a * @param {*} b * @return {Boolean} * @example * * var o = {}; * R.eq(o, o); //=> true * R.eq(o, {}); //=> false * R.eq(1, 1); //=> true * R.eq(1, '1'); //=> false */ R.eq = curry2(function _eq(a, b) { return a === b; }); /** * Returns a function that when supplied an object returns the indicated property of that object, if it exists. * * @func * @memberOf R * @category Object * @sig s -> {s: a} -> a * @param {String} p The property name * @param {Object} obj The object to query * @return {*} The value at obj.p * @example * * R.prop('x', {x: 100}); //=> 100 * R.prop('x', {}); //=> undefined * * var fifth = R.prop(4); // indexed from 0, remember * fifth(['Bashful', 'Doc', 'Dopey', 'Grumpy', 'Happy', 'Sleepy', 'Sneezy']); * //=> 'Happy' */ var prop = R.prop = function prop(p, obj) { switch (arguments.length) { case 0: throw NO_ARGS_EXCEPTION; case 1: return function _prop(obj) { return obj[p]; }; } return obj[p]; }; /** * @func * @memberOf R * @category Object * @see R.prop */ R.get = R.prop; /** * Returns the value at the specified property. * The only difference from `prop` is the parameter order. * * @func * @memberOf R * @see R.prop * @category Object * @sig {s: a} -> s -> a * @param {Object} obj The object to query * @param {String} prop The property name * @return {*} The value at obj.p * @example * * R.props({x: 100}, 'x'); //=> 100 */ R.props = flip(R.prop); /** * An internal reference to `Object.prototype.hasOwnProperty` * @private */ var hasOwnProperty = Object.prototype.hasOwnProperty; /** * If the given object has an own property with the specified name, * returns the value of that property. * Otherwise returns the provided default value. * * @func * @memberOf R * @category Object * @sig s -> v -> {s: x} -> x | v * @param {String} p The name of the property to return. * @param {*} val The default value. * @returns {*} The value of given property or default value. * @example * * var alice = { * name: 'ALICE', * age: 101 * }; * var favorite = R.prop('favoriteLibrary'); * var favoriteWithDefault = R.propOrDefault('favoriteLibrary', 'Ramda'); * * favorite(alice); //=> undefined * favoriteWithDefault(alice); //=> 'Ramda' */ R.propOrDefault = curry3(function _propOrDefault(p, val, obj) { return hasOwnProperty.call(obj, p) ? obj[p] : val; }); /** * Calls the specified function on the supplied object. Any additional arguments * after `fn` and `obj` are passed in to `fn`. If no additional arguments are passed to `func`, * `fn` is invoked with no arguments. * * @func * @memberOf R * @category Object * @sig k -> {k : v} -> v(*) * @param {String} fn The name of the property mapped to the function to invoke * @param {Object} obj The object * @return {*} The value of invoking `obj.fn` * @example * * R.func('add', R, 1, 2); //=> 3 * * var obj = { f: function() { return 'f called'; } }; * R.func('f', obj); //=> 'f called' */ R.func = function _func(funcName, obj) { switch (arguments.length) { case 0: throw NO_ARGS_EXCEPTION; case 1: return function(obj) { return obj[funcName].apply(obj, _slice(arguments, 1)); }; default: return obj[funcName].apply(obj, _slice(arguments, 2)); } }; /** * Returns a function that always returns the given value. * * @func * @memberOf R * @category Function * @sig a -> (* -> a) * @param {*} val The value to wrap in a function * @return {Function} A Function :: * -> val * @example * * var t = R.always('Tee'); * t(); //=> 'Tee' */ var always = R.always = function _always(val) { return function() { return val; }; }; /** * Internal reference to Object.keys * * @private * @param {Object} * @return {Array} */ var nativeKeys = Object.keys; /** * Returns a list containing the names of all the enumerable own * properties of the supplied object. * Note that the order of the output array is not guaranteed to be * consistent across different JS platforms. * * @func * @memberOf R * @category Object * @sig {k: v} -> [k] * @param {Object} obj The object to extract properties from * @return {Array} An array of the object's own properties * @example * * R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c'] */ var keys = R.keys = (function() { // cover IE < 9 keys issues var hasEnumBug = !({toString: null}).propertyIsEnumerable('toString'); var nonEnumerableProps = ['constructor', 'valueOf', 'isPrototypeOf', 'toString', 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; return function _keys(obj) { if (!R.is(Object, obj)) { return []; } if (nativeKeys) { return nativeKeys(Object(obj)); } var prop, ks = [], nIdx; for (prop in obj) { if (hasOwnProperty.call(obj, prop)) { ks.push(prop); } } if (hasEnumBug) { nIdx = nonEnumerableProps.length; while (nIdx--) { prop = nonEnumerableProps[nIdx]; if (hasOwnProperty.call(obj, prop) && !R.contains(prop, ks)) { ks.push(prop); } } } return ks; }; }()); /** * Returns a list containing the names of all the * properties of the supplied object, including prototype properties. * Note that the order of the output array is not guaranteed to be * consistent across different JS platforms. * * @func * @memberOf R * @category Object * @sig {k: v} -> [k] * @param {Object} obj The object to extract properties from * @return {Array} An array of the object's own and prototype properties * @example * * var F = function() { this.x = 'X'; }; * F.prototype.y = 'Y'; * var f = new F(); * R.keysIn(f); //=> ['x', 'y'] */ R.keysIn = function _keysIn(obj) { var prop, ks = []; for (prop in obj) { ks.push(prop); } return ks; }; /** * @private * @param {Function} fn The strategy for extracting keys from an object * @return {Function} A function that takes an object and returns an array of * key-value arrays. */ var pairWith = function(fn) { return function(obj) { return R.map(function(key) { return [key, obj[key]]; }, fn(obj)); }; }; /** * Converts an object into an array of key, value arrays. * Only the object's own properties are used. * Note that the order of the output array is not guaranteed to be * consistent across different JS platforms. * * @func * @memberOf R * @category Object * @sig {k: v} -> [[k,v]] * @param {Object} obj The object to extract from * @return {Array} An array of key, value arrays from the object's own properties * @example * * R.toPairs({a: 1, b: 2, c: 3}); //=> [['a', 1], ['b', 2], ['c', 3]] */ R.toPairs = pairWith(R.keys); /** * Converts an object into an array of key, value arrays. * The object's own properties and prototype properties are used. * Note that the order of the output array is not guaranteed to be * consistent across different JS platforms. * * @func * @memberOf R * @category Object * @sig {k: v} -> [[k,v]] * @param {Object} obj The object to extract from * @return {Array} An array of key, value arrays from the object's own * and prototype properties * @example * * var F = function() { this.x = 'X'; }; * F.prototype.y = 'Y'; * var f = new F(); * R.toPairsIn(f); //=> [['x','X'], ['y','Y']] */ R.toPairsIn = pairWith(R.keysIn); /** * Returns a list of all the enumerable own properties of the supplied object. * Note that the order of the output array is not guaranteed across * different JS platforms. * * @func * @memberOf R * @category Object * @sig {k: v} -> [v] * @param {Object} obj The object to extract values from * @return {Array} An array of the values of the object's own properties * @example * * R.values({a: 1, b: 2, c: 3}); //=> [1, 2, 3] */ R.values = function _values(obj) { var props = keys(obj), length = props.length, vals = new Array(length); for (var idx = 0; idx < length; idx++) { vals[idx] = obj[props[idx]]; } return vals; }; /** * Returns a list of all the properties, including prototype properties, * of the supplied object. * Note that the order of the output array is not guaranteed to be * consistent across different JS platforms. * * @func * @memberOf R * @category Object * @sig {k: v} -> [v] * @param {Object} obj The object to extract values from * @return {Array} An array of the values of the object's own and prototype properties * @example * * var F = function() { this.x = 'X'; }; * F.prototype.y = 'Y'; * var f = new F(); * R.valuesIn(f); //=> ['X', 'Y'] */ R.valuesIn = function _valuesIn(obj) { var prop, vs = []; for (prop in obj) { vs.push(obj[prop]); } return vs; }; /** * Internal helper function for making a partial copy of an object * * @private * */ // TODO: document, even for internals... function pickWith(test, obj) { var copy = {}, props = keys(obj), prop, val; for (var idx = 0, len = props.length; idx < len; idx++) { prop = props[idx]; val = obj[prop]; if (test(val, prop, obj)) { copy[prop] = val; } } return copy; } /** * Returns a partial copy of an object containing only the keys specified. If the key does not exist, the * property is ignored. * * @func * @memberOf R * @category Object * @sig [k] -> {k: v} -> {k: v} * @param {Array} names an array of String propery names to copy onto a new object * @param {Object} obj The object to copy from * @return {Object} A new object with only properties from `names` on it. * @example * * R.pick(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4} * R.pick(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1} */ R.pick = curry2(function pick(names, obj) { return pickWith(function(val, key) { return contains(key, names); }, obj); }); /** * Returns a partial copy of an object omitting the keys specified. * * @func * @memberOf R * @category Object * @sig [k] -> {k: v} -> {k: v} * @param {Array} names an array of String propery names to omit from the new object * @param {Object} obj The object to copy from * @return {Object} A new object with properties from `names` not on it. * @example * * R.omit(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3} */ R.omit = curry2(function omit(names, obj) { return pickWith(function(val, key) { return !contains(key, names); }, obj); }); /** * Returns a partial copy of an object containing only the keys that * satisfy the supplied predicate. * * @func * @memberOf R * @category Object * @sig (v, k -> Boolean) -> {k: v} -> {k: v} * @param {Function} pred A predicate to determine whether or not a key * should be included on the output object. * @param {Object} obj The object to copy from * @return {Object} A new object with only properties that satisfy `pred` * on it. * @see R.pick * @example * * var isUpperCase = function(val, key) { return key.toUpperCase() === key; } * R.pickWith(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4} */ R.pickWith = curry2(pickWith); /** * Internal implementation of `pickAll` * * @private * @see R.pickAll */ // TODO: document, even for internals... var pickAll = function _pickAll(names, obj) { var copy = {}; forEach(function(name) { copy[name] = obj[name]; }, names); return copy; }; /** * Similar to `pick` except that this one includes a `key: undefined` pair for properties that don't exist. * * @func * @memberOf R * @category Object * @sig [k] -> {k: v} -> {k: v} * @param {Array} names an array of String propery names to copy onto a new object * @param {Object} obj The object to copy from * @return {Object} A new object with only properties from `names` on it. * @see R.pick * @example * * R.pickAll(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4} * R.pickAll(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, e: undefined, f: undefined} */ R.pickAll = curry2(pickAll); /** * Assigns own enumerable properties of the other object to the destination * object prefering items in other. * * @private * @memberOf R * @category Object * @param {Object} object The destination object. * @param {Object} other The other object to merge with destination. * @returns {Object} Returns the destination object. * @example * * extend({ 'name': 'fred', 'age': 10 }, { 'age': 40 }); * //=> { 'name': 'fred', 'age': 40 } */ function extend(destination, other) { var props = keys(other), idx = -1, length = props.length; while (++idx < length) { destination[props[idx]] = other[props[idx]]; } return destination; } /** * Create a new object with the own properties of a * merged with the own properties of object b. * This function will *not* mutate passed-in objects. * * @func * @memberOf R * @category Object * @sig {k: v} -> {k: v} -> {k: v} * @param {Object} a source object * @param {Object} b object with higher precendence in output * @returns {Object} Returns the destination object. * @example * * R.mixin({ 'name': 'fred', 'age': 10 }, { 'age': 40 }); * //=> { 'name': 'fred', 'age': 40 } */ R.mixin = curry2(function _mixin(a, b) { return extend(extend({}, a), b); }); /** * Creates a shallow copy of an object's own properties. * * @func * @memberOf R * @category Object * @sig {*} -> {*} * @param {Object} obj The object to clone * @returns {Object} A new object * @example * * R.cloneObj({a: 1, b: 2, c: [1, 2, 3]}); // {a: 1, b: 2, c: [1, 2, 3]} */ R.cloneObj = function(obj) { return extend({}, obj); }; /** * Reports whether two functions have the same value for the specified property. Useful as a curried predicate. * * @func * @memberOf R * @category Object * @sig k -> {k: v} -> {k: v} -> Boolean * @param {String} prop The name of the property to compare * @param {Object} obj1 * @param {Object} obj2 * @return {Boolean} * * @example * * var o1 = { a: 1, b: 2, c: 3, d: 4 }; * var o2 = { a: 10, b: 20, c: 3, d: 40 }; * R.eqProps('a', o1, o2); //=> false * R.eqProps('c', o1, o2); //=> true */ R.eqProps = curry3(function eqProps(prop, obj1, obj2) { return obj1[prop] === obj2[prop]; }); /** * internal helper for `where` * * @private * @see R.where */ function satisfiesSpec(spec, parsedSpec, testObj) { if (spec === testObj) { return true; } if (testObj == null) { return false; } parsedSpec.fn = parsedSpec.fn || []; parsedSpec.obj = parsedSpec.obj || []; var key, val, idx = -1, fnLen = parsedSpec.fn.length, j = -1, objLen = parsedSpec.obj.length; while (++idx < fnLen) { key = parsedSpec.fn[idx]; val = spec[key]; // if (!hasOwnProperty.call(testObj, key)) { // return false; // } if (!(key in testObj)) { return false; } if (!val(testObj[key], testObj)) { return false; } } while (++j < objLen) { key = parsedSpec.obj[j]; if (spec[key] !== testObj[key]) { return false; } } return true; } /** * Takes a spec object and a test object and returns true if the test satisfies the spec. * Any property on the spec that is not a function is interpreted as an equality * relation. * * If the spec has a property mapped to a function, then `where` evaluates the function, passing in * the test object's value for the property in question, as well as the whole test object. * * `where` is well suited to declarativley expressing constraints for other functions, e.g., * `filter`, `find`, `pickWith`, etc. * * @func * @memberOf R * @category Object * @sig {k: v} -> {k: v} -> Boolean * @param {Object} spec * @param {Object} testObj * @return {Boolean} * @example * * var spec = {x: 2}; * R.where(spec, {w: 10, x: 2, y: 300}); //=> true * R.where(spec, {x: 1, y: 'moo', z: true}); //=> false * * var spec2 = {x: function(val, obj) { return val + obj.y > 10; }}; * R.where(spec2, {x: 2, y: 7}); //=> false * R.where(spec2, {x: 3, y: 8}); //=> true * * var xs = [{x: 2, y: 1}, {x: 10, y: 2}, {x: 8, y: 3}, {x: 10, y: 4}]; * R.filter(R.where({x: 10}), xs); // ==> [{x: 10, y: 2}, {x: 10, y: 4}] */ R.where = function where(spec, testObj) { var parsedSpec = R.groupBy(function(key) { return typeof spec[key] === 'function' ? 'fn' : 'obj'; }, keys(spec)); switch (arguments.length) { case 0: throw NO_ARGS_EXCEPTION; case 1: return function(testObj) { return satisfiesSpec(spec, parsedSpec, testObj); }; } return satisfiesSpec(spec, parsedSpec, testObj); }; // Miscellaneous Functions // ----------------------- // // A few functions in need of a good home. // -------- /** * Expose the functions from ramda as properties of another object. * If the provided object is the global object then the ramda * functions become global functions. * Warning: This function *will* mutate the object provided. * * @func * @memberOf R * @category Object * @sig -> {*} -> {*} * @param {Object} obj The object to attach ramda functions * @return {Object} a reference to the mutated object * @example * * var x = {} * R.installTo(x); // x now contains ramda functions * R.installTo(this); // add ramda functions to `this` object */ R.installTo = function(obj) { return extend(obj, R); }; /** * See if an object (`val`) is an instance of the supplied constructor. * This function will check up the inheritance chain, if any. * * @func * @memberOf R * @category type * @sig (* -> {*}) -> a -> Boolean * @param {Object} ctor A constructor * @param {*} val The value to test * @return {Boolean} * @example * * R.is(Object, {}); //=> true * R.is(Number, 1); //=> true * R.is(Object, 1); //=> false * R.is(String, 's'); //=> true * R.is(String, new String('')); //=> true * R.is(Object, new String('')); //=> true * R.is(Object, 's'); //=> false * R.is(Number, {}); //=> false */ R.is = curry2(function is(ctor, val) { return val != null && val.constructor === ctor || val instanceof ctor; }); /** * A function that always returns `0`. Any passed in parameters are ignored. * * @func * @memberOf R * @category function * @sig * -> 0 * @see R.always * @return {Number} 0. Always zero. * @example * * R.alwaysZero(); //=> 0 */ R.alwaysZero = always(0); /** * A function that always returns `false`. Any passed in parameters are ignored. * * @func * @memberOf R * @category function * @sig * -> false * @see R.always * @return {Boolean} false * @example * * R.alwaysFalse(); //=> false */ R.alwaysFalse = always(false); /** * A function that always returns `true`. Any passed in parameters are ignored. * * @func * @memberOf R * @category function * @sig * -> true * @see R.always * @return {Boolean} true * @example * * R.alwaysTrue(); //=> true */ R.alwaysTrue = always(true); // Logic Functions // --------------- // // These functions are very simple wrappers around the built-in logical operators, useful in building up // more complex functional forms. // -------- /** * * A function wrapping calls to the two functions in an `&&` operation, returning `true` or `false`. Note that * this is short-circuited, meaning that the second function will not be invoked if the first returns a false-y * value. * * @func * @memberOf R * @category logic * @sig (*... -> Boolean) -> (*... -> Boolean) -> (*... -> Boolean) * @param {Function} f a predicate * @param {Function} g another predicate * @return {Function} a function that applies its arguments to `f` and `g` and ANDs their outputs together. * @example * * var gt10 = function(x) { return x > 10; }; * var even = function(x) { return x % 2 === 0 }; * var f = R.and(gt10, even); * f(100); //=> true * f(101); //=> false */ R.and = curry2(function and(f, g) { return function _and() { return !!(f.apply(this, arguments) && g.apply(this, arguments)); }; }); /** * A function wrapping calls to the two functions in an `||` operation, returning `true` or `false`. Note that * this is short-circuited, meaning that the second function will not be invoked if the first returns a truth-y * value. * * @func * @memberOf R * @category logic * @sig (*... -> Boolean) -> (*... -> Boolean) -> (*... -> Boolean) * @param {Function} f a predicate * @param {Function} g another predicate * @return {Function} a function that applies its arguments to `f` and `g` and ORs their outputs together. * @example * * var gt10 = function(x) { return x > 10; }; * var even = function(x) { return x % 2 === 0 }; * var f = R.or(gt10, even); * f(101); //=> true * f(8); //=> true */ R.or = curry2(function or(f, g) { return function _or() { return !!(f.apply(this, arguments) || g.apply(this, arguments)); }; }); /** * A function wrapping a call to the given function in a `!` operation. It will return `true` when the * underlying function would return a false-y value, and `false` when it would return a truth-y one. * * @func * @memberOf R * @category logic * @sig (*... -> Boolean) -> (*... -> Boolean) * @param {Function} f a predicate * @return {Function} a function that applies its arguments to `f` and logically inverts its output. * @example * * var gt10 = function(x) { return x > 10; }; * var f = R.not(gt10); * f(11); //=> false * f(9); //=> true */ var not = R.not = function _not(f) { return function() {return !f.apply(this, arguments);}; }; /** * Create a predicate wrapper which will call a pick function (all/any) for each predicate * * @private * @see R.every * @see R.some */ // TODO: document, even for internals... var predicateWrap = function _predicateWrap(predPicker) { return function(preds /* , args */) { var predIterator = function() { var args = arguments; return predPicker(function(predicate) { return predicate.apply(null, args); }, preds); }; return arguments.length > 1 ? // Call function imediately if given arguments predIterator.apply(null, _slice(arguments, 1)) : // Return a function which will call the predicates with the provided arguments arity(max(pluck('length', preds)), predIterator); }; }; /** * Given a list of predicates, returns a new predicate that will be true exactly when all of them are. * * @func * @memberOf R * @category logic * @sig [(*... -> Boolean)] -> (*... -> Boolean) * @param {Array} list An array of predicate functions * @param {*} optional Any arguments to pass into the predicates * @return {Function} a function that applies its arguments to each of * the predicates, returning `true` if all are satisfied. * @example * * var gt10 = function(x) { return x > 10; }; * var even = function(x) { return x % 2 === 0}; * var f = R.allPredicates([gt10, even]); * f(11); //=> false * f(12); //=> true */ R.allPredicates = predicateWrap(every); /** * Given a list of predicates returns a new predicate that will be true exactly when any one of them is. * * @func * @memberOf R * @category logic * @sig [(*... -> Boolean)] -> (*... -> Boolean) * @param {Array} list An array of predicate functions * @param {*} optional Any arguments to pass into the predicates * @return {Function} a function that applies its arguments to each of the predicates, returning * `true` if all are satisfied.. * @example * * var gt10 = function(x) { return x > 10; }; * var even = function(x) { return x % 2 === 0}; * var f = R.anyPredicates([gt10, even]); * f(11); //=> true * f(8); //=> true * f(9); //=> false */ R.anyPredicates = predicateWrap(some); // Arithmetic Functions // -------------------- // // These functions wrap up the certain core arithmetic operators // -------- /** * Adds two numbers (or strings). Equivalent to `a + b` but curried. * * @func * @memberOf R * @category math * @sig Number -> Number -> Number * @sig String -> String -> String * @param {number|string} a The first value. * @param {number|string} b The second value. * @return {number|string} The result of `a + b`. * @example * * var increment = R.add(1); * increment(10); //=> 11 * R.add(2, 3); //=> 5 * R.add(7)(10); //=> 17 */ var add = R.add = curry2(function _add(a, b) { return a + b; }); /** * Multiplies two numbers. Equivalent to `a * b` but curried. * * @func * @memberOf R * @category math * @sig Number -> Number -> Number * @param {number} a The first value. * @param {number} b The second value. * @return {number} The result of `a * b`. * @example * * var double = R.multiply(2); * var triple = R.multiply(3); * double(3); //=> 6 * triple(4); //=> 12 * R.multiply(2, 5); //=> 10 */ var multiply = R.multiply = curry2(function _multiply(a, b) { return a * b; }); /** * Subtracts two numbers. Equivalent to `a - b` but curried. * * @func * @memberOf R * @category math * @sig Number -> Number -> Number * @param {number} a The first value. * @param {number} b The second value. * @return {number} The result of `a - b`. * @note Operator: this is right-curried by default, but can be called via sections * @example * * R.subtract(10, 8); //=> 2 * * var minus5 = R.subtract(5); * minus5(17); //=> 12 * * // note: In this example, `_` is just an `undefined` value. You could use `void 0` instead * var complementaryAngle = R.subtract(90, _); * complementaryAngle(30); //=> 60 * complementaryAngle(72); //=> 18 */ R.subtract = op(function _subtract(a, b) { return a - b; }); /** * Divides two numbers. Equivalent to `a / b`. * While at times the curried version of `divide` might be useful, * probably the curried version of `divideBy` will be more useful. * * @func * @memberOf R * @category math * @sig Number -> Number -> Number * @param {number} a The first value. * @param {number} b The second value. * @return {number} The result of `a / b`. * @note Operator: this is right-curried by default, but can be called via sections * @example * * R.divide(71, 100); //=> 0.71 * * // note: In this example, `_` is just an `undefined` value. You could use `void 0` instead * var half = R.divide(2); * half(42); //=> 21 * * var reciprocal = R.divide(1, _); * reciprocal(4); //=> 0.25 */ R.divide = op(function _divide(a, b) { return a / b; }); /** * Divides the second parameter by the first and returns the remainder. * Note that this functions preserves the JavaScript-style behavior for * modulo. For mathematical modulo see `mathMod` * * @func * @memberOf R * @category math * @sig Number -> Number -> Number * @param {number} a The value to the divide. * @param {number} b The pseudo-modulus * @return {number} The result of `b % a`. * @note Operator: this is right-curried by default, but can be called via sections * @see R.mathMod * @example * * R.modulo(17, 3); //=> 2 * // JS behavior: * R.modulo(-17, 3); //=> -2 * R.modulo(17, -3); //=> 2 * * var isOdd = R.modulo(2); * isOdd(42); //=> 0 * isOdd(21); //=> 1 */ R.modulo = op(function _modulo(a, b) { return a % b; }); /** * Determine if the passed argument is an integer. * * @private * @param {*} n * @category type * @return {Boolean} */ // TODO: document, even for internals... var isInteger = Number.isInteger || function isInteger(n) { return (n << 0) === n; }; /** * mathMod behaves like the modulo operator should mathematically, unlike the `%` * operator (and by extension, R.modulo). So while "-17 % 5" is -2, * mathMod(-17, 5) is 3. mathMod requires Integer arguments, and returns NaN * when the modulus is zero or negative. * * @func * @memberOf R * @category math * @sig Number -> Number -> Number * @param {number} m The dividend. * @param {number} p the modulus. * @return {number} The result of `b mod a`. * @see R.moduloBy * @example * * R.mathMod(-17, 5); //=> 3 * R.mathMod(17, 5); //=> 2 * R.mathMod(17, -5); //=> NaN * R.mathMod(17, 0); //=> NaN * R.mathMod(17.2, 5); //=> NaN * R.mathMod(17, 5.3); //=> NaN * * var clock = R.mathMod(12); * clock(15); //=> 3 * clock(24); //=> 0 * * // note: In this example, `_` is just an `undefined` value. You could use `void 0` instead * var seventeenMod = R.mathMod(17, _); * seventeenMod(3); //=> 2 * seventeenMod(4); //=> 1 * seventeenMod(10); //=> 7 */ R.mathMod = op(function _mathMod(m, p) { if (!isInteger(m)) { return NaN; } if (!isInteger(p) || p < 1) { return NaN; } return ((m % p) + p) % p; }); /** * Adds together all the elements of a list. * * @func * @memberOf R * @category math * @sig [Number] -> Number * @param {Array} list An array of numbers * @return {number} The sum of all the numbers in the list. * @see reduce * @example * * R.sum([2,4,6,8,100,1]); //=> 121 */ R.sum = foldl(add, 0); /** * Multiplies together all the elements of a list. * * @func * @memberOf R * @category math * @sig [Number] -> Number * @param {Array} list An array of numbers * @return {number} The product of all the numbers in the list. * @see reduce * @example * * R.product([2,4,6,8,100,1]); //=> 38400 */ R.product = foldl(multiply, 1); /** * Returns true if the first parameter is less than the second. * * @func * @memberOf R * @category math * @sig Number -> Number -> Boolean * @param {Number} a * @param {Number} b * @return {Boolean} a < b * @note Operator: this is right-curried by default, but can be called via sections * @example * * R.lt(2, 6); //=> true * R.lt(2, 0); //=> false * R.lt(2, 2); //=> false * R.lt(5)(10); //=> false // default currying is right-sectioned * R.lt(5, _)(10); //=> true // left-sectioned currying */ R.lt = op(function _lt(a, b) { return a < b; }); /** * Returns true if the first parameter is less than or equal to the second. * * @func * @memberOf R * @category math * @sig Number -> Number -> Boolean * @param {Number} a * @param {Number} b * @return {Boolean} a <= b * @note Operator: this is right-curried by default, but can be called via sections * @example * * R.lte(2, 6); //=> true * R.lte(2, 0); //=> false * R.lte(2, 2); //=> true */ R.lte = op(function _lte(a, b) { return a <= b; }); /** * Returns true if the first parameter is greater than the second. * * @func * @memberOf R * @category math * @sig Number -> Number -> Boolean * @param {Number} a * @param {Number} b * @return {Boolean} a > b * @note Operator: this is right-curried by default, but can be called via sections * @example * * R.gt(2, 6); //=> false * R.gt(2, 0); //=> true * R.gt(2, 2); //=> false */ R.gt = op(function _gt(a, b) { return a > b; }); /** * Returns true if the first parameter is greater than or equal to the second. * * @func * @memberOf R * @category math * @sig Number -> Number -> Boolean * @param {Number} a * @param {Number} b * @return {Boolean} a >= b * @note Operator: this is right-curried by default, but can be called via sections * @example * * R.gte(2, 6); //=> false * R.gte(2, 0); //=> true * R.gte(2, 2); //=> true */ R.gte = op(function _gte(a, b) { return a >= b; }); /** * Determines the largest of a list of numbers (or elements that can be cast to numbers) * * @func * @memberOf R * @category math * @sig [Number] -> Number * @see R.maxWith * @param {Array} list A list of numbers * @return {Number} The greatest number in the list * @example * * R.max([7, 3, 9, 2, 4, 9, 3]); //=> 9 */ var max = R.max = function _max(list) { return foldl(binary(Math.max), -Infinity, list); }; /** * Determines the largest of a list of items as determined by pairwise comparisons from the supplied comparator * * @func * @memberOf R * @category math * @sig (a -> Number) -> [a] -> a * @param {Function} keyFn A comparator function for elements in the list * @param {Array} list A list of comparable elements * @return {*} The greatest element in the list. `undefined` if the list is empty. * @see R.max * @example * * function cmp(obj) { return obj.x; } * var a = {x: 1}, b = {x: 2}, c = {x: 3}; * R.maxWith(cmp, [a, b, c]); //=> {x: 3} */ R.maxWith = curry2(function _maxWith(keyFn, list) { if (!(list && list.length > 0)) { return; } var idx = 0, winner = list[idx], max = keyFn(winner), testKey; while (++idx < list.length) { testKey = keyFn(list[idx]); if (testKey > max) { max = testKey; winner = list[idx]; } } return winner; }); /** * Determines the smallest of a list of numbers (or elements that can be cast to numbers) * * @func * @memberOf R * @category math * @sig [Number] -> Number * @param {Array} list A list of numbers * @return {Number} The greatest number in the list * @see R.minWith * @example * * R.min([7, 3, 9, 2, 4, 9, 3]); //=> 2 */ R.min = function _min(list) { return foldl(binary(Math.min), Infinity, list); }; /** * Determines the smallest of a list of items as determined by pairwise comparisons from the supplied comparator * * @func * @memberOf R * @category math * @sig (a -> Number) -> [a] -> a * @param {Function} keyFn A comparator function for elements in the list * @param {Array} list A list of comparable elements * @see R.min * @return {*} The greatest element in the list. `undefined` if the list is empty. * @example * * function cmp(obj) { return obj.x; } * var a = {x: 1}, b = {x: 2}, c = {x: 3}; * R.minWith(cmp, [a, b, c]); //=> {x: 1} */ // TODO: combine this with maxWith? R.minWith = curry2(function _minWith(keyFn, list) { if (!(list && list.length > 0)) { return; } var idx = 0, winner = list[idx], min = keyFn(list[idx]), testKey; while (++idx < list.length) { testKey = keyFn(list[idx]); if (testKey < min) { min = testKey; winner = list[idx]; } } return winner; }); // String Functions // ---------------- // // Much of the String.prototype API exposed as simple functions. // -------- /** * returns a subset of a string between one index and another. * * @func * @memberOf R * @category string * @sig Number -> Number -> String -> String * @param {Number} indexA An integer between 0 and the length of the string. * @param {Number} indexB An integer between 0 and the length of the string. * @param {String} The string to extract from * @return {String} the extracted substring * @see R.invoker * @example * * R.substring(2, 5, 'abcdefghijklm'); //=> 'cde' */ var substring = R.substring = invoker('substring', String.prototype); /** * The trailing substring of a String starting with the nth character: * * @func * @memberOf R * @category string * @sig Number -> String -> String * @param {Number} indexA An integer between 0 and the length of the string. * @param {String} The string to extract from * @return {String} the extracted substring * @see R.invoker * @example * * R.substringFrom(8, 'abcdefghijklm'); //=> 'ijklm' */ R.substringFrom = flip(substring)(void 0); /** * The leading substring of a String ending before the nth character: * * @func * @memberOf R * @category string * @sig Number -> String -> String * @param {Number} indexA An integer between 0 and the length of the string. * @param {String} The string to extract from * @return {String} the extracted substring * @see R.invoker * @example * * R.substringTo(8, 'abcdefghijklm'); //=> 'abcdefgh' */ R.substringTo = substring(0); /** * The character at the nth position in a String: * * @func * @memberOf R * @category string * @sig Number -> String -> String * @param {Number} index An integer between 0 and the length of the string. * @param {String} str The string to extract a char from * @return {String} the character at `index` of `str` * @see R.invoker * @example * * R.charAt(8, 'abcdefghijklm'); //=> 'i' */ R.charAt = invoker('charAt', String.prototype); /** * The ascii code of the character at the nth position in a String: * * @func * @memberOf R * @category string * @sig Number -> String -> Number * @param {Number} index An integer between 0 and the length of the string. * @param {String} str The string to extract a charCode from * @return {Number} the code of the character at `index` of `str` * @see R.invoker * @example * * R.charCodeAt(8, 'abcdefghijklm'); //=> 105 * // (... 'a' ~ 97, 'b' ~ 98, ... 'i' ~ 105) */ R.charCodeAt = invoker('charCodeAt', String.prototype); /** * Tests a regular expression agains a String * * @func * @memberOf R * @category string * @sig RegExp -> String -> [String] | null * @param {RegExp} rx A regular expression. * @param {String} str The string to match against * @return {Array} The list of matches, or null if no matches found * @see R.invoker * @example * * R.match(/([a-z]a)/g, 'bananas'); //=> ['ba', 'na', 'na'] */ R.match = invoker('match', String.prototype); /** * Finds the first index of a substring in a string, returning -1 if it's not present * * @func * @memberOf R * @category string * @sig String -> String -> Number * @param {String} c A string to find. * @param {String} str The string to search in * @return {Number} The first index of `c` or -1 if not found * @see R.invoker * @example * * R.strIndexOf('c', 'abcdefg'); //=> 2 */ R.strIndexOf = curry2(function _strIndexOf(c, str) { return str.indexOf(c); }); /** * * Finds the last index of a substring in a string, returning -1 if it's not present * * @func * @memberOf R * @category string * @sig String -> String -> Number * @param {String} c A string to find. * @param {String} str The string to search in * @return {Number} The last index of `c` or -1 if not found * @see R.invoker * @example * * R.strLastIndexOf('a', 'banana split'); //=> 5 */ R.strLastIndexOf = curry2(function(c, str) { return str.lastIndexOf(c); }); /** * The upper case version of a string. * * @func * @memberOf R * @category string * @sig String -> String * @param {string} str The string to upper case. * @return {string} The upper case version of `str`. * @example * * R.toUpperCase('abc'); //=> 'ABC' */ R.toUpperCase = invoker('toUpperCase', String.prototype); /** * The lower case version of a string. * * @func * @memberOf R * @category string * @sig String -> String * @param {string} str The string to lower case. * @return {string} The lower case version of `str`. * @example * * R.toLowerCase('XYZ'); //=> 'xyz' */ R.toLowerCase = invoker('toLowerCase', String.prototype); /** * Splits a string into an array of strings based on the given * separator. * * @func * @memberOf R * @category string * @sig String -> String -> [String] * @param {string} sep The separator string. * @param {string} str The string to separate into an array. * @return {Array} The array of strings from `str` separated by `str`. * @example * * var pathComponents = R.split('/'); * R.tail(pathComponents('/usr/local/bin/node')); //=> ['usr', 'local', 'bin', 'node'] * * R.split('.', 'a.b.c.xyz.d'); //=> ['a', 'b', 'c', 'xyz', 'd'] */ R.split = invoker('split', String.prototype, 1); /** * internal path function * Takes an array, paths, indicating the deep set of keys * to find. * * @private * @memberOf R * @category string * @param {Array} paths An array of strings to map to object properties * @param {Object} obj The object to find the path in * @return {Array} The value at the end of the path or `undefined`. * @example * * path(['a', 'b'], {a: {b: 2}}); //=> 2 */ function path(paths, obj) { var idx = -1, length = paths.length, val; if (obj == null) { return; } val = obj; while (val != null && ++idx < length) { val = val[paths[idx]]; } return val; } /** * Retrieve a nested path on an object seperated by the specified * separator value. * * @func * @memberOf R * @category string * @sig String -> String -> {*} -> * * @param {string} sep The separator to use in `path`. * @param {string} path The path to use. * @return {*} The data at `path`. * @example * * R.pathOn('/', 'a/b/c', {a: {b: {c: 3}}}); //=> 3 */ R.pathOn = curry3(function pathOn(sep, str, obj) { return path(str.split(sep), obj); }); /** * Retrieve a nested path on an object seperated by periods * * @func * @memberOf R * @category string * @sig String -> {*} -> * * @param {string} path The dot path to use. * @return {*} The data at `path`. * @example * * R.path('a.b', {a: {b: 2}}); //=> 2 */ R.path = R.pathOn('.'); // Data Analysis and Grouping Functions // ------------------------------------ // // Functions performing SQL-like actions on lists of objects. These do // not have any SQL-like optimizations performed on them, however. // -------- /** * Reasonable analog to SQL `select` statement. * * @func * @memberOf R * @category object * @category relation * @string [k] -> [{k: v}] -> [{k: v}] * @param {Array} props The property names to project * @param {Array} objs The objects to query * @return {Array} An array of objects with just the `props` properties. * @example * * var abby = {name: 'Abby', age: 7, hair: 'blond', grade: 2}; * var fred = {name: 'Fred', age: 12, hair: 'brown', grade: 7}; * var kids = [abby, fred]; * R.project(['name', 'grade'], kids); //=> [{name: 'Abby', grade: 2}, {name: 'Fred', grade: 7}] */ R.project = useWith(map, R.pickAll, identity); // passing `identity` gives correct arity /** * Determines whether the given property of an object has a specific * value according to strict equality (`===`). Most likely used to * filter a list: * * @func * @memberOf R * @category relation * @sig k -> v -> {k: v} -> Boolean * @param {string|number} name The property name (or index) to use. * @param {*} val The value to compare the property with. * @return {boolean} `true` if the properties are equal, `false` otherwise. * @example * * var abby = {name: 'Abby', age: 7, hair: 'blond'}; * var fred = {name: 'Fred', age: 12, hair: 'brown'}; * var rusty = {name: 'Rusty', age: 10, hair: 'brown'}; * var alois = {name: 'Alois', age: 15, disposition: 'surly'}; * var kids = [abby, fred, rusty, alois]; * var hasBrownHair = R.propEq('hair', 'brown'); * R.filter(hasBrownHair, kids); //=> [fred, rusty] */ R.propEq = curry3(function propEq(name, val, obj) { return obj[name] === val; }); /** * Combines two lists into a set (i.e. no duplicates) composed of the * elements of each list. * * @func * @memberOf R * @category relation * @sig [a] -> [a] -> [a] * @param {Array} as The first list. * @param {Array} bs The second list. * @return {Array} The first and second lists concatenated, with * duplicates removed. * @example * * R.union([1, 2, 3], [2, 3, 4]); //=> [1, 2, 3, 4] */ R.union = compose(uniq, R.concat); /** * Combines two lists into a set (i.e. no duplicates) composed of the elements of each list. Duplication is * determined according to the value returned by applying the supplied predicate to two list elements. * * @func * @memberOf R * @category relation * @sig (a,a -> Boolean) -> [a] -> [a] -> [a] * @param {Function} pred * @param {Array} list1 The first list. * @param {Array} list2 The second list. * @return {Array} The first and second lists concatenated, with * duplicates removed. * @see R.union * @example * * function cmp(x, y) { return x.a === y.a; } * var l1 = [{a: 1}, {a: 2}]; * var l2 = [{a: 1}, {a: 4}]; * R.unionWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}, {a: 4}] */ R.unionWith = curry3(function _unionWith(pred, list1, list2) { return uniqWith(pred, concat(list1, list2)); }); /** * Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list. * * @func * @memberOf R * @category relation * @sig [a] -> [a] -> [a] * @param {Array} list1 The first list. * @param {Array} list2 The second list. * @return {Array} The elements in `list1` that are not in `list2` * @see R.differenceWith * @example * * R.difference([1,2,3,4], [7,6,5,4,3]); //=> [1,2] * R.difference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5] */ R.difference = curry2(function _difference(first, second) { return uniq(reject(flip(contains)(second), first)); }); /** * Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list. * Duplication is determined according to the value returned by applying the supplied predicate to two list * elements. * * @func * @memberOf R * @category relation * @sig (a,a -> Boolean) -> [a] -> [a] -> [a] * @param {Function} pred * @param {Array} list1 The first list. * @param {Array} list2 The second list. * @see R.difference * @return {Array} The elements in `list1` that are not in `list2` * @example * * function cmp(x, y) { return x.a === y.a; } * var l1 = [{a: 1}, {a: 2}, {a: 3}]; * var l2 = [{a: 3}, {a: 4}]; * R.differenceWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}] * */ R.differenceWith = curry3(function differenceWith(pred, first, second) { return uniqWith(pred)(reject(flip(R.containsWith(pred))(second), first)); }); /** * Combines two lists into a set (i.e. no duplicates) composed of those elements common to both lists. * * @func * @memberOf R * @category relation * @sig [a] -> [a] -> [a] * @param {Array} list1 The first list. * @param {Array} list2 The second list. * @see R.intersectionWith * @return {Array} The list of elements found in both `list1` and `list2` * @example * * R.intersection([1,2,3,4], [7,6,5,4,3]); //=> [4, 3] */ R.intersection = curry2(function intersection(list1, list2) { return uniq(filter(flip(contains)(list1), list2)); }); /** * Combines two lists into a set (i.e. no duplicates) composed of those * elements common to both lists. Duplication is determined according * to the value returned by applying the supplied predicate to two list * elements. * * @func * @memberOf R * @category relation * @sig (a,a -> Boolean) -> [a] -> [a] -> [a] * @param {Function} pred A predicate function that determines whether * the two supplied elements are equal. * Signatrue: a -> a -> Boolean * @param {Array} list1 One list of items to compare * @param {Array} list2 A second list of items to compare * @see R.intersection * @return {Array} A new list containing those elements common to both lists. * @example * * var buffaloSpringfield = [ * {id: 824, name: 'Richie Furay'}, * {id: 956, name: 'Dewey Martin'}, * {id: 313, name: 'Bruce Palmer'}, * {id: 456, name: 'Stephen Stills'}, * {id: 177, name: 'Neil Young'} * ]; * var csny = [ * {id: 204, name: 'David Crosby'}, * {id: 456, name: 'Stephen Stills'}, * {id: 539, name: 'Graham Nash'}, * {id: 177, name: 'Neil Young'} * ]; * * var sameId = function(o1, o2) {return o1.id === o2.id;}; * * R.intersectionWith(sameId, buffaloSpringfield, csny); * //=> [{id: 456, name: 'Stephen Stills'}, {id: 177, name: 'Neil Young'}] */ R.intersectionWith = curry3(function intersectionWith(pred, list1, list2) { var results = [], idx = -1; while (++idx < list1.length) { if (containsWith(pred, list1[idx], list2)) { results[results.length] = list1[idx]; } } return uniqWith(pred, results); }); /** * Creates a new list whose elements each have two properties: `val` is * the value of the corresponding item in the list supplied, and `key` * is the result of applying the supplied function to that item. * * @private * @func * @memberOf R * @category relation * @param {Function} fn An arbitrary unary function returning a potential * object key. Signature: Any -> String * @param {Array} list The list of items to process * @return {Array} A new list with the described structure. * @example * * var people = [ * {first: 'Fred', last: 'Flintstone', age: 23}, * {first: 'Betty', last: 'Rubble', age: 21}, * {first: 'George', last: 'Jetson', age: 29} * ]; * * var fullName = function(p) {return p.first + ' ' + p.last;}; * * keyValue(fullName, people); //=> * // [ * // { * // key: 'Fred Flintstone', * // val: {first: 'Fred', last: 'Flintstone', age: 23} * // }, { * // key: 'Betty Rubble', * // val: {first: 'Betty', last: 'Rubble', age: 21} * // }, { * // key: 'George Jetson', * // val: {first: 'George', last: 'Jetson', age: 29} * // } * // ]; */ function keyValue(fn, list) { // TODO: Should this be made public? return map(function(item) {return {key: fn(item), val: item};}, list); } /** * Sorts the list according to a key generated by the supplied function. * * @func * @memberOf R * @category relation * @sig (a -> String) -> [a] -> [a] * @param {Function} fn The function mapping `list` items to keys. * @param {Array} list The list to sort. * @return {Array} A new list sorted by the keys generated by `fn`. * @example * * var sortByFirstItem = R.sortBy(prop(0)); * var sortByNameCaseInsensitive = R.sortBy(compose(R.toLowerCase, prop('name'))); * var pairs = [[-1, 1], [-2, 2], [-3, 3]]; * sortByFirstItem(pairs); //=> [[-3, 3], [-2, 2], [-1, 1]] * var alice = { * name: 'ALICE', * age: 101 * }; * var bob = { * name: 'Bob', * age: -10 * }; * var clara = { * name: 'clara', * age: 314.159 * }; * var people = [clara, bob, alice]; * sortByNameCaseInsensitive(people); //=> [alice, bob, clara] */ R.sortBy = curry2(function sortBy(fn, list) { return pluck('val', keyValue(fn, list).sort(comparator(function(a, b) {return a.key < b.key;}))); }); /** * Counts the elements of a list according to how many match each value * of a key generated by the supplied function. Returns an object * mapping the keys produced by `fn` to the number of occurrences in * the list. Note that all keys are coerced to strings because of how * JavaScript objects work. * * @func * @memberOf R * @category relation * @sig (a -> String) -> [a] -> {*} * @param {Function} fn The function used to map values to keys. * @param {Array} list The list to count elements from. * @return {Object} An object mapping keys to number of occurrences in the list. * @example * * var numbers = [1.0, 1.1, 1.2, 2.0, 3.0, 2.2]; * var letters = R.split('', 'abcABCaaaBBc'); * R.countBy(Math.floor)(numbers); //=> {'1': 3, '2': 2, '3': 1} * R.countBy(R.toLowerCase)(letters); //=> {'a': 5, 'b': 4, 'c': 3} */ R.countBy = curry2(function countBy(fn, list) { return foldl(function(counts, obj) { counts[obj.key] = (counts[obj.key] || 0) + 1; return counts; }, {}, keyValue(fn, list)); }); /** * @private * @param {Function} fn The strategy for extracting function names from an object * @return {Function} A function that takes an object and returns an array of function names * */ var functionsWith = function(fn) { return function(obj) { return R.filter(function(key) { return typeof obj[key] === 'function'; }, fn(obj)); }; }; /** * Returns a list of function names of object's own functions * * @func * @memberOf R * @category Object * @sig {*} -> [String] * @param {Object} obj The objects with functions in it * @return {Array} returns a list of the object's own properites that map to functions * @example * * R.functions(R); // returns list of ramda's own function names * * var F = function() { this.x = function(){}; this.y = 1; } * F.prototype.z = function() {}; * F.prototype.a = 100; * R.functions(new F()); //=> ["x"] */ R.functions = functionsWith(R.keys); /** * Returns a list of function names of object's own and prototype functions * * @func * @memberOf R * @category Object * @sig {*} -> [String] * @param {Object} obj The objects with functions in it * @return {Array} returns a list of the object's own properites and prototype * properties that map to functions * @example * * R.functionsIn(R); // returns list of ramda's own and prototype function names * * var F = function() { this.x = function(){}; this.y = 1; } * F.prototype.z = function() {}; * F.prototype.a = 100; * R.functionsIn(new F()); //=> ["x", "z"] */ R.functionsIn = functionsWith(R.keysIn); // All the functional goodness, wrapped in a nice little package, just for you! return R; }));
neveldo/cdnjs
ajax/libs/ramda/0.5.0/ramda.js
JavaScript
mit
171,861
# # Cookbook Name:: apache2 # Recipe:: authz_groupfile # # Copyright 2008-2013, Opscode, 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. # apache_module 'authz_groupfile'
3ofcoins/idk-repo
vendor/cookbooks/apache2/recipes/mod_authz_groupfile.rb
Ruby
apache-2.0
675
/* TabularData.java -- Tables of composite data structures. Copyright (C) 2006, 2007 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package javax.management.openmbean; import java.util.Collection; import java.util.Set; /** * Provides an interface to a specific type of composite * data structure, where keys (the columns) map to the * {@link CompositeData} objects that form the rows of * the table. * * @author Andrew John Hughes (gnu_andrew@member.fsf.org) * @since 1.5 */ public interface TabularData { /** * Calculates the index the specified {@link CompositeData} value * would have, if it was to be added to this {@link TabularData} * instance. This method includes a check that the type of the * given value is the same as the row type of this instance, but not * a check for existing instances of the given value. The value * must also not be <code>null</code>. Possible indices are * returned by the {@link TabularType#getIndexNames()} method of * this instance's tabular type. The returned indices are the * values of the fields in the supplied {@link CompositeData} * instance that match the names given in the {@link TabularType}. * * @param val the {@link CompositeData} value whose index should * be calculated. * @return the index the value would take on, if it were to be added. * @throws NullPointerException if the value is <code>null</code>. * @throws InvalidOpenTypeException if the value does not match the * row type of this instance. */ Object[] calculateIndex(CompositeData val); /** * Removes all {@link CompositeData} values from the table. */ void clear(); /** * Returns true iff this instance of the {@link TabularData} class * contains a {@link CompositeData} value at the specified index. * In any other circumstance, including if the given key * is <code>null</code> or of the incorrect type, according to * the {@link TabularType} of this instance, this method returns * false. * * @param key the key to test for. * @return true if the key maps to a {@link CompositeData} value. */ boolean containsKey(Object[] key); /** * Returns true iff this instance of the {@link TabularData} class * contains the specified {@link CompositeData} value. * In any other circumstance, including if the given value * is <code>null</code> or of the incorrect type, according to * the {@link TabularType} of this instance, this method returns * false. * * @param val the value to test for. * @return true if the value exists. */ boolean containsValue(CompositeData val); /** * Compares the specified object with this object for equality. * The object is judged equivalent if it is non-null, and also * an instance of {@link TabularData} with the same row type, * and {@link CompositeData} values. The two compared instances may * be equivalent even if they represent different implementations * of {@link TabularData}. * * @param obj the object to compare for equality. * @return true if <code>obj</code> is equal to <code>this</code>. */ boolean equals(Object obj); /** * Retrieves the {@link CompositeData} value for the specified * key, or <code>null</code> if no such mapping exists. * * @param key the key whose value should be returned. * @return the matching {@link CompositeData} value, or * <code>null</code> if one does not exist. * @throws NullPointerException if the key is <code>null</code>. * @throws InvalidKeyException if the key does not match * the {@link TabularType} of this * instance. */ CompositeData get(Object[] key); /** * Returns the tabular type which corresponds to this instance * of {@link TabularData}. * * @return the tabular type for this instance. */ TabularType getTabularType(); /** * Returns the hash code of the composite data type. This is * computed as the sum of the hash codes of each value, together * with the hash code of the tabular type. These are the same * elements of the type that are compared as part of the {@link * #equals(java.lang.Object)} method, thus ensuring that the * hashcode is compatible with the equality test. * * @return the hash code of this instance. */ int hashCode(); /** * Returns true if this {@link TabularData} instance * contains no {@link CompositeData} values. * * @return true if the instance is devoid of rows. */ boolean isEmpty(); /** * Returns a {@link java.util.Set} view of the keys or * indices of this {@link TabularData} instance. * * @return a set containing the keys of this instance. */ Set<?> keySet(); /** * Adds the specified {@link CompositeData} value to the * table. The value must be non-null, of the same type * as the row type of this instance, and must not have * the same index as an existing value. The index is * calculated using the index names of the * {@link TabularType} for this instance. * * @param val the {@link CompositeData} value to add. * @throws NullPointerException if <code>val</code> is * <code>null</code>. * @throws InvalidOpenTypeException if the type of the * given value does not * match the row type. * @throws KeyAlreadyExistsException if the value has the * same calculated index * as an existing value. */ void put(CompositeData val); /** * Adds each of the specified {@link CompositeData} values * to the table. Each element of the array must meet the * conditions given for the {@link #put(CompositeData)} * method. In addition, the index of each value in the * array must be distinct from the index of the other * values in the array, as well as from the existing values * in the table. The operation should be atomic; if one * value can not be added, then none of the values should * be. If the array is <code>null</code> or empty, the * method simply returns. * * @param vals the {@link CompositeData} values to add. * @throws NullPointerException if a value from the array is * <code>null</code>. * @throws InvalidOpenTypeException if the type of a * given value does not * match the row type. * @throws KeyAlreadyExistsException if a value has the * same calculated index * as an existing value or * of one of the other * specified values. */ void putAll(CompositeData[] vals); /** * Removes the {@link CompositeData} value located at the * specified index. <code>null</code> is returned if the * value does not exist. Otherwise, the removed value is * returned. * * @param key the key of the value to remove. * @return the removed value, or <code>null</code> if * there is no value for the given key. * @throws NullPointerException if the key is <code>null</code>. * @throws InvalidOpenTypeException if the key does not match * the {@link TabularType} of this * instance. */ CompositeData remove(Object[] key); /** * Returns the number of {@link CompositeData} values or rows * in the table. * * @return the number of rows in the table. */ int size(); /** * Returns a textual representation of this instance. The * exact format is left up to the implementation, but it * should contain the name of the implementing class and * the tabular type. * * @return a {@link java.lang.String} representation of the * object. */ String toString(); /** * Returns the values associated with this instance. * * @return the values of this instance. */ Collection<?> values(); }
SanDisk-Open-Source/SSD_Dashboard
uefi/gcc/gcc-4.6.3/libjava/classpath/javax/management/openmbean/TabularData.java
Java
gpl-2.0
9,916
/* Copyright (c) 2010, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 3.3.0 build: 3167 */ YUI.add('dataschema-json', function(Y) { /** * Provides a DataSchema implementation which can be used to work with JSON data. * * @module dataschema * @submodule dataschema-json */ /** * JSON subclass for the DataSchema Utility. * @class DataSchema.JSON * @extends DataSchema.Base * @static */ var LANG = Y.Lang, SchemaJSON = { ///////////////////////////////////////////////////////////////////////////// // // DataSchema.JSON static methods // ///////////////////////////////////////////////////////////////////////////// /** * Utility function converts JSON locator strings into walkable paths * * @method DataSchema.JSON.getPath * @param locator {String} JSON value locator. * @return {String[]} Walkable path to data value. * @static */ getPath: function(locator) { var path = null, keys = [], i = 0; if (locator) { // Strip the ["string keys"] and [1] array indexes locator = locator. replace(/\[(['"])(.*?)\1\]/g, function (x,$1,$2) {keys[i]=$2;return '.@'+(i++);}). replace(/\[(\d+)\]/g, function (x,$1) {keys[i]=parseInt($1,10)|0;return '.@'+(i++);}). replace(/^\./,''); // remove leading dot // Validate against problematic characters. if (!/[^\w\.\$@]/.test(locator)) { path = locator.split('.'); for (i=path.length-1; i >= 0; --i) { if (path[i].charAt(0) === '@') { path[i] = keys[parseInt(path[i].substr(1),10)]; } } } else { } } return path; }, /** * Utility function to walk a path and return the value located there. * * @method DataSchema.JSON.getLocationValue * @param path {String[]} Locator path. * @param data {String} Data to traverse. * @return {Object} Data value at location. * @static */ getLocationValue: function (path, data) { var i = 0, len = path.length; for (;i<len;i++) { if( LANG.isObject(data) && (path[i] in data) ) { data = data[path[i]]; } else { data = undefined; break; } } return data; }, /** * Applies a given schema to given JSON data. * * @method apply * @param schema {Object} Schema to apply. * @param data {Object} JSON data. * @return {Object} Schema-parsed data. * @static */ apply: function(schema, data) { var data_in = data, data_out = {results:[],meta:{}}; // Convert incoming JSON strings if(!LANG.isObject(data)) { try { data_in = Y.JSON.parse(data); } catch(e) { data_out.error = e; return data_out; } } if(LANG.isObject(data_in) && schema) { // Parse results data if(!LANG.isUndefined(schema.resultListLocator)) { data_out = SchemaJSON._parseResults.call(this, schema, data_in, data_out); } // Parse meta data if(!LANG.isUndefined(schema.metaFields)) { data_out = SchemaJSON._parseMeta(schema.metaFields, data_in, data_out); } } else { data_out.error = new Error("JSON schema parse failure"); } return data_out; }, /** * Schema-parsed list of results from full data * * @method _parseResults * @param schema {Object} Schema to parse against. * @param json_in {Object} JSON to parse. * @param data_out {Object} In-progress parsed data to update. * @return {Object} Parsed data object. * @static * @protected */ _parseResults: function(schema, json_in, data_out) { var results = [], path, error; if(schema.resultListLocator) { path = SchemaJSON.getPath(schema.resultListLocator); if(path) { results = SchemaJSON.getLocationValue(path, json_in); if (results === undefined) { data_out.results = []; error = new Error("JSON results retrieval failure"); } else { if(LANG.isArray(results)) { // if no result fields are passed in, then just take the results array whole-hog // Sometimes you're getting an array of strings, or want the whole object, // so resultFields don't make sense. if (LANG.isArray(schema.resultFields)) { data_out = SchemaJSON._getFieldValues.call(this, schema.resultFields, results, data_out); } else { data_out.results = results; } } else { data_out.results = []; error = new Error("JSON Schema fields retrieval failure"); } } } else { error = new Error("JSON Schema results locator failure"); } if (error) { data_out.error = error; } } return data_out; }, /** * Get field data values out of list of full results * * @method _getFieldValues * @param fields {Array} Fields to find. * @param array_in {Array} Results to parse. * @param data_out {Object} In-progress parsed data to update. * @return {Object} Parsed data object. * @static * @protected */ _getFieldValues: function(fields, array_in, data_out) { var results = [], len = fields.length, i, j, field, key, locator, path, parser, simplePaths = [], complexPaths = [], fieldParsers = [], result, record; // First collect hashes of simple paths, complex paths, and parsers for (i=0; i<len; i++) { field = fields[i]; // A field can be a simple string or a hash key = field.key || field; // Find the key locator = field.locator || key; // Find the locator // Validate and store locators for later path = SchemaJSON.getPath(locator); if (path) { if (path.length === 1) { simplePaths[simplePaths.length] = {key:key, path:path[0]}; } else { complexPaths[complexPaths.length] = {key:key, path:path}; } } else { } // Validate and store parsers for later //TODO: use Y.DataSchema.parse? parser = (LANG.isFunction(field.parser)) ? field.parser : Y.Parsers[field.parser+'']; if (parser) { fieldParsers[fieldParsers.length] = {key:key, parser:parser}; } } // Traverse list of array_in, creating records of simple fields, // complex fields, and applying parsers as necessary for (i=array_in.length-1; i>=0; --i) { record = {}; result = array_in[i]; if(result) { // Cycle through simpleLocators for (j=simplePaths.length-1; j>=0; --j) { // Bug 1777850: The result might be an array instead of object record[simplePaths[j].key] = Y.DataSchema.Base.parse.call(this, (LANG.isUndefined(result[simplePaths[j].path]) ? result[j] : result[simplePaths[j].path]), simplePaths[j]); } // Cycle through complexLocators for (j=complexPaths.length - 1; j>=0; --j) { record[complexPaths[j].key] = Y.DataSchema.Base.parse.call(this, (SchemaJSON.getLocationValue(complexPaths[j].path, result)), complexPaths[j] ); } // Cycle through fieldParsers for (j=fieldParsers.length-1; j>=0; --j) { key = fieldParsers[j].key; record[key] = fieldParsers[j].parser.call(this, record[key]); // Safety net if (LANG.isUndefined(record[key])) { record[key] = null; } } results[i] = record; } } data_out.results = results; return data_out; }, /** * Parses results data according to schema * * @method _parseMeta * @param metaFields {Object} Metafields definitions. * @param json_in {Object} JSON to parse. * @param data_out {Object} In-progress parsed data to update. * @return {Object} Schema-parsed meta data. * @static * @protected */ _parseMeta: function(metaFields, json_in, data_out) { if(LANG.isObject(metaFields)) { var key, path; for(key in metaFields) { if (metaFields.hasOwnProperty(key)) { path = SchemaJSON.getPath(metaFields[key]); if (path && json_in) { data_out.meta[key] = SchemaJSON.getLocationValue(path, json_in); } } } } else { data_out.error = new Error("JSON meta data retrieval failure"); } return data_out; } }; Y.DataSchema.JSON = Y.mix(SchemaJSON, Y.DataSchema.Base); }, '3.3.0' ,{requires:['dataschema-base','json']});
blackstark/site
www/sugar/jssource/src_files/include/javascript/yui3/build/dataschema/dataschema-json.js
JavaScript
gpl-2.0
11,142
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Gdata * @subpackage Health * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: ProfileListEntry.php 24779 2012-05-08 19:13:59Z adamlundrigan $ */ /** * @see Zend_Exception */ require_once 'Zend/Exception.php'; /** * @see Zend_Gdata_Entry */ require_once 'Zend/Gdata/Entry.php'; /** * Concrete class for working with Health profile list entries. * * @link http://code.google.com/apis/health/ * * @category Zend * @package Zend_Gdata * @subpackage Health * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Gdata_Health_ProfileListEntry extends Zend_Gdata_Entry { /** * Constructs a new Zend_Gdata_Health_ProfileListEntry object. * @param DOMElement $element (optional) The DOMElement on which to base this object. */ public function __construct($element = null) { throw new Zend_Exception( 'Google Health API has been discontinued by Google and was removed' . ' from Zend Framework in 1.12.0. For more information see: ' . 'http://googleblog.blogspot.ca/2011/06/update-on-google-health-and-google.html' ); } }
mattsimpson/entrada-1x
www-root/core/library/Zend/Gdata/Health/ProfileListEntry.php
PHP
gpl-3.0
1,879
<?php class ModelAccountOrder extends Model { public function getOrder($order_id) { $order_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "order` WHERE order_id = '" . (int)$order_id . "' AND customer_id = '" . (int)$this->customer->getId() . "' AND order_status_id > '0'"); if ($order_query->num_rows) { $country_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE country_id = '" . (int)$order_query->row['payment_country_id'] . "'"); if ($country_query->num_rows) { $payment_iso_code_2 = $country_query->row['iso_code_2']; $payment_iso_code_3 = $country_query->row['iso_code_3']; } else { $payment_iso_code_2 = ''; $payment_iso_code_3 = ''; } $zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$order_query->row['payment_zone_id'] . "'"); if ($zone_query->num_rows) { $payment_zone_code = $zone_query->row['code']; } else { $payment_zone_code = ''; } $country_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE country_id = '" . (int)$order_query->row['shipping_country_id'] . "'"); if ($country_query->num_rows) { $shipping_iso_code_2 = $country_query->row['iso_code_2']; $shipping_iso_code_3 = $country_query->row['iso_code_3']; } else { $shipping_iso_code_2 = ''; $shipping_iso_code_3 = ''; } $zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$order_query->row['shipping_zone_id'] . "'"); if ($zone_query->num_rows) { $shipping_zone_code = $zone_query->row['code']; } else { $shipping_zone_code = ''; } return array( 'order_id' => $order_query->row['order_id'], 'invoice_no' => $order_query->row['invoice_no'], 'invoice_prefix' => $order_query->row['invoice_prefix'], 'store_id' => $order_query->row['store_id'], 'store_name' => $order_query->row['store_name'], 'store_url' => $order_query->row['store_url'], 'customer_id' => $order_query->row['customer_id'], 'firstname' => $order_query->row['firstname'], 'lastname' => $order_query->row['lastname'], 'telephone' => $order_query->row['telephone'], 'fax' => $order_query->row['fax'], 'email' => $order_query->row['email'], 'payment_firstname' => $order_query->row['payment_firstname'], 'payment_lastname' => $order_query->row['payment_lastname'], 'payment_company' => $order_query->row['payment_company'], 'payment_address_1' => $order_query->row['payment_address_1'], 'payment_address_2' => $order_query->row['payment_address_2'], 'payment_postcode' => $order_query->row['payment_postcode'], 'payment_city' => $order_query->row['payment_city'], 'payment_zone_id' => $order_query->row['payment_zone_id'], 'payment_zone' => $order_query->row['payment_zone'], 'payment_zone_code' => $payment_zone_code, 'payment_country_id' => $order_query->row['payment_country_id'], 'payment_country' => $order_query->row['payment_country'], 'payment_iso_code_2' => $payment_iso_code_2, 'payment_iso_code_3' => $payment_iso_code_3, 'payment_address_format' => $order_query->row['payment_address_format'], 'payment_method' => $order_query->row['payment_method'], 'shipping_firstname' => $order_query->row['shipping_firstname'], 'shipping_lastname' => $order_query->row['shipping_lastname'], 'shipping_company' => $order_query->row['shipping_company'], 'shipping_address_1' => $order_query->row['shipping_address_1'], 'shipping_address_2' => $order_query->row['shipping_address_2'], 'shipping_postcode' => $order_query->row['shipping_postcode'], 'shipping_city' => $order_query->row['shipping_city'], 'shipping_zone_id' => $order_query->row['shipping_zone_id'], 'shipping_zone' => $order_query->row['shipping_zone'], 'shipping_zone_code' => $shipping_zone_code, 'shipping_country_id' => $order_query->row['shipping_country_id'], 'shipping_country' => $order_query->row['shipping_country'], 'shipping_iso_code_2' => $shipping_iso_code_2, 'shipping_iso_code_3' => $shipping_iso_code_3, 'shipping_address_format' => $order_query->row['shipping_address_format'], 'shipping_method' => $order_query->row['shipping_method'], 'comment' => $order_query->row['comment'], 'total' => $order_query->row['total'], 'order_status_id' => $order_query->row['order_status_id'], 'language_id' => $order_query->row['language_id'], 'currency_id' => $order_query->row['currency_id'], 'currency_code' => $order_query->row['currency_code'], 'currency_value' => $order_query->row['currency_value'], 'date_modified' => $order_query->row['date_modified'], 'date_added' => $order_query->row['date_added'], 'ip' => $order_query->row['ip'] ); } else { return false; } } public function getOrders($start = 0, $limit = 20) { if ($start < 0) { $start = 0; } if ($limit < 1) { $limit = 1; } $query = $this->db->query("SELECT o.order_id, o.firstname, o.lastname, os.name as status, o.date_added, o.total, o.currency_code, o.currency_value FROM `" . DB_PREFIX . "order` o LEFT JOIN " . DB_PREFIX . "order_status os ON (o.order_status_id = os.order_status_id) WHERE o.customer_id = '" . (int)$this->customer->getId() . "' AND o.order_status_id > '0' AND o.store_id = '" . (int)$this->config->get('config_store_id') . "' AND os.language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY o.order_id DESC LIMIT " . (int)$start . "," . (int)$limit); return $query->rows; } public function getOrderProduct($order_id, $order_product_id) { $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "' AND order_product_id = '" . (int)$order_product_id . "'"); return $query->row; } public function getOrderProducts($order_id) { $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "'"); return $query->rows; } public function getOrderOptions($order_id, $order_product_id) { $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_option WHERE order_id = '" . (int)$order_id . "' AND order_product_id = '" . (int)$order_product_id . "'"); return $query->rows; } public function getOrderVouchers($order_id) { $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "order_voucher` WHERE order_id = '" . (int)$order_id . "'"); return $query->rows; } public function getOrderTotals($order_id) { $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_total WHERE order_id = '" . (int)$order_id . "' ORDER BY sort_order"); return $query->rows; } public function getOrderHistories($order_id) { $query = $this->db->query("SELECT date_added, os.name AS status, oh.comment, oh.notify FROM " . DB_PREFIX . "order_history oh LEFT JOIN " . DB_PREFIX . "order_status os ON oh.order_status_id = os.order_status_id WHERE oh.order_id = '" . (int)$order_id . "' AND os.language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY oh.date_added"); return $query->rows; } public function getTotalOrders() { $query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "order` o WHERE customer_id = '" . (int)$this->customer->getId() . "' AND o.order_status_id > '0' AND o.store_id = '" . (int)$this->config->get('config_store_id') . "'"); return $query->row['total']; } public function getTotalOrderProductsByOrderId($order_id) { $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "'"); return $query->row['total']; } public function getTotalOrderVouchersByOrderId($order_id) { $query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "order_voucher` WHERE order_id = '" . (int)$order_id . "'"); return $query->row['total']; } }
fercamp09/expigo1
www/catalog/model/account/order.php
PHP
gpl-3.0
8,457
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Xml; namespace System.Runtime.Serialization.Json { internal class JsonUriDataContract : JsonDataContract { public JsonUriDataContract(UriDataContract traditionalUriDataContract) : base(traditionalUriDataContract) { } public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) { if (context == null) { return TryReadNullAtTopLevel(jsonReader) ? null : jsonReader.ReadElementContentAsUri(); } else { return HandleReadValue(jsonReader.ReadElementContentAsUri(), context); } } } }
shahid-pk/corefx
src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonUriDataContract.cs
C#
mit
1,029
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Gdata * @subpackage Gdata * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * @see Zend_Gdata_Extension */ require_once 'Zend/Gdata/Extension.php'; /** * Implements the gd:reminder element used to set/retrieve notifications * * @category Zend * @package Zend_Gdata * @subpackage Gdata * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Gdata_Extension_Reminder extends Zend_Gdata_Extension { protected $_rootElement = 'reminder'; protected $_absoluteTime = null; protected $_method = null; protected $_days = null; protected $_hours = null; protected $_minutes = null; public function __construct($absoluteTime = null, $method = null, $days = null, $hours = null, $minutes = null) { parent::__construct(); $this->_absoluteTime = $absoluteTime; $this->_method = $method; $this->_days = $days; $this->_hours = $hours; $this->_minutes = $minutes; } public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) { $element = parent::getDOM($doc, $majorVersion, $minorVersion); if ($this->_absoluteTime !== null) { $element->setAttribute('absoluteTime', $this->_absoluteTime); } if ($this->_method !== null) { $element->setAttribute('method', $this->_method); } if ($this->_days !== null) { $element->setAttribute('days', $this->_days); } if ($this->_hours !== null) { $element->setAttribute('hours', $this->_hours); } if ($this->_minutes !== null) { $element->setAttribute('minutes', $this->_minutes); } return $element; } protected function takeAttributeFromDOM($attribute) { switch ($attribute->localName) { case 'absoluteTime': $this->_absoluteTime = $attribute->nodeValue; break; case 'method': $this->_method = $attribute->nodeValue; break; case 'days': $this->_days = $attribute->nodeValue; break; case 'hours': $this->_hours = $attribute->nodeValue; break; case 'minutes': $this->_minutes = $attribute->nodeValue; break; default: parent::takeAttributeFromDOM($attribute); } } public function __toString() { $s = ''; if ($this->_absoluteTime) $s = " at " . $this->_absoluteTime; else if ($this->_days) $s = " in " . $this->_days . " days"; else if ($this->_hours) $s = " in " . $this->_hours . " hours"; else if ($this->_minutes) $s = " in " . $this->_minutes . " minutes"; return $this->_method . $s; } public function getAbsoluteTime() { return $this->_absoluteTime; } public function setAbsoluteTime($value) { $this->_absoluteTime = $value; return $this; } public function getDays() { return $this->_days; } public function setDays($value) { $this->_days = $value; return $this; } public function getHours() { return $this->_hours; } public function setHours($value) { $this->_hours = $value; return $this; } public function getMinutes() { return $this->_minutes; } public function setMinutes($value) { $this->_minutes = $value; return $this; } public function getMethod() { return $this->_method; } public function setMethod($value) { $this->_method = $value; return $this; } }
angusty/symfony-study
vendor/Zend/Gdata/Extension/Reminder.php
PHP
mit
4,593
class Ascii < Formula desc "List ASCII idiomatic names and octal/decimal code-point forms" homepage "http://www.catb.org/~esr/ascii/" url "http://www.catb.org/~esr/ascii/ascii-3.15.tar.gz" sha256 "ace1db8b64371d53d9ad420d341f2b542324ae70437e37b4b75646f12475ff5f" bottle do cellar :any_skip_relocation sha256 "b7b74752e577efa60d98732e688910980436e42fbbf1f77a041cb2af458789f5" => :yosemite sha256 "56cec53206fc55f1fcd63b09b69c1afe858f4097ac6a460b7c9c07fbdfeaa0ed" => :mavericks sha256 "1a25c357bde021b59904fc8184c45a5eb85ae6be507a1e100aa79d441ad07943" => :mountain_lion end head do url "git://thyrsus.com/repositories/ascii.git" depends_on "xmlto" => :build end def install ENV["XML_CATALOG_FILES"] = "#{etc}/xml/catalog" if build.head? bin.mkpath man1.mkpath system "make" system "make", "PREFIX=#{prefix}", "install" end test do assert_match "Official name: Line Feed", shell_output(bin/"ascii 0x0a") end end
rokn/Count_Words_2015
fetched_code/ruby/ascii.rb
Ruby
mit
985
// mksyscall.pl -l32 -nacl syscall_nacl.go syscall_nacl_386.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build 386,nacl package syscall import "unsafe" // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func naclClose(fd int) (err error) { _, _, e1 := Syscall(sys_close, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) (err error) { _, _, e1 := Syscall(sys_exit, uintptr(code), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func naclFstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(sys_fstat, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func naclRead(fd int, b []byte) (n int, err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(sys_read, uintptr(fd), uintptr(_p0), uintptr(len(b))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func naclSeek(fd int, off *int64, whence int) (err error) { _, _, e1 := Syscall(sys_lseek, uintptr(fd), uintptr(unsafe.Pointer(off)), uintptr(whence)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func naclGetRandomBytes(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(sys_get_random_bytes, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return }
yeyuguo/go
src/syscall/zsyscall_nacl_386.go
GO
bsd-3-clause
1,815
// PR middle-end/42760 // { dg-do compile } template <typename T> struct A { static T b (T it) { return it; } }; template <typename T, typename U> static U baz (T x, T y, U z) { for (long n = y - x; n > 0; --n) { *z = *x; ++z; } }; template <typename T, typename U> U bar (T x, T y, U z) { baz (A <T>::b (x), A <T>::b (y), A <U>::b (z)); } struct C { __complex__ float v; }; template <class T> struct B { B (T y[]) { bar (y, y + 1, x); } operator T *() { return x; } T x[1]; }; B <C> foo () { C y[1]; return B <C> (y); };
SanDisk-Open-Source/SSD_Dashboard
uefi/gcc/gcc-4.6.3/gcc/testsuite/g++.dg/torture/pr42760.C
C++
gpl-2.0
566
/* Copyright 2016 The Kubernetes Authors. 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. */ package rest import ( "path" "testing" "k8s.io/client-go/pkg/api" ) func TestValidatesHostParameter(t *testing.T) { testCases := []struct { Host string APIPath string URL string Err bool }{ {"127.0.0.1", "", "http://127.0.0.1/" + api.Registry.GroupOrDie(api.GroupName).GroupVersion.Version, false}, {"127.0.0.1:8080", "", "http://127.0.0.1:8080/" + api.Registry.GroupOrDie(api.GroupName).GroupVersion.Version, false}, {"foo.bar.com", "", "http://foo.bar.com/" + api.Registry.GroupOrDie(api.GroupName).GroupVersion.Version, false}, {"http://host/prefix", "", "http://host/prefix/" + api.Registry.GroupOrDie(api.GroupName).GroupVersion.Version, false}, {"http://host", "", "http://host/" + api.Registry.GroupOrDie(api.GroupName).GroupVersion.Version, false}, {"http://host", "/", "http://host/" + api.Registry.GroupOrDie(api.GroupName).GroupVersion.Version, false}, {"http://host", "/other", "http://host/other/" + api.Registry.GroupOrDie(api.GroupName).GroupVersion.Version, false}, {"host/server", "", "", true}, } for i, testCase := range testCases { u, versionedAPIPath, err := DefaultServerURL(testCase.Host, testCase.APIPath, api.Registry.GroupOrDie(api.GroupName).GroupVersion, false) switch { case err == nil && testCase.Err: t.Errorf("expected error but was nil") continue case err != nil && !testCase.Err: t.Errorf("unexpected error %v", err) continue case err != nil: continue } u.Path = path.Join(u.Path, versionedAPIPath) if e, a := testCase.URL, u.String(); e != a { t.Errorf("%d: expected host %s, got %s", i, e, a) continue } } }
wanghaoran1988/origin
vendor/k8s.io/kubernetes/staging/src/k8s.io/client-go/rest/url_utils_test.go
GO
apache-2.0
2,193
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This is an empty file with a .cc extension, to convince the toolchain // (I'm looking at YOU, Xcode) that it needs to link any target this file // belongs to as C++.
plxaye/chromium
src/chrome/installer/mac/third_party/bsdiff/empty.cc
C++
apache-2.0
339
package com.iluwatar.servicelayer.wizard; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; import com.iluwatar.servicelayer.common.BaseEntity; import com.iluwatar.servicelayer.spellbook.Spellbook; /** * * Wizard entity. * */ @Entity @Table(name="WIZARD") public class Wizard extends BaseEntity { public Wizard() { spellbooks = new HashSet<Spellbook>(); } public Wizard(String name) { this(); this.name = name; } @Id @GeneratedValue @Column(name = "WIZARD_ID") private Long id; public Long getId() { return id; } public void setId(Long id) { this.id = id; } private String name; @ManyToMany(cascade = CascadeType.ALL) private Set<Spellbook> spellbooks; public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Spellbook> getSpellbooks() { return spellbooks; } public void setSpellbooks(Set<Spellbook> spellbooks) { this.spellbooks = spellbooks; } public void addSpellbook(Spellbook spellbook) { spellbook.getWizards().add(this); spellbooks.add(spellbook); } @Override public String toString() { return name; } }
ooon/java-design-patterns
service-layer/src/main/java/com/iluwatar/servicelayer/wizard/Wizard.java
Java
mit
1,383
<?php /** * @file * Contains \Drupal\Tests\Core\Database\Driver\pgsql\PostgresqlSchemaTest. */ namespace Drupal\Tests\Core\Database\Driver\pgsql; use Drupal\Core\Database\Driver\pgsql\Schema; use Drupal\Tests\UnitTestCase; /** * @coversDefaultClass \Drupal\Core\Database\Driver\pgsql\Schema * @group Database */ class PostgresqlSchemaTest extends UnitTestCase { /** * The PostgreSql DB connection. * * @var \PHPUnit_Framework_MockObject_MockObject|\Drupal\Core\Database\Driver\pgsql\Connection */ protected $connection; /** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->connection = $this->getMockBuilder('\Drupal\Core\Database\Driver\pgsql\Connection') ->disableOriginalConstructor() ->getMock(); } /** * Tests whether the actual constraint name is correctly computed. * * @param string $table_name * The table name the constrained column belongs to. * @param string $name * The constraint name. * @param string $expected * The expected computed constraint name. * * @covers ::constraintExists * @dataProvider providerComputedConstraintName */ public function testComputedConstraintName($table_name, $name, $expected) { $max_identifier_length = 63; $schema = new Schema($this->connection); $statement = $this->getMock('\Drupal\Core\Database\StatementInterface'); $statement->expects($this->any()) ->method('fetchField') ->willReturn($max_identifier_length); $this->connection->expects($this->any()) ->method('query') ->willReturn($statement); $this->connection->expects($this->at(2)) ->method('query') ->with("SELECT 1 FROM pg_constraint WHERE conname = '$expected'") ->willReturn($this->getMock('\Drupal\Core\Database\StatementInterface')); $schema->constraintExists($table_name, $name); } /** * Data provider for ::testComputedConstraintName(). */ public function providerComputedConstraintName() { return [ ['user_field_data', 'pkey', 'user_field_data____pkey'], ['user_field_data', 'name__key', 'user_field_data__name__key'], ['user_field_data', 'a_veeeery_veery_very_super_long_field_name__key', 'drupal_BGGYAXgbqlAF1rMOyFTdZGj9zIMXZtSvEjMAKZ9wGIk_key'], ]; } }
nrackleff/capstone
web/core/tests/Drupal/Tests/Core/Database/Driver/pgsql/PostgresqlSchemaTest.php
PHP
gpl-2.0
2,317
/* Copyright 2016 The Kubernetes Authors. 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. */ package options import ( "fmt" "net" "time" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/serializer" "k8s.io/apiserver/pkg/server" utilfeature "k8s.io/apiserver/pkg/util/feature" // add the generic feature gates _ "k8s.io/apiserver/pkg/features" "github.com/spf13/pflag" ) // ServerRunOptions contains the options while running a generic api server. type ServerRunOptions struct { AdvertiseAddress net.IP CorsAllowedOriginList []string ExternalHost string MaxRequestsInFlight int MaxMutatingRequestsInFlight int RequestTimeout time.Duration MinRequestTimeout int TargetRAMMB int } func NewServerRunOptions() *ServerRunOptions { defaults := server.NewConfig(serializer.CodecFactory{}) return &ServerRunOptions{ MaxRequestsInFlight: defaults.MaxRequestsInFlight, MaxMutatingRequestsInFlight: defaults.MaxMutatingRequestsInFlight, RequestTimeout: defaults.RequestTimeout, MinRequestTimeout: defaults.MinRequestTimeout, } } // ApplyOptions applies the run options to the method receiver and returns self func (s *ServerRunOptions) ApplyTo(c *server.Config) error { c.CorsAllowedOriginList = s.CorsAllowedOriginList c.ExternalAddress = s.ExternalHost c.MaxRequestsInFlight = s.MaxRequestsInFlight c.MaxMutatingRequestsInFlight = s.MaxMutatingRequestsInFlight c.RequestTimeout = s.RequestTimeout c.MinRequestTimeout = s.MinRequestTimeout c.PublicAddress = s.AdvertiseAddress return nil } // DefaultAdvertiseAddress sets the field AdvertiseAddress if unset. The field will be set based on the SecureServingOptions. func (s *ServerRunOptions) DefaultAdvertiseAddress(secure *SecureServingOptions) error { if secure == nil { return nil } if s.AdvertiseAddress == nil || s.AdvertiseAddress.IsUnspecified() { hostIP, err := secure.DefaultExternalAddress() if err != nil { return fmt.Errorf("Unable to find suitable network address.error='%v'. "+ "Try to set the AdvertiseAddress directly or provide a valid BindAddress to fix this.", err) } s.AdvertiseAddress = hostIP } return nil } // Validate checks validation of ServerRunOptions func (s *ServerRunOptions) Validate() []error { errors := []error{} if s.TargetRAMMB < 0 { errors = append(errors, fmt.Errorf("--target-ram-mb can not be negative value")) } if s.MaxRequestsInFlight < 0 { errors = append(errors, fmt.Errorf("--max-requests-inflight can not be negative value")) } if s.MaxMutatingRequestsInFlight < 0 { errors = append(errors, fmt.Errorf("--max-mutating-requests-inflight can not be negative value")) } if s.RequestTimeout.Nanoseconds() < 0 { errors = append(errors, fmt.Errorf("--request-timeout can not be negative value")) } return errors } // AddFlags adds flags for a specific APIServer to the specified FlagSet func (s *ServerRunOptions) AddUniversalFlags(fs *pflag.FlagSet) { // Note: the weird ""+ in below lines seems to be the only way to get gofmt to // arrange these text blocks sensibly. Grrr. fs.IPVar(&s.AdvertiseAddress, "advertise-address", s.AdvertiseAddress, ""+ "The IP address on which to advertise the apiserver to members of the cluster. This "+ "address must be reachable by the rest of the cluster. If blank, the --bind-address "+ "will be used. If --bind-address is unspecified, the host's default interface will "+ "be used.") fs.StringSliceVar(&s.CorsAllowedOriginList, "cors-allowed-origins", s.CorsAllowedOriginList, ""+ "List of allowed origins for CORS, comma separated. An allowed origin can be a regular "+ "expression to support subdomain matching. If this list is empty CORS will not be enabled.") fs.IntVar(&s.TargetRAMMB, "target-ram-mb", s.TargetRAMMB, "Memory limit for apiserver in MB (used to configure sizes of caches, etc.)") fs.StringVar(&s.ExternalHost, "external-hostname", s.ExternalHost, "The hostname to use when generating externalized URLs for this master (e.g. Swagger API Docs).") deprecatedMasterServiceNamespace := metav1.NamespaceDefault fs.StringVar(&deprecatedMasterServiceNamespace, "master-service-namespace", deprecatedMasterServiceNamespace, ""+ "DEPRECATED: the namespace from which the kubernetes master services should be injected into pods.") fs.IntVar(&s.MaxRequestsInFlight, "max-requests-inflight", s.MaxRequestsInFlight, ""+ "The maximum number of non-mutating requests in flight at a given time. When the server exceeds this, "+ "it rejects requests. Zero for no limit.") fs.IntVar(&s.MaxMutatingRequestsInFlight, "max-mutating-requests-inflight", s.MaxMutatingRequestsInFlight, ""+ "The maximum number of mutating requests in flight at a given time. When the server exceeds this, "+ "it rejects requests. Zero for no limit.") fs.DurationVar(&s.RequestTimeout, "request-timeout", s.RequestTimeout, ""+ "An optional field indicating the duration a handler must keep a request open before timing "+ "it out. This is the default request timeout for requests but may be overridden by flags such as "+ "--min-request-timeout for specific types of requests.") fs.IntVar(&s.MinRequestTimeout, "min-request-timeout", s.MinRequestTimeout, ""+ "An optional field indicating the minimum number of seconds a handler must keep "+ "a request open before timing it out. Currently only honored by the watch request "+ "handler, which picks a randomized value above this number as the connection timeout, "+ "to spread out load.") utilfeature.DefaultFeatureGate.AddFlag(fs) }
kgrygiel/autoscaler
vertical-pod-autoscaler/vendor/k8s.io/apiserver/pkg/server/options/server_run_options.go
GO
apache-2.0
6,147
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\View\Helper; /** * Renders <html> tag (both opening and closing) of a web page, to which some custom * attributes can be added dynamically. * * @author Nikola Posa <posa.nikola@gmail.com> */ class HtmlTag extends AbstractHtmlElement { /** * Attributes for the <html> tag. * * @var array */ protected $attributes = array(); /** * Whether to pre-set appropriate attributes in accordance * with the currently set DOCTYPE. * * @var bool */ protected $useNamespaces = false; /** * @var bool */ private $handledNamespaces = false; /** * Retrieve object instance; optionally add attributes. * * @param array $attribs * @return self */ public function __invoke(array $attribs = array()) { if (!empty($attribs)) { $this->setAttributes($attribs); } return $this; } /** * Set new attribute. * * @param string $attrName * @param string $attrValue * @return self */ public function setAttribute($attrName, $attrValue) { $this->attributes[$attrName] = $attrValue; return $this; } /** * Add new or overwrite the existing attributes. * * @param array $attribs * @return self */ public function setAttributes(array $attribs) { foreach ($attribs as $name => $value) { $this->setAttribute($name, $value); } return $this; } /** * @return array */ public function getAttributes() { return $this->attributes; } /** * @param bool $useNamespaces * @return self */ public function setUseNamespaces($useNamespaces) { $this->useNamespaces = (bool) $useNamespaces; return $this; } /** * @return bool */ public function getUseNamespaces() { return $this->useNamespaces; } /** * Render opening tag. * * @return string */ public function openTag() { $this->handleNamespaceAttributes(); return sprintf('<html%s>', $this->htmlAttribs($this->attributes)); } protected function handleNamespaceAttributes() { if ($this->useNamespaces && !$this->handledNamespaces) { if (method_exists($this->view, 'plugin')) { $doctypeAttributes = array(); if ($this->view->plugin('doctype')->isXhtml()) { $doctypeAttributes = array('xmlns' => 'http://www.w3.org/1999/xhtml'); } if (!empty($doctypeAttributes)) { $this->attributes = array_merge($doctypeAttributes, $this->attributes); } } $this->handledNamespaces = true; } } /** * Render closing tag. * * @return string */ public function closeTag() { return '</html>'; } }
pdhwi/hwi_test
z/ZendFramework-2.4.3/library/Zend/View/Helper/HtmlTag.php
PHP
bsd-3-clause
3,309
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Unit tests for Web CT question importer. * * @package qformat_webct * @copyright 2013 Jean-Michel Vedrine * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); global $CFG; require_once($CFG->libdir . '/questionlib.php'); require_once($CFG->dirroot . '/question/format.php'); require_once($CFG->dirroot . '/question/format/webct/format.php'); require_once($CFG->dirroot . '/question/engine/tests/helpers.php'); /** * Unit tests for the webct question import format. * * @copyright 2013 Jean-Michel Vedrine * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class qformat_webct_test extends question_testcase { public function make_test() { $lines = file(__DIR__ . '/fixtures/sample_webct.txt'); return $lines; } public function test_import_match() { $txt = $this->make_test(); $importer = new qformat_webct(); $questions = $importer->readquestions($txt); $q = $questions[3]; $expectedq = new stdClass(); $expectedq->qtype = 'match'; $expectedq->name = 'Classify the animals.'; $expectedq->questiontext = '<i>Classify the animals.</i>'; $expectedq->questiontextformat = FORMAT_HTML; $expectedq->correctfeedback = array( 'text' => '', 'format' => FORMAT_HTML, 'files' => array(), ); $expectedq->partiallycorrectfeedback = array( 'text' => '', 'format' => FORMAT_HTML, 'files' => array(), ); $expectedq->incorrectfeedback = array( 'text' => '', 'format' => FORMAT_HTML, 'files' => array(), ); $expectedq->generalfeedback = ''; $expectedq->generalfeedbackformat = FORMAT_MOODLE; $expectedq->defaultmark = 1; $expectedq->length = 1; $expectedq->penalty = 0.3333333; $expectedq->shuffleanswers = get_config('quiz', 'shuffleanswers'); $expectedq->subquestions = array( 1 => array('text' => 'cat', 'format' => FORMAT_HTML), 2 => array('text' => 'frog', 'format' => FORMAT_HTML), 3 => array('text' => 'newt', 'format' => FORMAT_HTML)); $expectedq->subanswers = array(1 => 'mammal', 2 => 'amphibian', 3 => 'amphibian'); $this->assert(new question_check_specified_fields_expectation($expectedq), $q); } public function test_import_multichoice_single() { $txt = $this->make_test(); $importer = new qformat_webct(); $questions = $importer->readquestions($txt); $q = $questions[1]; $expectedq = new stdClass(); $expectedq->qtype = 'multichoice'; $expectedq->single = 1; $expectedq->name = 'USER-2'; $expectedq->questiontext = '<font size="+1">What\'s between orange and green in the spectrum?</font>'; $expectedq->questiontextformat = FORMAT_HTML; $expectedq->correctfeedback = array( 'text' => '', 'format' => FORMAT_HTML, 'files' => array(), ); $expectedq->partiallycorrectfeedback = array( 'text' => '', 'format' => FORMAT_HTML, 'files' => array(), ); $expectedq->incorrectfeedback = array( 'text' => '', 'format' => FORMAT_HTML, 'files' => array(), ); $expectedq->generalfeedback = ''; $expectedq->generalfeedbackformat = FORMAT_MOODLE; $expectedq->defaultmark = 1; $expectedq->length = 1; $expectedq->penalty = 0.3333333; $expectedq->shuffleanswers = get_config('quiz', 'shuffleanswers'); $expectedq->answer = array( 1 => array( 'text' => 'red', 'format' => FORMAT_HTML, ), 2 => array( 'text' => 'yellow', 'format' => FORMAT_HTML, ), 3 => array( 'text' => 'blue', 'format' => FORMAT_HTML, ) ); $expectedq->fraction = array( 1 => 0, 2 => 1, 3 => 0, ); $expectedq->feedback = array( 1 => array( 'text' => 'Red is not between orange and green in the spectrum but yellow is.', 'format' => FORMAT_HTML, ), 2 => array( 'text' => 'You gave the right answer.', 'format' => FORMAT_HTML, ), 3 => array( 'text' => 'Blue is not between orange and green in the spectrum but yellow is.', 'format' => FORMAT_HTML, ) ); $this->assert(new question_check_specified_fields_expectation($expectedq), $q); } public function test_import_multichoice_multi() { $txt = $this->make_test(); $importer = new qformat_webct(); $questions = $importer->readquestions($txt); $q = $questions[2]; $expectedq = new stdClass(); $expectedq->qtype = 'multichoice'; $expectedq->single = 0; $expectedq->name = 'USER-3'; $expectedq->questiontext = '<i>What\'s between orange and green in the spectrum?</i>'; $expectedq->questiontextformat = FORMAT_HTML; $expectedq->correctfeedback = array( 'text' => '', 'format' => FORMAT_HTML, 'files' => array(), ); $expectedq->partiallycorrectfeedback = array( 'text' => '', 'format' => FORMAT_HTML, 'files' => array(), ); $expectedq->incorrectfeedback = array( 'text' => '', 'format' => FORMAT_HTML, 'files' => array(), ); $expectedq->generalfeedback = ''; $expectedq->generalfeedbackformat = FORMAT_MOODLE; $expectedq->defaultmark = 1; $expectedq->length = 1; $expectedq->penalty = 0.3333333; $expectedq->shuffleanswers = get_config('quiz', 'shuffleanswers'); $expectedq->answer = array( 1 => array( 'text' => 'yellow', 'format' => FORMAT_HTML, ), 2 => array( 'text' => 'red', 'format' => FORMAT_HTML, ), 3 => array( 'text' => 'off-beige', 'format' => FORMAT_HTML, ), 4 => array( 'text' => 'blue', 'format' => FORMAT_HTML, ) ); $expectedq->fraction = array( 1 => 0.5, 2 => 0, 3 => 0.5, 4 => 0, ); $expectedq->feedback = array( 1 => array( 'text' => 'True, yellow is between orange and green in the spectrum,', 'format' => FORMAT_HTML, ), 2 => array( 'text' => 'False, red is not between orange and green in the spectrum,', 'format' => FORMAT_HTML, ), 3 => array( 'text' => 'True, off-beige is between orange and green in the spectrum,', 'format' => FORMAT_HTML, ), 4 => array( 'text' => 'False, red is not between orange and green in the spectrum,', 'format' => FORMAT_HTML, ) ); $this->assert(new question_check_specified_fields_expectation($expectedq), $q); } public function test_import_truefalse() { $txt = $this->make_test(); $importer = new qformat_webct(); $questions = $importer->readquestions($txt); $q = $questions[0]; $expectedq = new stdClass(); $expectedq->qtype = 'multichoice'; $expectedq->single = 1; $expectedq->name = 'USER-1'; $expectedq->questiontext = '42 is the Absolute Answer to everything.'; $expectedq->questiontextformat = FORMAT_HTML; $expectedq->correctfeedback = array( 'text' => '', 'format' => FORMAT_HTML, 'files' => array(), ); $expectedq->partiallycorrectfeedback = array( 'text' => '', 'format' => FORMAT_HTML, 'files' => array(), ); $expectedq->incorrectfeedback = array( 'text' => '', 'format' => FORMAT_HTML, 'files' => array(), ); $expectedq->generalfeedback = ''; $expectedq->generalfeedbackformat = FORMAT_MOODLE; $expectedq->defaultmark = 1; $expectedq->length = 1; $expectedq->shuffleanswers = get_config('quiz', 'shuffleanswers'); $expectedq->answer = array( 1 => array( 'text' => 'True', 'format' => FORMAT_HTML, ), 2 => array( 'text' => 'False', 'format' => FORMAT_HTML, ), ); $expectedq->fraction = array( 1 => 0, 2 => 1, ); $expectedq->feedback = array( 1 => array( 'text' => '42 is the <b>Ultimate</b> Answer.', 'format' => FORMAT_HTML, ), 2 => array( 'text' => '42 is the <b>Ultimate</b> Answer.', 'format' => FORMAT_HTML, ), ); $this->assert(new question_check_specified_fields_expectation($expectedq), $q); } public function test_import_fill_in_the_blank() { $txt = $this->make_test(); $importer = new qformat_webct(); $questions = $importer->readquestions($txt); $q = $questions[4]; $expectedq = new stdClass(); $expectedq->qtype = 'shortanswer'; $expectedq->name = 'USER-5'; $expectedq->questiontext = 'Name an amphibian&#58; __________'; $expectedq->questiontextformat = FORMAT_HTML; $expectedq->generalfeedback = 'A frog is an amphibian'; $expectedq->generalfeedbackformat = FORMAT_HTML; $expectedq->defaultmark = 1; $expectedq->length = 1; $expectedq->usecase = 0; $expectedq->answer = array( 1 => 'frog', ); $expectedq->fraction = array( 1 => 1, ); $expectedq->feedback = array( 1 => array( 'text' => '', 'format' => FORMAT_HTML, ), ); $this->assert(new question_check_specified_fields_expectation($expectedq), $q); } public function test_import_essay() { $txt = $this->make_test(); $importer = new qformat_webct(); $questions = $importer->readquestions($txt); $q = $questions[5]; $expectedq = new stdClass(); $expectedq->qtype = 'essay'; $expectedq->name = 'USER-6'; $expectedq->questiontext = 'How are you?'; $expectedq->questiontextformat = FORMAT_HTML; $expectedq->generalfeedback = ''; $expectedq->generalfeedbackformat = FORMAT_HTML; $expectedq->defaultmark = 1; $expectedq->length = 1; $expectedq->responseformat = 'editor'; $expectedq->responsefieldlines = 15; $expectedq->attachments = 0; $expectedq->graderinfo = array( 'text' => 'Blackboard answer for essay questions will be imported as informations for graders.', 'format' => FORMAT_HTML, ); $this->assert(new question_check_specified_fields_expectation($expectedq), $q); } }
cjamieso/moodle289
question/format/webct/tests/webctformat_test.php
PHP
gpl-3.0
12,989
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to you 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. */ package org.apache.hadoop.io.file.tfile; import java.io.IOException; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; /** * Exception - No such Meta Block with the given name. */ @SuppressWarnings("serial") @InterfaceAudience.Public @InterfaceStability.Stable public class MetaBlockDoesNotExist extends IOException { /** * Constructor * * @param s * message. */ MetaBlockDoesNotExist(String s) { super(s); } }
tseen/Federated-HDFS
tseenliu/FedHDFS-hadoop-src/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/file/tfile/MetaBlockDoesNotExist.java
Java
apache-2.0
1,320
/* { dg-do compile } */ /* { dg-options "-O2" } */ /* We were not getting the offset of a in B and a in C::B correct, causing an abort. */ struct A { A(); }; struct B : A { A a; }; struct C : B { }; C c;
SanDisk-Open-Source/SSD_Dashboard
uefi/gcc/gcc-4.6.3/gcc/testsuite/g++.dg/tree-ssa/pr22404.C
C++
gpl-2.0
217
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Resets the emoticons mapping into the default value * * @package core * @copyright 2010 David Mudrak <david@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ require(__DIR__ . '/../config.php'); require_once($CFG->libdir.'/adminlib.php'); admin_externalpage_setup('resetemoticons'); $confirm = optional_param('confirm', false, PARAM_BOOL); if (!$confirm or !confirm_sesskey()) { echo $OUTPUT->header(); echo $OUTPUT->heading(get_string('confirmation', 'admin')); echo $OUTPUT->confirm(get_string('emoticonsreset', 'admin'), new moodle_url($PAGE->url, array('confirm' => 1)), new moodle_url('/admin/settings.php', array('section' => 'htmlsettings'))); echo $OUTPUT->footer(); die(); } $manager = get_emoticon_manager(); set_config('emoticons', $manager->encode_stored_config($manager->default_emoticons())); redirect(new moodle_url('/admin/settings.php', array('section' => 'htmlsettings')));
cbradley456/moodle
admin/resetemoticons.php
PHP
gpl-3.0
1,673
// { dg-do assemble } // Copyright (C) 2000 Free Software Foundation, Inc. // Contributed by Nathan Sidwell 23 June 2000 <nathan@codesourcery.com> // Origin GNATS bug report 69 from Glenn Ammons <ammons@cs.wisc.edu> // // A base which derives a virtual base hides declarations in the virtual base, // even if that virtual base is accessible via another path [10.2]/6. Make // sure that non-virtual bases of the virtual base are also hidden, not matter // what order bases are declared in. struct A {int a;}; struct B : A {}; struct L1 : virtual B { int a; }; struct L2 : virtual A { int a; }; struct R1 : virtual B {}; struct R2 : virtual A {}; struct C1 : R1, L1 {}; struct C2 : R2, L2 {}; struct D1 : L1, R1 {}; struct D2 : L2, R2 {}; void fn (C1 *c1, D1 *d1, C2 *c2, D2 *d2) { c1->a = 1; d1->a = 1; c2->a = 1; d2->a = 1; }
SanDisk-Open-Source/SSD_Dashboard
uefi/gcc/gcc-4.6.3/gcc/testsuite/g++.old-deja/g++.other/ambig3.C
C++
gpl-2.0
844
// { dg-do run } // GROUPS passed miscellaneous extern "C" int printf (const char *, ...); int main() { int i = 0; // Make sure build_unary_op correctly computes this. int *pi = &(++i); *pi = 4; if (i != 4) { printf ("FAIL\n"); return 1; } else printf ("PASS\n"); }
SanDisk-Open-Source/SSD_Dashboard
uefi/gcc/gcc-4.6.3/gcc/testsuite/g++.old-deja/g++.brendan/misc7.C
C++
gpl-2.0
289
// { dg-do assemble } template <class A> class B { public: A a; }; static B<int> b_int; static B<char> b_char; static B<unsigned char> b_uchar; int foo () { return b_int.a + b_char.a + b_uchar.a; }
SanDisk-Open-Source/SSD_Dashboard
uefi/gcc/gcc-4.6.3/gcc/testsuite/g++.old-deja/g++.pt/t04.C
C++
gpl-2.0
201
/** * @fileoverview Rule to spot scenarios where a newline looks like it is ending a statement, but is not. * @author Glen Mailer * @copyright 2015 Glen Mailer */ "use strict"; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = function(context) { var FUNCTION_MESSAGE = "Unexpected newline between function and ( of function call."; var PROPERTY_MESSAGE = "Unexpected newline between object and [ of property access."; /** * Check to see if the bracket prior to the node is continuing the previous * line's expression * @param {ASTNode} node The node to check. * @param {string} msg The error message to use. * @returns {void} * @private */ function checkForBreakBefore(node, msg) { var tokens = context.getTokensBefore(node, 2); var paren = tokens[1]; var before = tokens[0]; if (paren.loc.start.line !== before.loc.end.line) { context.report(node, paren.loc.start, msg, { char: paren.value }); } } //-------------------------------------------------------------------------- // Public API //-------------------------------------------------------------------------- return { "MemberExpression": function(node) { if (!node.computed) { return; } checkForBreakBefore(node.property, PROPERTY_MESSAGE); }, "CallExpression": function(node) { if (node.arguments.length === 0) { return; } checkForBreakBefore(node.arguments[0], FUNCTION_MESSAGE); } }; }; module.exports.schema = [];
Phalanstere/WritersStudio
writers_studio-win32-ia32/resources/app/node_modules/eslint/lib/rules/no-unexpected-multiline.js
JavaScript
mit
1,803
YUI.add('color-base', function (Y, NAME) { /** Color provides static methods for color conversion. Y.Color.toRGB('f00'); // rgb(255, 0, 0) Y.Color.toHex('rgb(255, 255, 0)'); // #ffff00 @module color @submodule color-base @class Color @since 3.8.0 **/ var REGEX_HEX = /^#?([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})/, REGEX_HEX3 = /^#?([\da-fA-F]{1})([\da-fA-F]{1})([\da-fA-F]{1})/, REGEX_RGB = /rgba?\(([\d]{1,3}), ?([\d]{1,3}), ?([\d]{1,3}),? ?([.\d]*)?\)/, TYPES = { 'HEX': 'hex', 'RGB': 'rgb', 'RGBA': 'rgba' }, CONVERTS = { 'hex': 'toHex', 'rgb': 'toRGB', 'rgba': 'toRGBA' }; Y.Color = { /** @static @property KEYWORDS @type Object @since 3.8.0 **/ KEYWORDS: { 'black': '000', 'silver': 'c0c0c0', 'gray': '808080', 'white': 'fff', 'maroon': '800000', 'red': 'f00', 'purple': '800080', 'fuchsia': 'f0f', 'green': '008000', 'lime': '0f0', 'olive': '808000', 'yellow': 'ff0', 'navy': '000080', 'blue': '00f', 'teal': '008080', 'aqua': '0ff' }, /** @static @property REGEX_HEX @type RegExp @default /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/ @since 3.8.0 **/ REGEX_HEX: REGEX_HEX, /** @static @property REGEX_HEX3 @type RegExp @default /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})/ @since 3.8.0 **/ REGEX_HEX3: REGEX_HEX3, /** @static @property REGEX_RGB @type RegExp @default /rgba?\(([0-9]{1,3}), ?([0-9]{1,3}), ?([0-9]{1,3}),? ?([.0-9]{1,3})?\)/ @since 3.8.0 **/ REGEX_RGB: REGEX_RGB, re_RGB: REGEX_RGB, re_hex: REGEX_HEX, re_hex3: REGEX_HEX3, /** @static @property STR_HEX @type String @default #{*}{*}{*} @since 3.8.0 **/ STR_HEX: '#{*}{*}{*}', /** @static @property STR_RGB @type String @default rgb({*}, {*}, {*}) @since 3.8.0 **/ STR_RGB: 'rgb({*}, {*}, {*})', /** @static @property STR_RGBA @type String @default rgba({*}, {*}, {*}, {*}) @since 3.8.0 **/ STR_RGBA: 'rgba({*}, {*}, {*}, {*})', /** @static @property TYPES @type Object @default {'rgb':'rgb', 'rgba':'rgba'} @since 3.8.0 **/ TYPES: TYPES, /** @static @property CONVERTS @type Object @default {} @since 3.8.0 **/ CONVERTS: CONVERTS, /** @public @method convert @param {String} str @param {String} to @return {String} @since 3.8.0 **/ convert: function (str, to) { // check for a toXXX conversion method first // if it doesn't exist, use the toXxx conversion method var convert = Y.Color.CONVERTS[to], clr = Y.Color[convert](str); return clr.toLowerCase(); }, /** Converts provided color value to a hex value string @public @method toHex @param {String} str Hex or RGB value string @return {String} returns array of values or CSS string if options.css is true @since 3.8.0 **/ toHex: function (str) { var clr = Y.Color._convertTo(str, 'hex'); return clr.toLowerCase(); }, /** Converts provided color value to an RGB value string @public @method toRGB @param {String} str Hex or RGB value string @return {String} @since 3.8.0 **/ toRGB: function (str) { var clr = Y.Color._convertTo(str, 'rgb'); return clr.toLowerCase(); }, /** Converts provided color value to an RGB value string @public @method toRGBA @param {String} str Hex or RGB value string @return {String} @since 3.8.0 **/ toRGBA: function (str) { var clr = Y.Color._convertTo(str, 'rgba' ); return clr.toLowerCase(); }, /** Converts the provided color string to an array of values. Will return an empty array if the provided string is not able to be parsed. @public @method toArray @param {String} str @return {Array} @since 3.8.0 **/ toArray: function(str) { // parse with regex and return "matches" array var type = Y.Color.findType(str).toUpperCase(), regex, arr, length, lastItem; if (type === 'HEX' && str.length < 5) { type = 'HEX3'; } if (type.charAt(type.length - 1) === 'A') { type = type.slice(0, -1); } regex = Y.Color['REGEX_' + type]; if (regex) { arr = regex.exec(str) || []; length = arr.length; if (length) { arr.shift(); length--; lastItem = arr[length - 1]; if (!lastItem) { arr[length - 1] = 1; } } } return arr; }, /** Converts the array of values to a string based on the provided template. @public @method fromArray @param {Array} arr @param {String} template @return {String} @since 3.8.0 **/ fromArray: function(arr, template) { arr = arr.concat(); if (typeof template === 'undefined') { return arr.join(', '); } var replace = '{*}'; template = Y.Color['STR_' + template.toUpperCase()]; if (arr.length === 3 && template.match(/\{\*\}/g).length === 4) { arr.push(1); } while ( template.indexOf(replace) >= 0 && arr.length > 0) { template = template.replace(replace, arr.shift()); } return template; }, /** Finds the value type based on the str value provided. @public @method findType @param {String} str @return {String} @since 3.8.0 **/ findType: function (str) { if (Y.Color.KEYWORDS[str]) { return 'keyword'; } var index = str.indexOf('('), key; if (index > 0) { key = str.substr(0, index); } if (key && Y.Color.TYPES[key.toUpperCase()]) { return Y.Color.TYPES[key.toUpperCase()]; } return 'hex'; }, // return 'keyword', 'hex', 'rgb' /** Retrives the alpha channel from the provided string. If no alpha channel is present, `1` will be returned. @protected @method _getAlpha @param {String} clr @return {Number} @since 3.8.0 **/ _getAlpha: function (clr) { var alpha, arr = Y.Color.toArray(clr); if (arr.length > 3) { alpha = arr.pop(); } return +alpha || 1; }, /** Returns the hex value string if found in the KEYWORDS object @protected @method _keywordToHex @param {String} clr @return {String} @since 3.8.0 **/ _keywordToHex: function (clr) { var keyword = Y.Color.KEYWORDS[clr]; if (keyword) { return keyword; } }, /** Converts the provided color string to the value type provided as `to` @protected @method _convertTo @param {String} clr @param {String} to @return {String} @since 3.8.0 **/ _convertTo: function(clr, to) { var from = Y.Color.findType(clr), originalTo = to, needsAlpha, alpha, method, ucTo; if (from === 'keyword') { clr = Y.Color._keywordToHex(clr); from = 'hex'; } if (from === 'hex' && clr.length < 5) { if (clr.charAt(0) === '#') { clr = clr.substr(1); } clr = '#' + clr.charAt(0) + clr.charAt(0) + clr.charAt(1) + clr.charAt(1) + clr.charAt(2) + clr.charAt(2); } if (from === to) { return clr; } if (from.charAt(from.length - 1) === 'a') { from = from.slice(0, -1); } needsAlpha = (to.charAt(to.length - 1) === 'a'); if (needsAlpha) { to = to.slice(0, -1); alpha = Y.Color._getAlpha(clr); } ucTo = to.charAt(0).toUpperCase() + to.substr(1).toLowerCase(); method = Y.Color['_' + from + 'To' + ucTo ]; // check to see if need conversion to rgb first // check to see if there is a direct conversion method // convertions are: hex <-> rgb <-> hsl if (!method) { if (from !== 'rgb' && to !== 'rgb') { clr = Y.Color['_' + from + 'ToRgb'](clr); from = 'rgb'; method = Y.Color['_' + from + 'To' + ucTo ]; } } if (method) { clr = ((method)(clr, needsAlpha)); } // process clr from arrays to strings after conversions if alpha is needed if (needsAlpha) { if (!Y.Lang.isArray(clr)) { clr = Y.Color.toArray(clr); } clr.push(alpha); clr = Y.Color.fromArray(clr, originalTo.toUpperCase()); } return clr; }, /** Processes the hex string into r, g, b values. Will return values as an array, or as an rgb string. @protected @method _hexToRgb @param {String} str @param {Boolean} [toArray] @return {String|Array} @since 3.8.0 **/ _hexToRgb: function (str, toArray) { var r, g, b; /*jshint bitwise:false*/ if (str.charAt(0) === '#') { str = str.substr(1); } str = parseInt(str, 16); r = str >> 16; g = str >> 8 & 0xFF; b = str & 0xFF; if (toArray) { return [r, g, b]; } return 'rgb(' + r + ', ' + g + ', ' + b + ')'; }, /** Processes the rgb string into r, g, b values. Will return values as an array, or as a hex string. @protected @method _rgbToHex @param {String} str @param {Boolean} [toArray] @return {String|Array} @since 3.8.0 **/ _rgbToHex: function (str) { /*jshint bitwise:false*/ var rgb = Y.Color.toArray(str), hex = rgb[2] | (rgb[1] << 8) | (rgb[0] << 16); hex = (+hex).toString(16); while (hex.length < 6) { hex = '0' + hex; } return '#' + hex; } }; }, '@VERSION@', {"requires": ["yui-base"]});
sajochiu/cdnjs
ajax/libs/yui/3.9.1/color-base/color-base.js
JavaScript
mit
10,438
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bridge\Monolog\Handler; use Monolog\Handler\AbstractProcessingHandler; use Monolog\Logger; use Symfony\Bridge\Monolog\Formatter\ConsoleFormatter; use Symfony\Component\Console\ConsoleEvents; use Symfony\Component\Console\Event\ConsoleCommandEvent; use Symfony\Component\Console\Event\ConsoleTerminateEvent; use Symfony\Component\Console\Output\ConsoleOutputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; /** * Writes logs to the console output depending on its verbosity setting. * * It is disabled by default and gets activated as soon as a command is executed. * Instead of listening to the console events, the output can also be set manually. * * The minimum logging level at which this handler will be triggered depends on the * verbosity setting of the console output. The default mapping is: * - OutputInterface::VERBOSITY_NORMAL will show all WARNING and higher logs * - OutputInterface::VERBOSITY_VERBOSE (-v) will show all NOTICE and higher logs * - OutputInterface::VERBOSITY_VERY_VERBOSE (-vv) will show all INFO and higher logs * - OutputInterface::VERBOSITY_DEBUG (-vvv) will show all DEBUG and higher logs, i.e. all logs * * This mapping can be customized with the $verbosityLevelMap constructor parameter. * * @author Tobias Schultze <http://tobion.de> */ class ConsoleHandler extends AbstractProcessingHandler implements EventSubscriberInterface { /** * @var OutputInterface|null */ private $output; /** * @var array */ private $verbosityLevelMap = array( OutputInterface::VERBOSITY_NORMAL => Logger::WARNING, OutputInterface::VERBOSITY_VERBOSE => Logger::NOTICE, OutputInterface::VERBOSITY_VERY_VERBOSE => Logger::INFO, OutputInterface::VERBOSITY_DEBUG => Logger::DEBUG ); /** * Constructor. * * @param OutputInterface|null $output The console output to use (the handler remains disabled when passing null * until the output is set, e.g. by using console events) * @param bool $bubble Whether the messages that are handled can bubble up the stack * @param array $verbosityLevelMap Array that maps the OutputInterface verbosity to a minimum logging * level (leave empty to use the default mapping) */ public function __construct(OutputInterface $output = null, $bubble = true, array $verbosityLevelMap = array()) { parent::__construct(Logger::DEBUG, $bubble); $this->output = $output; if ($verbosityLevelMap) { $this->verbosityLevelMap = $verbosityLevelMap; } } /** * {@inheritdoc} */ public function isHandling(array $record) { return $this->updateLevel() && parent::isHandling($record); } /** * {@inheritdoc} */ public function handle(array $record) { // we have to update the logging level each time because the verbosity of the // console output might have changed in the meantime (it is not immutable) return $this->updateLevel() && parent::handle($record); } /** * Sets the console output to use for printing logs. * * @param OutputInterface $output The console output to use */ public function setOutput(OutputInterface $output) { $this->output = $output; } /** * Disables the output. */ public function close() { $this->output = null; parent::close(); } /** * Before a command is executed, the handler gets activated and the console output * is set in order to know where to write the logs. * * @param ConsoleCommandEvent $event */ public function onCommand(ConsoleCommandEvent $event) { $this->setOutput($event->getOutput()); } /** * After a command has been executed, it disables the output. * * @param ConsoleTerminateEvent $event */ public function onTerminate(ConsoleTerminateEvent $event) { $this->close(); } /** * {@inheritdoc} */ public static function getSubscribedEvents() { return array( ConsoleEvents::COMMAND => 'onCommand', ConsoleEvents::TERMINATE => 'onTerminate' ); } /** * {@inheritdoc} */ protected function write(array $record) { if ($record['level'] >= Logger::ERROR && $this->output instanceof ConsoleOutputInterface) { $this->output->getErrorOutput()->write((string) $record['formatted']); } else { $this->output->write((string) $record['formatted']); } } /** * {@inheritdoc} */ protected function getDefaultFormatter() { return new ConsoleFormatter(); } /** * Updates the logging level based on the verbosity setting of the console output. * * @return bool Whether the handler is enabled and verbosity is not set to quiet. */ private function updateLevel() { if (null === $this->output || OutputInterface::VERBOSITY_QUIET === $verbosity = $this->output->getVerbosity()) { return false; } if (isset($this->verbosityLevelMap[$verbosity])) { $this->setLevel($this->verbosityLevelMap[$verbosity]); } else { $this->setLevel(Logger::DEBUG); } return true; } }
marguerrero/onlinefeedback
vendor20150405/symfony/symfony/src/src/Symfony/Bridge/Monolog/Handler/ConsoleHandler.php
PHP
mit
5,853
class Ssdb < Formula desc "NoSQL database supporting many data structures: Redis alternative" homepage "http://ssdb.io/" url "https://github.com/ideawu/ssdb/archive/1.8.2.tar.gz" sha256 "2fe10689a0e1e9e9ca67acbe9e0fa3607810dca90dcc9f0813b2661cc6d4e826" head "https://github.com/ideawu/ssdb.git" bottle do cellar :any sha256 "1970e505fd1e8f6166010a892e66a718a39cbab1bcdd515bd6fdd4ec7c185600" => :yosemite sha256 "61430871ab15a312f8a6b0caf68003d379fc8e52199702747b84f86f3887d911" => :mavericks sha256 "16b3c20d79519328e01139ccf8fc71832f90d5df1c55c9ba32ab150a0cddf77e" => :mountain_lion end def install inreplace "Makefile", "PREFIX=/usr/local/ssdb", "PREFIX=#{prefix}" system "make", "prefix=#{prefix} CC=#{ENV.cc} CXX=#{ENV.cxx}" system "make", "install" ["bench", "dump", "ins.sh", "repair", "server"].each do |suffix| bin.install "#{prefix}/ssdb-#{suffix}" end ["run", "db/ssdb", "log"].each do |dir| (var+dir).mkpath end inreplace "ssdb.conf" do |s| s.gsub! "work_dir = ./var", "work_dir = #{var}/db/ssdb/" s.gsub! "pidfile = ./var/ssdb.pid", "pidfile = #{var}/run/ssdb.pid" s.gsub! "\toutput: log.txt", "\toutput: #{var}/log/ssdb.log" end inreplace "ssdb_slave.conf" do |s| s.gsub! "work_dir = ./var_slave", "work_dir = #{var}/db/ssdb/" s.gsub! "pidfile = ./var_slave/ssdb.pid", "pidfile = #{var}/run/ssdb_slave.pid" s.gsub! "\toutput: log_slave.txt", "\toutput: #{var}/log/ssdb_slave.log" end etc.install "ssdb.conf" etc.install "ssdb_slave.conf" end plist_options :manual => "ssdb-server #{HOMEBREW_PREFIX}/etc/ssdb.conf" def plist; <<-EOS.undent <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>KeepAlive</key> <dict> <key>SuccessfulExit</key> <false/> </dict> <key>Label</key> <string>#{plist_name}</string> <key>ProgramArguments</key> <array> <string>#{opt_bin}/ssdb-server</string> <string>#{etc}/ssdb.conf</string> </array> <key>RunAtLoad</key> <true/> <key>WorkingDirectory</key> <string>#{var}</string> <key>StandardErrorPath</key> <string>#{var}/log/ssdb.log</string> <key>StandardOutPath</key> <string>#{var}/log/ssdb.log</string> </dict> </plist> EOS end test do pid = fork do Signal.trap("TERM") do system("#{bin}/ssdb-server -d #{HOMEBREW_PREFIX}/etc/ssdb.conf") exit end end sleep(3) Process.kill("TERM", pid) end end
seeden/homebrew
Library/Formula/ssdb.rb
Ruby
bsd-2-clause
2,762
// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build plan9,!race package plan9 import ( "unsafe" ) const raceenabled = false func raceAcquire(addr unsafe.Pointer) { } func raceReleaseMerge(addr unsafe.Pointer) { } func raceReadRange(addr unsafe.Pointer, len int) { } func raceWriteRange(addr unsafe.Pointer, len int) { }
muzining/net
x/sys/plan9/race0.go
GO
bsd-3-clause
447
class Token(object): def __init__(self, start_mark, end_mark): self.start_mark = start_mark self.end_mark = end_mark def __repr__(self): attributes = [key for key in self.__dict__ if not key.endswith('_mark')] attributes.sort() arguments = ', '.join(['%s=%r' % (key, getattr(self, key)) for key in attributes]) return '%s(%s)' % (self.__class__.__name__, arguments) #class BOMToken(Token): # id = '<byte order mark>' class DirectiveToken(Token): id = '<directive>' def __init__(self, name, value, start_mark, end_mark): self.name = name self.value = value self.start_mark = start_mark self.end_mark = end_mark class DocumentStartToken(Token): id = '<document start>' class DocumentEndToken(Token): id = '<document end>' class StreamStartToken(Token): id = '<stream start>' def __init__(self, start_mark=None, end_mark=None, encoding=None): self.start_mark = start_mark self.end_mark = end_mark self.encoding = encoding class StreamEndToken(Token): id = '<stream end>' class BlockSequenceStartToken(Token): id = '<block sequence start>' class BlockMappingStartToken(Token): id = '<block mapping start>' class BlockEndToken(Token): id = '<block end>' class FlowSequenceStartToken(Token): id = '[' class FlowMappingStartToken(Token): id = '{' class FlowSequenceEndToken(Token): id = ']' class FlowMappingEndToken(Token): id = '}' class KeyToken(Token): id = '?' class ValueToken(Token): id = ':' class BlockEntryToken(Token): id = '-' class FlowEntryToken(Token): id = ',' class AliasToken(Token): id = '<alias>' def __init__(self, value, start_mark, end_mark): self.value = value self.start_mark = start_mark self.end_mark = end_mark class AnchorToken(Token): id = '<anchor>' def __init__(self, value, start_mark, end_mark): self.value = value self.start_mark = start_mark self.end_mark = end_mark class TagToken(Token): id = '<tag>' def __init__(self, value, start_mark, end_mark): self.value = value self.start_mark = start_mark self.end_mark = end_mark class ScalarToken(Token): id = '<scalar>' def __init__(self, value, plain, start_mark, end_mark, style=None): self.value = value self.plain = plain self.start_mark = start_mark self.end_mark = end_mark self.style = style
cortext/crawtextV2
~/venvs/crawler/lib/python2.7/site-packages/yaml/tokens.py
Python
mit
2,573
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _postcss = require('postcss'); var _clone = require('../clone'); var _clone2 = _interopRequireDefault(_clone); var _hasAllProps = require('../hasAllProps'); var _hasAllProps2 = _interopRequireDefault(_hasAllProps); var _getLastNode = require('../getLastNode'); var _getLastNode2 = _interopRequireDefault(_getLastNode); var _canMerge = require('../canMerge'); var _canMerge2 = _interopRequireDefault(_canMerge); exports['default'] = function (direction) { var wsc = ['width', 'style', 'color'].map(function (d) { return 'border-' + direction + '-' + d; }); var defaults = ['medium', 'none', 'currentColor']; var declaration = 'border-' + direction; var processor = { explode: function explode(rule) { rule.walkDecls(declaration, function (decl) { var values = _postcss.list.space(decl.value); wsc.forEach(function (prop, index) { var node = (0, _clone2['default'])(decl); node.prop = prop; node.value = values[index]; if (node.value === undefined) { node.value = defaults[index]; } rule.insertAfter(decl, node); }); decl.remove(); }); }, merge: function merge(rule) { var decls = rule.nodes.filter(function (node) { return node.prop && ~wsc.indexOf(node.prop); }); var _loop = function () { var lastNode = decls[decls.length - 1]; var props = decls.filter(function (node) { return node.important === lastNode.important; }); if (_hasAllProps2['default'].apply(undefined, [props].concat(wsc)) && _canMerge2['default'].apply(undefined, props)) { var values = wsc.map(function (prop) { return (0, _getLastNode2['default'])(props, prop).value; }); var value = values.concat(['']).reduceRight(function (prev, cur, i) { if (prev === '' && cur === defaults[i]) { return prev; } return cur + " " + prev; }).trim(); if (value === '') { value = defaults[0]; } var shorthand = (0, _clone2['default'])(lastNode); shorthand.prop = declaration; shorthand.value = value; rule.insertAfter(lastNode, shorthand); props.forEach(function (prop) { return prop.remove(); }); } decls = decls.filter(function (node) { return ! ~props.indexOf(node); }); }; while (decls.length) { _loop(); } } }; return processor; }; module.exports = exports['default'];
synchronit/synchronit_website
zensum/node_modules/postcss-merge-longhand/dist/lib/decl/border-base.js
JavaScript
apache-2.0
3,293
/** * @license AngularJS v1.3.10 * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) {'use strict'; var $sanitizeMinErr = angular.$$minErr('$sanitize'); /** * @ngdoc module * @name ngSanitize * @description * * # ngSanitize * * The `ngSanitize` module provides functionality to sanitize HTML. * * * <div doc-module-components="ngSanitize"></div> * * See {@link ngSanitize.$sanitize `$sanitize`} for usage. */ /* * HTML Parser By Misko Hevery (misko@hevery.com) * based on: HTML Parser By John Resig (ejohn.org) * Original code by Erik Arvidsson, Mozilla Public License * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js * * // Use like so: * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * */ /** * @ngdoc service * @name $sanitize * @kind function * * @description * The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are * then serialized back to properly escaped html string. This means that no unsafe input can make * it into the returned string, however, since our parser is more strict than a typical browser * parser, it's possible that some obscure input, which would be recognized as valid HTML by a * browser, won't make it through the sanitizer. The input may also contain SVG markup. * The whitelist is configured using the functions `aHrefSanitizationWhitelist` and * `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider `$compileProvider`}. * * @param {string} html HTML input. * @returns {string} Sanitized HTML. * * @example <example module="sanitizeExample" deps="angular-sanitize.js"> <file name="index.html"> <script> angular.module('sanitizeExample', ['ngSanitize']) .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) { $scope.snippet = '<p style="color:blue">an html\n' + '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' + 'snippet</p>'; $scope.deliberatelyTrustDangerousSnippet = function() { return $sce.trustAsHtml($scope.snippet); }; }]); </script> <div ng-controller="ExampleController"> Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea> <table> <tr> <td>Directive</td> <td>How</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="bind-html-with-sanitize"> <td>ng-bind-html</td> <td>Automatically uses $sanitize</td> <td><pre>&lt;div ng-bind-html="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng-bind-html="snippet"></div></td> </tr> <tr id="bind-html-with-trust"> <td>ng-bind-html</td> <td>Bypass $sanitize by explicitly trusting the dangerous value</td> <td> <pre>&lt;div ng-bind-html="deliberatelyTrustDangerousSnippet()"&gt; &lt;/div&gt;</pre> </td> <td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td> </tr> <tr id="bind-default"> <td>ng-bind</td> <td>Automatically escapes</td> <td><pre>&lt;div ng-bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng-bind="snippet"></div></td> </tr> </table> </div> </file> <file name="protractor.js" type="protractor"> it('should sanitize the html snippet by default', function() { expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()). toBe('<p>an html\n<em>click here</em>\nsnippet</p>'); }); it('should inline raw snippet if bound to a trusted value', function() { expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()). toBe("<p style=\"color:blue\">an html\n" + "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + "snippet</p>"); }); it('should escape snippet without any filter', function() { expect(element(by.css('#bind-default div')).getInnerHtml()). toBe("&lt;p style=\"color:blue\"&gt;an html\n" + "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" + "snippet&lt;/p&gt;"); }); it('should update', function() { element(by.model('snippet')).clear(); element(by.model('snippet')).sendKeys('new <b onclick="alert(1)">text</b>'); expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()). toBe('new <b>text</b>'); expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe( 'new <b onclick="alert(1)">text</b>'); expect(element(by.css('#bind-default div')).getInnerHtml()).toBe( "new &lt;b onclick=\"alert(1)\"&gt;text&lt;/b&gt;"); }); </file> </example> */ function $SanitizeProvider() { this.$get = ['$$sanitizeUri', function($$sanitizeUri) { return function(html) { var buf = []; htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) { return !/^unsafe/.test($$sanitizeUri(uri, isImage)); })); return buf.join(''); }; }]; } function sanitizeText(chars) { var buf = []; var writer = htmlSanitizeWriter(buf, angular.noop); writer.chars(chars); return buf.join(''); } // Regular Expressions for parsing tags and attributes var START_TAG_REGEXP = /^<((?:[a-zA-Z])[\w:-]*)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*(>?)/, END_TAG_REGEXP = /^<\/\s*([\w:-]+)[^>]*>/, ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g, BEGIN_TAG_REGEXP = /^</, BEGING_END_TAGE_REGEXP = /^<\//, COMMENT_REGEXP = /<!--(.*?)-->/g, DOCTYPE_REGEXP = /<!DOCTYPE([^>]*?)>/i, CDATA_REGEXP = /<!\[CDATA\[(.*?)]]>/g, SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g, // Match everything outside of normal chars and " (quote character) NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g; // Good source of info about elements and attributes // http://dev.w3.org/html5/spec/Overview.html#semantics // http://simon.html5.org/html-elements // Safe Void Elements - HTML5 // http://dev.w3.org/html5/spec/Overview.html#void-elements var voidElements = makeMap("area,br,col,hr,img,wbr"); // Elements that you can, intentionally, leave open (and which close themselves) // http://dev.w3.org/html5/spec/Overview.html#optional-tags var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"), optionalEndTagInlineElements = makeMap("rp,rt"), optionalEndTagElements = angular.extend({}, optionalEndTagInlineElements, optionalEndTagBlockElements); // Safe Block Elements - HTML5 var blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap("address,article," + "aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5," + "h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul")); // Inline Elements - HTML5 var inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b," + "bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s," + "samp,small,span,strike,strong,sub,sup,time,tt,u,var")); // SVG Elements // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements var svgElements = makeMap("animate,animateColor,animateMotion,animateTransform,circle,defs," + "desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,hkern,image,linearGradient," + "line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,radialGradient,rect,set," + "stop,svg,switch,text,title,tspan,use"); // Special Elements (can contain anything) var specialElements = makeMap("script,style"); var validElements = angular.extend({}, voidElements, blockElements, inlineElements, optionalEndTagElements, svgElements); //Attributes that have href and hence need to be sanitized var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap,xlink:href"); var htmlAttrs = makeMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+ 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,'+ 'id,ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,'+ 'scope,scrolling,shape,size,span,start,summary,target,title,type,'+ 'valign,value,vspace,width'); // SVG attributes (without "id" and "name" attributes) // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes var svgAttrs = makeMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' + 'attributeName,attributeType,baseProfile,bbox,begin,by,calcMode,cap-height,class,color,' + 'color-rendering,content,cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,' + 'font-size,font-stretch,font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,' + 'gradientUnits,hanging,height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,' + 'keySplines,keyTimes,lang,marker-end,marker-mid,marker-start,markerHeight,markerUnits,' + 'markerWidth,mathematical,max,min,offset,opacity,orient,origin,overline-position,' + 'overline-thickness,panose-1,path,pathLength,points,preserveAspectRatio,r,refX,refY,' + 'repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,' + 'stemv,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,stroke,' + 'stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,' + 'stroke-opacity,stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,' + 'underline-position,underline-thickness,unicode,unicode-range,units-per-em,values,version,' + 'viewBox,visibility,width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,' + 'xlink:show,xlink:title,xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,' + 'zoomAndPan'); var validAttrs = angular.extend({}, uriAttrs, svgAttrs, htmlAttrs); function makeMap(str) { var obj = {}, items = str.split(','), i; for (i = 0; i < items.length; i++) obj[items[i]] = true; return obj; } /** * @example * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * * @param {string} html string * @param {object} handler */ function htmlParser(html, handler) { if (typeof html !== 'string') { if (html === null || typeof html === 'undefined') { html = ''; } else { html = '' + html; } } var index, chars, match, stack = [], last = html, text; stack.last = function() { return stack[ stack.length - 1 ]; }; while (html) { text = ''; chars = true; // Make sure we're not in a script or style element if (!stack.last() || !specialElements[ stack.last() ]) { // Comment if (html.indexOf("<!--") === 0) { // comments containing -- are not allowed unless they terminate the comment index = html.indexOf("--", 4); if (index >= 0 && html.lastIndexOf("-->", index) === index) { if (handler.comment) handler.comment(html.substring(4, index)); html = html.substring(index + 3); chars = false; } // DOCTYPE } else if (DOCTYPE_REGEXP.test(html)) { match = html.match(DOCTYPE_REGEXP); if (match) { html = html.replace(match[0], ''); chars = false; } // end tag } else if (BEGING_END_TAGE_REGEXP.test(html)) { match = html.match(END_TAG_REGEXP); if (match) { html = html.substring(match[0].length); match[0].replace(END_TAG_REGEXP, parseEndTag); chars = false; } // start tag } else if (BEGIN_TAG_REGEXP.test(html)) { match = html.match(START_TAG_REGEXP); if (match) { // We only have a valid start-tag if there is a '>'. if (match[4]) { html = html.substring(match[0].length); match[0].replace(START_TAG_REGEXP, parseStartTag); } chars = false; } else { // no ending tag found --- this piece should be encoded as an entity. text += '<'; html = html.substring(1); } } if (chars) { index = html.indexOf("<"); text += index < 0 ? html : html.substring(0, index); html = index < 0 ? "" : html.substring(index); if (handler.chars) handler.chars(decodeEntities(text)); } } else { html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'), function(all, text) { text = text.replace(COMMENT_REGEXP, "$1").replace(CDATA_REGEXP, "$1"); if (handler.chars) handler.chars(decodeEntities(text)); return ""; }); parseEndTag("", stack.last()); } if (html == last) { throw $sanitizeMinErr('badparse', "The sanitizer was unable to parse the following block " + "of html: {0}", html); } last = html; } // Clean up any remaining tags parseEndTag(); function parseStartTag(tag, tagName, rest, unary) { tagName = angular.lowercase(tagName); if (blockElements[ tagName ]) { while (stack.last() && inlineElements[ stack.last() ]) { parseEndTag("", stack.last()); } } if (optionalEndTagElements[ tagName ] && stack.last() == tagName) { parseEndTag("", tagName); } unary = voidElements[ tagName ] || !!unary; if (!unary) stack.push(tagName); var attrs = {}; rest.replace(ATTR_REGEXP, function(match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) { var value = doubleQuotedValue || singleQuotedValue || unquotedValue || ''; attrs[name] = decodeEntities(value); }); if (handler.start) handler.start(tagName, attrs, unary); } function parseEndTag(tag, tagName) { var pos = 0, i; tagName = angular.lowercase(tagName); if (tagName) // Find the closest opened tag of the same type for (pos = stack.length - 1; pos >= 0; pos--) if (stack[ pos ] == tagName) break; if (pos >= 0) { // Close all the open elements, up the stack for (i = stack.length - 1; i >= pos; i--) if (handler.end) handler.end(stack[ i ]); // Remove the open elements from the stack stack.length = pos; } } } var hiddenPre=document.createElement("pre"); var spaceRe = /^(\s*)([\s\S]*?)(\s*)$/; /** * decodes all entities into regular string * @param value * @returns {string} A string with decoded entities. */ function decodeEntities(value) { if (!value) { return ''; } // Note: IE8 does not preserve spaces at the start/end of innerHTML // so we must capture them and reattach them afterward var parts = spaceRe.exec(value); var spaceBefore = parts[1]; var spaceAfter = parts[3]; var content = parts[2]; if (content) { hiddenPre.innerHTML=content.replace(/</g,"&lt;"); // innerText depends on styling as it doesn't display hidden elements. // Therefore, it's better to use textContent not to cause unnecessary // reflows. However, IE<9 don't support textContent so the innerText // fallback is necessary. content = 'textContent' in hiddenPre ? hiddenPre.textContent : hiddenPre.innerText; } return spaceBefore + content + spaceAfter; } /** * Escapes all potentially dangerous characters, so that the * resulting string can be safely inserted into attribute or * element text. * @param value * @returns {string} escaped text */ function encodeEntities(value) { return value. replace(/&/g, '&amp;'). replace(SURROGATE_PAIR_REGEXP, function(value) { var hi = value.charCodeAt(0); var low = value.charCodeAt(1); return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';'; }). replace(NON_ALPHANUMERIC_REGEXP, function(value) { // unsafe chars are: \u0000-\u001f \u007f-\u009f \u00ad \u0600-\u0604 \u070f \u17b4 \u17b5 \u200c-\u200f \u2028-\u202f \u2060-\u206f \ufeff \ufff0-\uffff from jslint.com/lint.html // decimal values are: 0-31, 127-159, 173, 1536-1540, 1807, 6068, 6069, 8204-8207, 8232-8239, 8288-8303, 65279, 65520-65535 var c = value.charCodeAt(0); // if unsafe character encode if(c <= 159 || c == 173 || (c >= 1536 && c <= 1540) || c == 1807 || c == 6068 || c == 6069 || (c >= 8204 && c <= 8207) || (c >= 8232 && c <= 8239) || (c >= 8288 && c <= 8303) || c == 65279 || (c >= 65520 && c <= 65535)) return '&#' + c + ';'; return value; // avoids multilingual issues }). replace(/</g, '&lt;'). replace(/>/g, '&gt;'); } var trim = (function() { // native trim is way faster: http://jsperf.com/angular-trim-test // but IE doesn't have it... :-( // TODO: we should move this into IE/ES5 polyfill if (!String.prototype.trim) { return function(value) { return angular.isString(value) ? value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : value; }; } return function(value) { return angular.isString(value) ? value.trim() : value; }; })(); // Custom logic for accepting certain style options only - textAngular // Currently allows only the color, background-color, text-align, float, width and height attributes // all other attributes should be easily done through classes. function validStyles(styleAttr){ var result = ''; var styleArray = styleAttr.split(';'); angular.forEach(styleArray, function(value){ var v = value.split(':'); if(v.length == 2){ var key = trim(angular.lowercase(v[0])); var value = trim(angular.lowercase(v[1])); if( (key === 'color' || key === 'background-color') && ( value.match(/^rgb\([0-9%,\. ]*\)$/i) || value.match(/^rgba\([0-9%,\. ]*\)$/i) || value.match(/^hsl\([0-9%,\. ]*\)$/i) || value.match(/^hsla\([0-9%,\. ]*\)$/i) || value.match(/^#[0-9a-f]{3,6}$/i) || value.match(/^[a-z]*$/i) ) || key === 'text-align' && ( value === 'left' || value === 'right' || value === 'center' || value === 'justify' ) || key === 'float' && ( value === 'left' || value === 'right' || value === 'none' ) || (key === 'width' || key === 'height') && ( value.match(/[0-9\.]*(px|em|rem|%)/) ) ) result += key + ': ' + value + ';'; } }); return result; } // this function is used to manually allow specific attributes on specific tags with certain prerequisites function validCustomTag(tag, attrs, lkey, value){ // catch the div placeholder for the iframe replacement if (tag === 'img' && attrs['ta-insert-video']){ if(lkey === 'ta-insert-video' || lkey === 'allowfullscreen' || lkey === 'frameborder' || (lkey === 'contenteditble' && value === 'false')) return true; } return false; } /** * create an HTML/XML writer which writes to buffer * @param {Array} buf use buf.jain('') to get out sanitized html string * @returns {object} in the form of { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * } */ function htmlSanitizeWriter(buf, uriValidator) { var ignore = false; var out = angular.bind(buf, buf.push); return { start: function(tag, attrs, unary) { tag = angular.lowercase(tag); if (!ignore && specialElements[tag]) { ignore = tag; } if (!ignore && validElements[tag] === true) { out('<'); out(tag); angular.forEach(attrs, function(value, key) { var lkey=angular.lowercase(key); var isImage=(tag === 'img' && lkey === 'src') || (lkey === 'background'); if ((lkey === 'style' && (value = validStyles(value)) !== '') || validCustomTag(tag, attrs, lkey, value) || validAttrs[lkey] === true && (uriAttrs[lkey] !== true || uriValidator(value, isImage))) { out(' '); out(key); out('="'); out(encodeEntities(value)); out('"'); } }); out(unary ? '/>' : '>'); } }, end: function(tag) { tag = angular.lowercase(tag); if (!ignore && validElements[tag] === true) { out('</'); out(tag); out('>'); } if (tag == ignore) { ignore = false; } }, chars: function(chars) { if (!ignore) { out(encodeEntities(chars)); } } }; } // define ngSanitize module and register $sanitize service angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider); /* global sanitizeText: false */ /** * @ngdoc filter * @name linky * @kind function * * @description * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and * plain email address links. * * Requires the {@link ngSanitize `ngSanitize`} module to be installed. * * @param {string} text Input text. * @param {string} target Window (_blank|_self|_parent|_top) or named frame to open links in. * @returns {string} Html-linkified text. * * @usage <span ng-bind-html="linky_expression | linky"></span> * * @example <example module="linkyExample" deps="angular-sanitize.js"> <file name="index.html"> <script> angular.module('linkyExample', ['ngSanitize']) .controller('ExampleController', ['$scope', function($scope) { $scope.snippet = 'Pretty text with some links:\n'+ 'http://angularjs.org/,\n'+ 'mailto:us@somewhere.org,\n'+ 'another@somewhere.org,\n'+ 'and one more: ftp://127.0.0.1/.'; $scope.snippetWithTarget = 'http://angularjs.org/'; }]); </script> <div ng-controller="ExampleController"> Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea> <table> <tr> <td>Filter</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="linky-filter"> <td>linky filter</td> <td> <pre>&lt;div ng-bind-html="snippet | linky"&gt;<br>&lt;/div&gt;</pre> </td> <td> <div ng-bind-html="snippet | linky"></div> </td> </tr> <tr id="linky-target"> <td>linky target</td> <td> <pre>&lt;div ng-bind-html="snippetWithTarget | linky:'_blank'"&gt;<br>&lt;/div&gt;</pre> </td> <td> <div ng-bind-html="snippetWithTarget | linky:'_blank'"></div> </td> </tr> <tr id="escaped-html"> <td>no filter</td> <td><pre>&lt;div ng-bind="snippet"&gt;<br>&lt;/div&gt;</pre></td> <td><div ng-bind="snippet"></div></td> </tr> </table> </file> <file name="protractor.js" type="protractor"> it('should linkify the snippet with urls', function() { expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()). toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' + 'another@somewhere.org, and one more: ftp://127.0.0.1/.'); expect(element.all(by.css('#linky-filter a')).count()).toEqual(4); }); it('should not linkify snippet without the linky filter', function() { expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()). toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' + 'another@somewhere.org, and one more: ftp://127.0.0.1/.'); expect(element.all(by.css('#escaped-html a')).count()).toEqual(0); }); it('should update', function() { element(by.model('snippet')).clear(); element(by.model('snippet')).sendKeys('new http://link.'); expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()). toBe('new http://link.'); expect(element.all(by.css('#linky-filter a')).count()).toEqual(1); expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()) .toBe('new http://link.'); }); it('should work with the target property', function() { expect(element(by.id('linky-target')). element(by.binding("snippetWithTarget | linky:'_blank'")).getText()). toBe('http://angularjs.org/'); expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank'); }); </file> </example> */ angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) { var LINKY_URL_REGEXP = /((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"”’]/, MAILTO_REGEXP = /^mailto:/; return function(text, target) { if (!text) return text; var match; var raw = text; var html = []; var url; var i; while ((match = raw.match(LINKY_URL_REGEXP))) { // We can not end in these as they are sometimes found at the end of the sentence url = match[0]; // if we did not match ftp/http/www/mailto then assume mailto if (!match[2] && !match[4]) { url = (match[3] ? 'http://' : 'mailto:') + url; } i = match.index; addText(raw.substr(0, i)); addLink(url, match[0].replace(MAILTO_REGEXP, '')); raw = raw.substring(i + match[0].length); } addText(raw); return $sanitize(html.join('')); function addText(text) { if (!text) { return; } html.push(sanitizeText(text)); } function addLink(url, text) { html.push('<a '); if (angular.isDefined(target)) { html.push('target="', target, '" '); } html.push('href="', url.replace(/"/g, '&quot;'), '">'); addText(text); html.push('</a>'); } }; }]); })(window, window.angular);
walgheraibi/StemCells
ui/js/bower_components/textAngular/src/textAngular-sanitize.js
JavaScript
mit
26,988
<?php /* * This file is part of PHPUnit. * * (c) Sebastian Bergmann <sebastian@phpunit.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Filesystem helpers. * * @since Class available since Release 3.0.0 */ class PHPUnit_Util_Filesystem { /** * @var array */ protected static $buffer = []; /** * Maps class names to source file names: * - PEAR CS: Foo_Bar_Baz -> Foo/Bar/Baz.php * - Namespace: Foo\Bar\Baz -> Foo/Bar/Baz.php * * @param string $className * * @return string * * @since Method available since Release 3.4.0 */ public static function classNameToFilename($className) { return str_replace( ['_', '\\'], DIRECTORY_SEPARATOR, $className ) . '.php'; } }
yeqingwen/Yii2_PHP7_Redis
yii2/vendor/phpunit/phpunit/src/Util/Filesystem.php
PHP
apache-2.0
907
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Security\Core\User; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; use Symfony\Component\Security\Core\Exception\UnsupportedUserException; /** * InMemoryUserProvider is a simple non persistent user provider. * * Useful for testing, demonstration, prototyping, and for simple needs * (a backend with a unique admin for instance) * * @author Fabien Potencier <fabien@symfony.com> */ class InMemoryUserProvider implements UserProviderInterface { private $users; /** * Constructor. * * The user array is a hash where the keys are usernames and the values are * an array of attributes: 'password', 'enabled', and 'roles'. * * @param array $users An array of users */ public function __construct(array $users = array()) { foreach ($users as $username => $attributes) { $password = isset($attributes['password']) ? $attributes['password'] : null; $enabled = isset($attributes['enabled']) ? $attributes['enabled'] : true; $roles = isset($attributes['roles']) ? $attributes['roles'] : array(); $user = new User($username, $password, $roles, $enabled, true, true, true); $this->createUser($user); } } /** * Adds a new User to the provider. * * @param UserInterface $user A UserInterface instance * * @throws \LogicException */ public function createUser(UserInterface $user) { if (isset($this->users[strtolower($user->getUsername())])) { throw new \LogicException('Another user with the same username already exist.'); } $this->users[strtolower($user->getUsername())] = $user; } /** * {@inheritdoc} */ public function loadUserByUsername($username) { if (!isset($this->users[strtolower($username)])) { $ex = new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username)); $ex->setUsername($username); throw $ex; } $user = $this->users[strtolower($username)]; return new User($user->getUsername(), $user->getPassword(), $user->getRoles(), $user->isEnabled(), $user->isAccountNonExpired(), $user->isCredentialsNonExpired(), $user->isAccountNonLocked()); } /** * {@inheritDoc} */ public function refreshUser(UserInterface $user) { if (!$user instanceof User) { throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user))); } return $this->loadUserByUsername($user->getUsername()); } /** * {@inheritDoc} */ public function supportsClass($class) { return $class === 'Symfony\Component\Security\Core\User\User'; } }
TroudIm/troud.im
web/Symfony/vendor/symfony/symfony/src/Symfony/Component/Security/Core/User/InMemoryUserProvider.php
PHP
gpl-2.0
3,091
module.exports = collect function collect (stream) { if (stream._collected) return stream._collected = true stream.pause() stream.on("data", save) stream.on("end", save) var buf = [] function save (b) { if (typeof b === "string") b = new Buffer(b) if (Buffer.isBuffer(b) && !b.length) return buf.push(b) } stream.on("entry", saveEntry) var entryBuffer = [] function saveEntry (e) { collect(e) entryBuffer.push(e) } stream.on("proxy", proxyPause) function proxyPause (p) { p.pause() } // replace the pipe method with a new version that will // unlock the buffered stuff. if you just call .pipe() // without a destination, then it'll re-play the events. stream.pipe = (function (orig) { return function (dest) { // console.error(" === open the pipes", dest && dest.path) // let the entries flow through one at a time. // Once they're all done, then we can resume completely. var e = 0 ;(function unblockEntry () { var entry = entryBuffer[e++] // console.error(" ==== unblock entry", entry && entry.path) if (!entry) return resume() entry.on("end", unblockEntry) if (dest) dest.add(entry) else stream.emit("entry", entry) })() function resume () { stream.removeListener("entry", saveEntry) stream.removeListener("data", save) stream.removeListener("end", save) stream.pipe = orig if (dest) stream.pipe(dest) buf.forEach(function (b) { if (b) stream.emit("data", b) else stream.emit("end") }) stream.resume() } return dest }})(stream.pipe) }
nikste/visualizationDemo
zeppelin-web/node/npm/node_modules/fstream/lib/collect.js
JavaScript
apache-2.0
1,652
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Mvc\Controller\Plugin; use Zend\Mvc\Exception\RuntimeException; use Zend\Session\Container; /** * Plugin to help facilitate Post/Redirect/Get (http://en.wikipedia.org/wiki/Post/Redirect/Get) */ class PostRedirectGet extends AbstractPlugin { /** * @var Container */ protected $sessionContainer; /** * Perform PRG logic * * If a null value is present for the $redirect, the current route is * retrieved and use to generate the URL for redirect. * * If the request method is POST, creates a session container set to expire * after 1 hop containing the values of the POST. It then redirects to the * specified URL using a status 303. * * If the request method is GET, checks to see if we have values in the * session container, and, if so, returns them; otherwise, it returns a * boolean false. * * @param null|string $redirect * @param bool $redirectToUrl * @return \Zend\Http\Response|array|\Traversable|false */ public function __invoke($redirect = null, $redirectToUrl = false) { $controller = $this->getController(); $request = $controller->getRequest(); $container = $this->getSessionContainer(); if ($request->isPost()) { $container->setExpirationHops(1, 'post'); $container->post = $request->getPost()->toArray(); return $this->redirect($redirect, $redirectToUrl); } else { if ($container->post !== null) { $post = $container->post; unset($container->post); return $post; } return false; } } /** * @return Container */ public function getSessionContainer() { if (!isset($this->sessionContainer)) { $this->sessionContainer = new Container('prg_post1'); } return $this->sessionContainer; } /** * @param Container $container * @return PostRedirectGet */ public function setSessionContainer(Container $container) { $this->sessionContainer = $container; return $this; } /** * TODO: Good candidate for traits method in PHP 5.4 with FilePostRedirectGet plugin * * @param string $redirect * @param bool $redirectToUrl * @return \Zend\Http\Response * @throws \Zend\Mvc\Exception\RuntimeException */ protected function redirect($redirect, $redirectToUrl) { $controller = $this->getController(); $params = array(); $options = array('query' => $controller->params()->fromQuery()); $reuseMatchedParams = false; if (null === $redirect) { $routeMatch = $controller->getEvent()->getRouteMatch(); $redirect = $routeMatch->getMatchedRouteName(); //null indicates to redirect for self. $reuseMatchedParams = true; } if (method_exists($controller, 'getPluginManager')) { // get the redirect plugin from the plugin manager $redirector = $controller->getPluginManager()->get('Redirect'); } else { /* * If the user wants to redirect to a route, the redirector has to come * from the plugin manager -- otherwise no router will be injected */ if ($redirectToUrl === false) { throw new RuntimeException('Could not redirect to a route without a router'); } $redirector = new Redirect(); } if ($redirectToUrl === false) { $response = $redirector->toRoute($redirect, $params, $options, $reuseMatchedParams); $response->setStatusCode(303); return $response; } $response = $redirector->toUrl($redirect); $response->setStatusCode(303); return $response; } }
JorikVartanov/zf2
zf2_project/vendor/zendframework/zendframework/library/Zend/Mvc/Controller/Plugin/PostRedirectGet.php
PHP
bsd-3-clause
4,294
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Security\Core\User; use Symfony\Component\Security\Core\Exception\AccountStatusException; use Symfony\Component\Security\Core\Exception\AccountExpiredException; use Symfony\Component\Security\Core\Exception\LockedException; use Symfony\Component\Security\Core\Exception\CredentialsExpiredException; use Symfony\Component\Security\Core\Exception\DisabledException; /** * Adds extra features to a user class related to account status flags. * * This interface can be implemented in place of UserInterface if you'd like * the authentication system to consider different account status flags * during authentication. If any of the methods in this interface return * false, authentication will fail. * * If you need to perform custom logic for any of these situations, then * you will need to register an exception listener and watch for the specific * exception instances thrown in each case. All exceptions are a subclass * of AccountStatusException * * @see UserInterface * @see AccountStatusException * * @author Fabien Potencier <fabien@symfony.com> */ interface AdvancedUserInterface extends UserInterface { /** * Checks whether the user's account has expired. * * Internally, if this method returns false, the authentication system * will throw an AccountExpiredException and prevent login. * * @return Boolean true if the user's account is non expired, false otherwise * * @see AccountExpiredException */ public function isAccountNonExpired(); /** * Checks whether the user is locked. * * Internally, if this method returns false, the authentication system * will throw a LockedException and prevent login. * * @return Boolean true if the user is not locked, false otherwise * * @see LockedException */ public function isAccountNonLocked(); /** * Checks whether the user's credentials (password) has expired. * * Internally, if this method returns false, the authentication system * will throw a CredentialsExpiredException and prevent login. * * @return Boolean true if the user's credentials are non expired, false otherwise * * @see CredentialsExpiredException */ public function isCredentialsNonExpired(); /** * Checks whether the user is enabled. * * Internally, if this method returns false, the authentication system * will throw a DisabledException and prevent login. * * @return Boolean true if the user is enabled, false otherwise * * @see DisabledException */ public function isEnabled(); }
gonzakpo/TPBaseDatos
web/vendor/symfony/symfony/src/Symfony/Component/Security/Core/User/AdvancedUserInterface.php
PHP
mit
2,905
/// <reference path="../../yui/yui.d.ts" /> /// <reference path="../cryptojs.d.ts" /> YUI.add('enc-latin1-test', function (Y) { var C = CryptoJS; Y.Test.Runner.add(new Y.Test.Case({ name: 'Latin1', testStringify: function () { Y.Assert.areEqual('\x12\x34\x56\x78', C.enc.Latin1.stringify(C.lib.WordArray.create([0x12345678]))); }, testParse: function () { Y.Assert.areEqual(C.lib.WordArray.create([0x12345678]).toString(), C.enc.Latin1.parse('\x12\x34\x56\x78').toString()); } })); }, '$Rev$');
rodzewich/playground
types/cryptojs/test/enc-latin1-tests.ts
TypeScript
mit
575
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's // vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. JavaScript code in this file should be added after the last require_* statement. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require rails-ujs //= require turbolinks //= require_tree .
thegillis/from_rails_to_phoenix
widget_market_rails/app/assets/javascripts/application.js
JavaScript
mit
695
YUI.add('escape', function(Y) { /** Provides utility methods for escaping strings. @module escape @class Escape @static @since 3.3.0 **/ var HTML_CHARS = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;', '/': '&#x2F;', '`': '&#x60;' }, Escape = { // -- Public Static Methods ------------------------------------------------ /** Returns a copy of the specified string with special HTML characters escaped. The following characters will be converted to their corresponding character entities: & < > " ' / ` This implementation is based on the [OWASP HTML escaping recommendations][1]. In addition to the characters in the OWASP recommendations, we also escape the <code>&#x60;</code> character, since IE interprets it as an attribute delimiter. If _string_ is not already a string, it will be coerced to a string. [1]: http://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet @method html @param {String} string String to escape. @return {String} Escaped string. @static **/ html: function (string) { return (string + '').replace(/[&<>"'\/`]/g, Escape._htmlReplacer); }, /** Returns a copy of the specified string with special regular expression characters escaped, allowing the string to be used safely inside a regex. The following characters, and all whitespace characters, are escaped: - # $ ^ * ( ) + [ ] { } | \ , . ? If _string_ is not already a string, it will be coerced to a string. @method regex @param {String} string String to escape. @return {String} Escaped string. @static **/ regex: function (string) { return (string + '').replace(/[\-#$\^*()+\[\]{}|\\,.?\s]/g, '\\$&'); }, // -- Protected Static Methods --------------------------------------------- /** * Regex replacer for HTML escaping. * * @method _htmlReplacer * @param {String} match Matched character (must exist in HTML_CHARS). * @returns {String} HTML entity. * @static * @protected */ _htmlReplacer: function (match) { return HTML_CHARS[match]; } }; Escape.regexp = Escape.regex; Y.Escape = Escape; }, '@VERSION@' ,{requires:['yui-base']});
drewfreyling/cdnjs
ajax/libs/yui/3.4.1pr1/escape/escape.js
JavaScript
mit
2,360
// -*- C++ -*- // Copyright (C) 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file hash_standard_resize_policy_imp.hpp * Contains a resize policy implementation. */ PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: hash_standard_resize_policy() : m_size(Size_Policy::get_nearest_larger_size(1)) { trigger_policy_base::notify_externally_resized(m_size); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: hash_standard_resize_policy(const Size_Policy& r_size_policy) : Size_Policy(r_size_policy), m_size(Size_Policy::get_nearest_larger_size(1)) { trigger_policy_base::notify_externally_resized(m_size); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: hash_standard_resize_policy(const Size_Policy& r_size_policy, const Trigger_Policy& r_trigger_policy) : Size_Policy(r_size_policy), Trigger_Policy(r_trigger_policy), m_size(Size_Policy::get_nearest_larger_size(1)) { trigger_policy_base::notify_externally_resized(m_size); } PB_DS_CLASS_T_DEC PB_DS_CLASS_C_DEC:: ~hash_standard_resize_policy() { } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: swap(PB_DS_CLASS_C_DEC& other) { trigger_policy_base::swap(other); size_policy_base::swap(other); std::swap(m_size, other.m_size); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_find_search_start() { trigger_policy_base::notify_find_search_start(); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_find_search_collision() { trigger_policy_base::notify_find_search_collision(); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_find_search_end() { trigger_policy_base::notify_find_search_end(); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_insert_search_start() { trigger_policy_base::notify_insert_search_start(); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_insert_search_collision() { trigger_policy_base::notify_insert_search_collision(); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_insert_search_end() { trigger_policy_base::notify_insert_search_end(); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_erase_search_start() { trigger_policy_base::notify_erase_search_start(); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_erase_search_collision() { trigger_policy_base::notify_erase_search_collision(); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_erase_search_end() { trigger_policy_base::notify_erase_search_end(); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_inserted(size_type num_e) { trigger_policy_base::notify_inserted(num_e); } PB_DS_CLASS_T_DEC inline void PB_DS_CLASS_C_DEC:: notify_erased(size_type num_e) { trigger_policy_base::notify_erased(num_e); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: notify_cleared() { trigger_policy_base::notify_cleared(); } PB_DS_CLASS_T_DEC inline bool PB_DS_CLASS_C_DEC:: is_resize_needed() const { return trigger_policy_base::is_resize_needed(); } PB_DS_CLASS_T_DEC typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: get_new_size(size_type size, size_type num_used_e) const { if (trigger_policy_base::is_grow_needed(size, num_used_e)) return size_policy_base::get_nearest_larger_size(size); return size_policy_base::get_nearest_smaller_size(size); } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: notify_resized(size_type new_size) { trigger_policy_base::notify_resized(new_size); m_size = new_size; } PB_DS_CLASS_T_DEC inline typename PB_DS_CLASS_C_DEC::size_type PB_DS_CLASS_C_DEC:: get_actual_size() const { PB_DS_STATIC_ASSERT(access, external_size_access); return m_size; } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: resize(size_type new_size) { PB_DS_STATIC_ASSERT(access, external_size_access); size_type actual_size = size_policy_base::get_nearest_larger_size(1); while (actual_size < new_size) { const size_type pot = size_policy_base::get_nearest_larger_size(actual_size); if (pot == actual_size && pot < new_size) __throw_resize_error(); actual_size = pot; } if (actual_size > 0) --actual_size; const size_type old_size = m_size; __try { do_resize(actual_size - 1); } __catch(insert_error& ) { m_size = old_size; __throw_resize_error(); } __catch(...) { m_size = old_size; __throw_exception_again; } } PB_DS_CLASS_T_DEC void PB_DS_CLASS_C_DEC:: do_resize(size_type) { // Do nothing } PB_DS_CLASS_T_DEC Trigger_Policy& PB_DS_CLASS_C_DEC:: get_trigger_policy() { return *this; } PB_DS_CLASS_T_DEC const Trigger_Policy& PB_DS_CLASS_C_DEC:: get_trigger_policy() const { return *this; } PB_DS_CLASS_T_DEC Size_Policy& PB_DS_CLASS_C_DEC:: get_size_policy() { return *this; } PB_DS_CLASS_T_DEC const Size_Policy& PB_DS_CLASS_C_DEC:: get_size_policy() const { return *this; }
chcbaram/FPGA
zap-2.3.0-windows/papilio-zap-ide/hardware/tools/g++_arm_none_eabi/arm-none-eabi/include/c++/4.4.1/ext/pb_ds/detail/resize_policy/hash_standard_resize_policy_imp.hpp
C++
mit
6,302
class Hashpump < Formula desc "Tool to exploit hash length extension attack" homepage "https://github.com/bwall/HashPump" url "https://github.com/bwall/HashPump/archive/v1.2.0.tar.gz" sha256 "d002e24541c6604e5243e5325ef152e65f9fcd00168a9fa7a06ad130e28b811b" bottle do cellar :any revision 1 sha256 "bc00f1a7c60564fed1ebf0ece40306aa169e4a7ddf7f9c8d56c7088130f5e530" => :el_capitan sha256 "8b33f44272b46174184639f3a6044f47151756039068343262d3e2cbe4a26a7c" => :yosemite sha256 "667650946f6e697657832f9f906f3a548bc55991e2422f8cbbbe7c793434111f" => :mavericks sha256 "a776ebf2d22d7b5fa492308fff20409696064ea70149c5cac695b75bcf004d7c" => :mountain_lion end option "without-python", "Build without python 2 support" depends_on "openssl" depends_on :python => :recommended if MacOS.version <= :snow_leopard depends_on :python3 => :optional # Remove on next release patch do url "https://patch-diff.githubusercontent.com/raw/bwall/HashPump/pull/14.diff" sha256 "47236fed281000726942740002e44ef8bb90b05f55b2e7deeb183d9f708906c1" end def install bin.mkpath system "make", "INSTALLLOCATION=#{bin}", "CXX=#{ENV.cxx}", "install" Language::Python.each_python(build) do |python, _version| system python, *Language::Python.setup_install_args(prefix) end end test do output = %x(#{bin}/hashpump -s '6d5f807e23db210bc254a28be2d6759a0f5f5d99' \\ -d 'count=10&lat=37.351&user_id=1&long=-119.827&waffle=eggo' \\ -a '&waffle=liege' -k 14) assert output.include? "0e41270260895979317fff3898ab85668953aaa2" assert output.include? "&waffle=liege" assert_equal 0, $?.exitstatus end end
rokn/Count_Words_2015
fetched_code/ruby/hashpump.rb
Ruby
mit
1,720
import React, {useState} from 'react'; import { ScrollView, StyleSheet, Text, TouchableOpacity, Platform, Linking, } from 'react-native'; import AutoHeightWebView from 'react-native-autoheight-webview'; import { autoHeightHtml0, autoHeightHtml1, autoHeightScript, autoWidthHtml0, autoWidthHtml1, autoWidthScript, autoDetectLinkScript, style0, inlineBodyStyle, } from './config'; const onShouldStartLoadWithRequest = result => { console.log(result); return true; }; const onError = ({nativeEvent}) => console.error('WebView error: ', nativeEvent); const onMessage = event => { const {data} = event.nativeEvent; let messageData; // maybe parse stringified JSON try { messageData = JSON.parse(data); } catch (e) { console.log(e.message); } if (typeof messageData === 'object') { const {url} = messageData; // check if this message concerns us if (url && url.startsWith('http')) { Linking.openURL(url).catch(error => console.error('An error occurred', error), ); } } }; const onHeightLoadStart = () => console.log('height on load start'); const onHeightLoad = () => console.log('height on load'); const onHeightLoadEnd = () => console.log('height on load end'); const onWidthLoadStart = () => console.log('width on load start'); const onWidthLoad = () => console.log('width on load'); const onWidthLoadEnd = () => console.log('width on load end'); const Explorer = () => { const [{widthHtml, heightHtml}, setHtml] = useState({ widthHtml: autoWidthHtml0, heightHtml: autoHeightHtml0, }); const changeSource = () => setHtml({ widthHtml: widthHtml === autoWidthHtml0 ? autoWidthHtml1 : autoWidthHtml0, heightHtml: heightHtml === autoHeightHtml0 ? autoHeightHtml1 : autoHeightHtml0, }); const [{widthStyle, heightStyle}, setStyle] = useState({ heightStyle: null, widthStyle: inlineBodyStyle, }); const changeStyle = () => setStyle({ widthStyle: widthStyle === inlineBodyStyle ? style0 + inlineBodyStyle : inlineBodyStyle, heightStyle: heightStyle === null ? style0 : null, }); const [{widthScript, heightScript}, setScript] = useState({ heightScript: autoDetectLinkScript, widthScript: null, }); const changeScript = () => setScript({ widthScript: widthScript == autoWidthScript ? autoWidthScript : null, heightScript: heightScript !== autoDetectLinkScript ? autoDetectLinkScript : autoHeightScript + autoDetectLinkScript, }); const [heightSize, setHeightSize] = useState({height: 0, width: 0}); const [widthSize, setWidthSize] = useState({height: 0, width: 0}); return ( <ScrollView style={{ paddingTop: 45, backgroundColor: 'lightyellow', }} contentContainerStyle={{ justifyContent: 'center', alignItems: 'center', }}> <AutoHeightWebView customStyle={heightStyle} onError={onError} onLoad={onHeightLoad} onLoadStart={onHeightLoadStart} onLoadEnd={onHeightLoadEnd} onShouldStartLoadWithRequest={onShouldStartLoadWithRequest} onSizeUpdated={setHeightSize} source={{html: heightHtml}} customScript={heightScript} onMessage={onMessage} /> <Text style={{padding: 5}}> height: {heightSize.height}, width: {heightSize.width} </Text> <AutoHeightWebView style={{ marginTop: 15, }} customStyle={widthStyle} onError={onError} onLoad={onWidthLoad} onLoadStart={onWidthLoadStart} onLoadEnd={onWidthLoadEnd} onShouldStartLoadWithRequest={onShouldStartLoadWithRequest} onSizeUpdated={setWidthSize} allowFileAccessFromFileURLs={true} allowUniversalAccessFromFileURLs={true} source={{ html: widthHtml, baseUrl: Platform.OS === 'android' ? 'file:///android_asset/' : 'web/', }} customScript={widthScript} /> <Text style={{padding: 5}}> height: {widthSize.height}, width: {widthSize.width} </Text> <TouchableOpacity onPress={changeSource} style={styles.button}> <Text>change source</Text> </TouchableOpacity> <TouchableOpacity onPress={changeStyle} style={styles.button}> <Text>change style</Text> </TouchableOpacity> <TouchableOpacity onPress={changeScript} style={[styles.button, {marginBottom: 100}]}> <Text>change script</Text> </TouchableOpacity> </ScrollView> ); }; const styles = StyleSheet.create({ button: { marginTop: 15, backgroundColor: 'aliceblue', borderRadius: 5, padding: 5, }, }); export default Explorer;
iou90/react-native-autoheight-webview
demo/App.js
JavaScript
isc
4,845
/* * Copyright © 2015 <code@io7m.com> http://io7m.com * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package com.io7m.jcanephora.fake; import com.io7m.jcanephora.core.JCGLArrayBufferType; import com.io7m.jcanephora.core.JCGLArrayBufferUsableType; import com.io7m.jcanephora.core.JCGLBufferUpdateType; import com.io7m.jcanephora.core.JCGLException; import com.io7m.jcanephora.core.JCGLExceptionBufferNotBound; import com.io7m.jcanephora.core.JCGLExceptionDeleted; import com.io7m.jcanephora.core.JCGLResources; import com.io7m.jcanephora.core.JCGLUsageHint; import com.io7m.jcanephora.core.api.JCGLArrayBuffersType; import com.io7m.jcanephora.core.api.JCGLByteBufferProducerType; import com.io7m.jnull.NullCheck; import com.io7m.jnull.Nullable; import com.io7m.jranges.RangeCheck; import com.io7m.jranges.Ranges; import com.io7m.junsigned.ranges.UnsignedRangeInclusiveL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.ByteBuffer; import java.util.Objects; import java.util.Optional; final class FakeArrayBuffers implements JCGLArrayBuffersType { private static final Logger LOG; static { LOG = LoggerFactory.getLogger(FakeArrayBuffers.class); } private final FakeContext context; private @Nullable FakeArrayBuffer bind; FakeArrayBuffers(final FakeContext c) { this.context = NullCheck.notNull(c, "Context"); } private void actualBind(final FakeArrayBuffer a) { LOG.trace("bind {} -> {}", this.bind, a); if (!Objects.equals(a, this.bind)) { this.bind = a; } } private void actualUnbind() { LOG.trace( "unbind {} -> {}", this.bind, null); if (this.bind != null) { this.bind = null; } } @Override public ByteBuffer arrayBufferRead( final JCGLArrayBufferUsableType a, final JCGLByteBufferProducerType f) throws JCGLException, JCGLExceptionDeleted, JCGLExceptionBufferNotBound { NullCheck.notNull(a, "Array"); this.checkArray(a); if (Objects.equals(a, this.bind)) { final UnsignedRangeInclusiveL r = a.byteRange(); final long size = r.getInterval(); final ByteBuffer b = f.apply(size); b.rewind(); final FakeArrayBuffer fa = (FakeArrayBuffer) a; final ByteBuffer fa_data = fa.getData(); /* * XXX: Clearly overflowing integers. */ final long lo = r.getLower(); final long hi = r.getUpper(); for (long index = lo; Long.compareUnsigned(index, hi) <= 0; ++index) { final int ii = (int) index; final byte x = fa_data.get(ii); b.put(ii, x); } return b; } throw this.notBound(a); } @Override public JCGLArrayBufferType arrayBufferAllocate( final long size, final JCGLUsageHint usage) throws JCGLException { RangeCheck.checkIncludedInLong( size, "Size", Ranges.NATURAL_LONG, "Valid size range"); LOG.debug( "allocate ({} bytes, {})", Long.valueOf(size), usage); final ByteBuffer data = ByteBuffer.allocate((int) size); final FakeArrayBuffer ao = new FakeArrayBuffer( this.context, this.context.getFreshID(), data, usage); this.actualBind(ao); return ao; } @Override public void arrayBufferReallocate(final JCGLArrayBufferUsableType a) throws JCGLException, JCGLExceptionDeleted, JCGLExceptionBufferNotBound { this.checkArray(a); if (Objects.equals(a, this.bind)) { final UnsignedRangeInclusiveL r = a.byteRange(); final long size = r.getInterval(); final JCGLUsageHint usage = a.usageHint(); if (LOG.isDebugEnabled()) { LOG.debug( "reallocate ({} bytes, {})", Long.valueOf(size), usage); } } else { throw this.notBound(a); } } @Override public Optional<JCGLArrayBufferUsableType> arrayBufferGetCurrentlyBound() throws JCGLException { return Optional.ofNullable(this.bind); } @Override public boolean arrayBufferAnyIsBound() throws JCGLException { return this.bind != null; } @Override public boolean arrayBufferIsBound( final JCGLArrayBufferUsableType a) throws JCGLException { this.checkArray(a); return Objects.equals(a, this.bind); } @Override public void arrayBufferBind(final JCGLArrayBufferUsableType a) throws JCGLException, JCGLExceptionDeleted { this.checkArray(a); this.actualBind((FakeArrayBuffer) a); } private void checkArray(final JCGLArrayBufferUsableType a) { FakeCompatibilityChecks.checkArrayBuffer(this.context, a); JCGLResources.checkNotDeleted(a); } @Override public void arrayBufferUnbind() throws JCGLException { this.actualUnbind(); } @Override public void arrayBufferDelete(final JCGLArrayBufferType a) throws JCGLException, JCGLExceptionDeleted { this.checkArray(a); LOG.debug("delete {}", Integer.valueOf(a.glName())); ((FakeArrayBuffer) a).setDeleted(); if (Objects.equals(a, this.bind)) { this.actualUnbind(); } } @Override public void arrayBufferUpdate( final JCGLBufferUpdateType<JCGLArrayBufferType> u) throws JCGLException, JCGLExceptionDeleted, JCGLExceptionBufferNotBound { NullCheck.notNull(u, "Update"); final JCGLArrayBufferType a = u.buffer(); this.checkArray(a); if (Objects.equals(a, this.bind)) { final UnsignedRangeInclusiveL r = u.dataUpdateRange(); final ByteBuffer data = u.data(); data.rewind(); final FakeArrayBuffer fa = (FakeArrayBuffer) a; final ByteBuffer fa_data = fa.getData(); /* * XXX: Clearly overflowing integers. */ final long lo = r.getLower(); final long hi = r.getUpper(); for (long index = lo; Long.compareUnsigned(index, hi) <= 0; ++index) { final int ii = (int) index; fa_data.put(ii, data.get(ii)); } } else { throw this.notBound(a); } } private JCGLExceptionBufferNotBound notBound( final JCGLArrayBufferUsableType a) { final StringBuilder sb = new StringBuilder(128); sb.append("Buffer is not bound."); sb.append(System.lineSeparator()); sb.append(" Required: "); sb.append(a); sb.append(System.lineSeparator()); sb.append(" Actual: "); sb.append(this.bind == null ? "none" : this.bind); return new JCGLExceptionBufferNotBound(sb.toString()); } }
io7m/jcanephora
com.io7m.jcanephora.fake/src/main/java/com/io7m/jcanephora/fake/FakeArrayBuffers.java
Java
isc
7,055
// Copyright (c) 2019 The Decred developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package lru import ( "container/list" "sync" ) // kv represents a key-value pair. type kv struct { key interface{} value interface{} } // KVCache provides a concurrency safe least-recently-used key/value cache with // nearly O(1) lookups, inserts, and deletions. The cache is limited to a // maximum number of items with eviction for the oldest entry when the // limit is exceeded. // // The NewKVCache function must be used to create a usable cache since the zero // value of this struct is not valid. type KVCache struct { mtx sync.Mutex cache map[interface{}]*list.Element // nearly O(1) lookups list *list.List // O(1) insert, update, delete limit uint } // Lookup returns the associated value of the passed key, if it is a member of // the cache. Looking up an existing item makes it the most recently used item. // // This function is safe for concurrent access. func (m *KVCache) Lookup(key interface{}) (interface{}, bool) { var value interface{} m.mtx.Lock() node, exists := m.cache[key] if exists { m.list.MoveToFront(node) pair := node.Value.(*kv) value = pair.value } m.mtx.Unlock() return value, exists } // Contains returns whether or not the passed key is a member of the cache. // The associated item of the passed key if it exists becomes the most // recently used item. // // This function is safe for concurrent access. func (m *KVCache) Contains(key interface{}) bool { m.mtx.Lock() node, exists := m.cache[key] if exists { m.list.MoveToFront(node) } m.mtx.Unlock() return exists } // Add adds the passed k/v to the cache and handles eviction of the oldest pair // if adding the new pair would exceed the max limit. Adding an existing pair // makes it the most recently used item. // // This function is safe for concurrent access. func (m *KVCache) Add(key interface{}, value interface{}) { m.mtx.Lock() defer m.mtx.Unlock() // When the limit is zero, nothing can be added to the cache, so just // return. if m.limit == 0 { return } // When the k/v already exists update the value and move it to the // front of the list thereby marking it most recently used. if node, exists := m.cache[key]; exists { node.Value.(*kv).value = value m.list.MoveToFront(node) m.cache[key] = node return } // Evict the least recently used k/v (back of the list) if the new // k/v would exceed the size limit for the cache. Also reuse the list // node so a new one doesn't have to be allocated. if uint(len(m.cache))+1 > m.limit { node := m.list.Back() lru := node.Value.(*kv) // Evict least recently used k/v. delete(m.cache, lru.key) // Reuse the list node of the k/v that was just evicted for the new // k/v. lru.key = key lru.value = value m.list.MoveToFront(node) m.cache[key] = node return } // The limit hasn't been reached yet, so just add the new k/v. node := m.list.PushFront(&kv{key: key, value: value}) m.cache[key] = node } // Delete deletes the k/v associated with passed key from the cache // (if it exists). // // This function is safe for concurrent access. func (m *KVCache) Delete(key interface{}) { m.mtx.Lock() if node, exists := m.cache[key]; exists { m.list.Remove(node) delete(m.cache, key) } m.mtx.Unlock() } // NewKVCache returns an initialized and empty KV LRU cache. // See the documentation for KV for more details. func NewKVCache(limit uint) KVCache { return KVCache{ cache: make(map[interface{}]*list.Element), list: list.New(), limit: limit, } }
decred/dcrd
lru/kv.go
GO
isc
3,662
<?php require_once "dbms.php"; $respuesta = getFieldPhoto("select photo from " . $_GET["source"] . " where id_" . $_GET["source"] . "=" . $_GET["id"]); //header('Content-type:image/gif'); //echo $respuesta; echo(base64_encode($respuesta)); ?>
MiguelAngelCifredo/AmigoInvisible
_bd_/php/getPhoto.php
PHP
isc
242
import { timeout as d3_timeout } from 'd3-timer'; export function uiFlash(context) { var _flashTimer; var _duration = 2000; var _iconName = '#iD-icon-no'; var _iconClass = 'disabled'; var _text = ''; var _textClass; function flash() { if (_flashTimer) { _flashTimer.stop(); } context.container().select('.main-footer-wrap') .classed('footer-hide', true) .classed('footer-show', false); context.container().select('.flash-wrap') .classed('footer-hide', false) .classed('footer-show', true); var content = context.container().select('.flash-wrap').selectAll('.flash-content') .data([0]); // Enter var contentEnter = content.enter() .append('div') .attr('class', 'flash-content'); var iconEnter = contentEnter .append('svg') .attr('class', 'flash-icon') .append('g') .attr('transform', 'translate(10,10)'); iconEnter .append('circle') .attr('r', 9); iconEnter .append('use') .attr('transform', 'translate(-7,-7)') .attr('width', '14') .attr('height', '14'); contentEnter .append('div') .attr('class', 'flash-text'); // Update content = content .merge(contentEnter); content .selectAll('.flash-icon') .attr('class', 'flash-icon ' + (_iconClass || '')); content .selectAll('.flash-icon use') .attr('xlink:href', _iconName); content .selectAll('.flash-text') .attr('class', 'flash-text ' + (_textClass || '')) .text(_text); _flashTimer = d3_timeout(function() { _flashTimer = null; context.container().select('.main-footer-wrap') .classed('footer-hide', false) .classed('footer-show', true); context.container().select('.flash-wrap') .classed('footer-hide', true) .classed('footer-show', false); }, _duration); return content; } flash.duration = function(_) { if (!arguments.length) return _duration; _duration = _; return flash; }; flash.text = function(_) { if (!arguments.length) return _text; _text = _; return flash; }; flash.textClass = function(_) { if (!arguments.length) return _textClass; _textClass = _; return flash; }; flash.iconName = function(_) { if (!arguments.length) return _iconName; _iconName = _; return flash; }; flash.iconClass = function(_) { if (!arguments.length) return _iconClass; _iconClass = _; return flash; }; return flash; }
morray/iD
modules/ui/flash.js
JavaScript
isc
2,966
"use strict"; const http_1 = require("http"); const WebSocketServer = require("ws"); const express = require("express"); const dgram = require("dgram"); const readUInt64BE = require("readuint64be"); const buffer_1 = require("buffer"); const _ = require("lodash"); // Health Insurrance: process.on("uncaughtException", function (err) { console.log(err); }); const debug = require("debug")("PeerTracker:Server"), redis = require("redis"), GeoIpNativeLite = require("geoip-native-lite"), bencode = require("bencode"); // Load in GeoData GeoIpNativeLite.loadDataSync(); // Keep statistics going, update every 30 min let stats = { seedCount: 0, leechCount: 0, torrentCount: 0, activeTcount: 0, scrapeCount: 0, successfulDown: 0, countries: {} }; const ACTION_CONNECT = 0, ACTION_ANNOUNCE = 1, ACTION_SCRAPE = 2, ACTION_ERROR = 3, INTERVAL = 1801, startConnectionIdHigh = 0x417, startConnectionIdLow = 0x27101980; // Without using streams, this can handle ~320 IPv4 addresses. More doesn't necessarily mean better. const MAX_PEER_SIZE = 1500; const FOUR_AND_FIFTEEN_DAYS = 415 * 24 * 60 * 60; // assuming start time is seconds for redis; // Redis let client; class Server { constructor(opts) { this._debug = (...args) => { args[0] = "[" + this._debugId + "] " + args[0]; debug.apply(null, args); }; const self = this; if (!opts) opts = { port: 80, udpPort: 1337, docker: false }; self._debugId = ~~((Math.random() * 100000) + 1); self._debug("peer-tracker Server instance created"); self.PORT = opts.port; self.udpPORT = opts.udpPort; self.server = http_1.createServer(); self.wss = new WebSocketServer.Server({ server: self.server }); self.udp4 = dgram.createSocket({ type: "udp4", reuseAddr: true }); self.app = express(); // PREP VISUAL AID: console.log(` . | | | ||| /___\\ |_ _| | | | | | | | | |__| |__| | | | | | | | | | | | | Peer Tracker 1.1.0 | | | | | | | | Running in standalone mode | | | | UDP PORT: ${self.udpPORT} | | | | HTTP & WS PORT: ${self.PORT} | | | | | |_| | |__| |__| | | | | LET'S BUILD AN EMPIRE! | | | | https://github.com/CraigglesO/peer-tracker | | | | | | | | |____|_|____| `); // Redis if (opts.docker) client = redis.createClient("6379", "redis"); else client = redis.createClient(); // If an error occurs, print it to the console client.on("error", function (err) { console.log("Redis error: " + err); }); client.on("ready", function () { console.log(new Date() + ": Redis is up and running."); }); self.app.set("trust proxy", function (ip) { return true; }); // Express self.app.get("/", function (req, res) { let ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress; if (ip.indexOf("::ffff:") !== -1) ip = ip.slice(7); res.status(202).send("Welcome to the Empire. Your address: " + ip); }); self.app.get("/stat.json", function (req, res) { res.status(202).send(stats); }); self.app.get("/stat", function (req, res) { // { seedCount, leechCount, torrentCount, activeTcount, scrapeCount, successfulDown, countries }; let parsedResponce = `<h1><span style="color:blue;">V1.0.3</span> - ${stats.torrentCount} Torrents {${stats.activeTcount} active}</h1>\n <h2>Successful Downloads: ${stats.successfulDown}</h2>\n <h2>Number of Scrapes to this tracker: ${stats.scrapeCount}</h2>\n <h3>Connected Peers: ${stats.seedCount + stats.leechCount}</h3>\n <h3><ul>Seeders: ${stats.seedCount}</ul></h3>\n <h3><ul>Leechers: ${stats.leechCount}</ul></h3>\n <h3>Countries that have connected: <h3>\n <ul>`; let countries; for (countries in stats.countries) parsedResponce += `<li>${stats.countries[countries]}</li>\n`; parsedResponce += "</ul>"; res.status(202).send(parsedResponce); }); self.app.get("*", function (req, res) { res.status(404).send("<h1>404 Not Found</h1>"); }); self.server.on("request", self.app.bind(self)); self.server.listen(self.PORT, function () { console.log(new Date() + ": HTTP Server Ready" + "\n" + new Date() + ": Websockets Ready."); }); // WebSocket: self.wss.on("connection", function connection(ws) { // let location = url.parse(ws.upgradeReq.url, true); let ip; let peerAddress; let port; if (opts.docker) { ip = ws.upgradeReq.headers["x-forwarded-for"]; peerAddress = ip.split(":")[0]; port = ip.split(":")[1]; } else { peerAddress = ws._socket.remoteAddress; port = ws._socket.remotePort; } if (peerAddress.indexOf("::ffff:") !== -1) peerAddress = peerAddress.slice(7); console.log("peerAddress", peerAddress); ws.on("message", function incoming(msg) { handleMessage(msg, peerAddress, port, "ws", (reply) => { ws.send(reply); }); }); }); // UDP: self.udp4.bind(self.udpPORT); self.udp4.on("message", function (msg, rinfo) { handleMessage(msg, rinfo.address, rinfo.port, "udp", (reply) => { self.udp4.send(reply, 0, reply.length, rinfo.port, rinfo.address, (err) => { if (err) { console.log("udp4 error: ", err); } ; }); }); }); self.udp4.on("error", function (err) { console.log("error", err); }); self.udp4.on("listening", () => { console.log(new Date() + ": UDP-4 Bound and ready."); }); self.updateStatus((info) => { stats = info; }); setInterval(() => { console.log("STAT UPDATE, " + Date.now()); self.updateStatus((info) => { stats = info; }); }, 30 * 60 * 1000); } updateStatus(cb) { const self = this; // Get hashes -> iterate through hashes and get all peers and leechers // Also get number of scrapes 'scrape' // Number of active hashes hash+':time' let NOW = Date.now(), seedCount = 0, // check leechCount = 0, // check torrentCount = 0, // check activeTcount = 0, // check scrapeCount = 0, // check successfulDown = 0, // check countries = {}; client.get("hashes", (err, reply) => { if (!reply) return; let hashList = reply.split(","); torrentCount = hashList.length; client.get("scrape", (err, rply) => { if (err) { return; } if (!rply) return; scrapeCount = rply; }); hashList.forEach((hash, i) => { client.mget([hash + ":seeders", hash + ":leechers", hash + ":time", hash + ":completed"], (err, rply) => { if (err) { return; } // iterate through: // seeders if (rply[0]) { rply[0] = rply[0].split(","); seedCount += rply[0].length; rply[0].forEach((addr) => { let ip = addr.split(":")[0]; let country = GeoIpNativeLite.lookup(ip); if (country) countries[country] = country.toUpperCase(); }); } if (rply[1]) { rply[1] = rply[1].split(","); seedCount += rply[1].length; rply[1].forEach((addr) => { let ip = addr.split(":")[0]; let country = GeoIpNativeLite.lookup(ip); if (country) countries[country] = country.toUpperCase(); }); } if (rply[2]) { if (((NOW - rply[2]) / 1000) < 432000) activeTcount++; } if (rply[3]) { successfulDown += Number(rply[3]); } if (i === (torrentCount - 1)) { cb({ seedCount, leechCount, torrentCount, activeTcount, scrapeCount, successfulDown, countries }); } }); }); }); } } // MESSAGE FUNCTIONS: function handleMessage(msg, peerAddress, port, type, cb) { // PACKET SIZES: // CONNECT: 16 - ANNOUNCE: 98 - SCRAPE: 16 OR (16 + 20 * n) let buf = new buffer_1.Buffer(msg), bufLength = buf.length, transaction_id = 0, action = null, connectionIdHigh = null, connectionIdLow = null, hash = null, responce = null, PEER_ID = null, PEER_ADDRESS = null, PEER_KEY = null, NUM_WANT = null, peerPort = port, peers = null; // Ensure packet fullfills the minimal 16 byte requirement. if (bufLength < 16) { ERROR(); } else { // Get generic data: connectionIdHigh = buf.readUInt32BE(0), connectionIdLow = buf.readUInt32BE(4), action = buf.readUInt32BE(8), transaction_id = buf.readUInt32BE(12); // 12 32-bit integer transaction_id } switch (action) { case ACTION_CONNECT: // Check whether the transaction ID is equal to the one you chose. if (startConnectionIdLow !== connectionIdLow || startConnectionIdHigh !== connectionIdHigh) { ERROR(); break; } // Create a new Connection ID and Transaction ID for this user... kill after 30 seconds: let newConnectionIDHigh = ~~((Math.random() * 100000) + 1); let newConnectionIDLow = ~~((Math.random() * 100000) + 1); client.setex(peerAddress + ":" + newConnectionIDHigh, 60, 1); client.setex(peerAddress + ":" + newConnectionIDLow, 60, 1); client.setex(peerAddress + ":" + startConnectionIdLow, 60, 1); client.setex(peerAddress + ":" + startConnectionIdHigh, 60, 1); // client.setex(peerAddress + ':' + transaction_id , 30 * 1000, 1); // THIS MIGHT BE WRONG // Create a responce buffer: responce = new buffer_1.Buffer(16); responce.fill(0); responce.writeUInt32BE(ACTION_CONNECT, 0); // 0 32-bit integer action 0 // connect responce.writeUInt32BE(transaction_id, 4); // 4 32-bit integer transaction_id responce.writeUInt32BE(newConnectionIDHigh, 8); // 8 64-bit integer connection_id responce.writeUInt32BE(newConnectionIDLow, 12); // 8 64-bit integer connection_id cb(responce); break; case ACTION_ANNOUNCE: // Checks to make sure the packet is worth analyzing: // 1. packet is atleast 84 bytes if (bufLength < 84) { ERROR(); break; } // Minimal requirements: hash = buf.slice(16, 36); hash = hash.toString("hex"); PEER_ID = buf.slice(36, 56); // -WD0017-I0mH4sMSAPOJ && -LT1000-9BjtQhMtTtTc PEER_ID = PEER_ID.toString(); let DOWNLOADED = readUInt64BE(buf, 56), LEFT = readUInt64BE(buf, 64), UPLOADED = readUInt64BE(buf, 72), EVENT = buf.readUInt32BE(80); if (bufLength > 96) { PEER_ADDRESS = buf.readUInt16BE(84); PEER_KEY = buf.readUInt16BE(88); NUM_WANT = buf.readUInt16BE(92); peerPort = buf.readUInt16BE(96); } // 2. check that Transaction ID and Connection ID match client.mget([peerAddress + ":" + connectionIdHigh, peerAddress + ":" + connectionIdLow], (err, reply) => { if (!reply[0] || !reply[1] || err) { ERROR(); return; } addHash(hash); // Check EVENT // 0: none; 1: completed; 2: started; 3: stopped // If 1, 2, or 3 do sets first. if (EVENT === 1) { // Change the array this peer is housed in. removePeer(peerAddress + ":" + peerPort, hash + type + ":leechers"); addPeer(peerAddress + ":" + peerPort, hash + type + ":seeders"); // Increment total users who completed file client.incr(hash + ":completed"); } else if (EVENT === 2) { // Add to array (leecher array if LEFT is > 0) if (LEFT > 0) addPeer(peerAddress + ":" + peerPort, hash + type + ":leechers"); else addPeer(peerAddress + ":" + peerPort, hash + type + ":seeders"); } else if (EVENT === 3) { // Remove peer from array (leecher array if LEFT is > 0) removePeer(peerAddress + ":" + peerPort, hash + type + ":leechers"); removePeer(peerAddress + ":" + peerPort, hash + type + ":seeders"); return; } client.mget([hash + type + ":seeders", hash + type + ":leechers"], (err, rply) => { if (err) { ERROR(); return; } // Convert all addresses to a proper hex buffer: // Addresses return: 0 - leechers; 1 - seeders; 2 - hexedUp address-port pairs; 3 - resulting buffersize let addresses = addrToBuffer(rply[0], rply[1], LEFT); // Create a responce buffer: responce = new buffer_1.Buffer(20); responce.fill(0); responce.writeUInt32BE(ACTION_ANNOUNCE, 0); // 0 32-bit integer action 1 -> announce responce.writeUInt32BE(transaction_id, 4); // 4 32-bit integer transaction_id responce.writeUInt32BE(INTERVAL, 8); // 8 32-bit integer interval responce.writeUInt32BE(addresses[0], 12); // 12 32-bit integer leechers responce.writeUInt32BE(addresses[1], 16); // 16 32-bit integer seeders responce = buffer_1.Buffer.concat([responce, addresses[2]]); // 20 + 6 * n 32-bit integer IP address // 24 + 6 * n 16-bit integer TCP port cb(responce); }); }); break; case ACTION_SCRAPE: // Check whether the transaction ID is equal to the one you chose. // 2. check that Transaction ID and Connection ID match // addresses return: 0 - leechers; 1 - seeders; 2 - hexedUp address-port pairs; 3 - resulting buffersize // Create a responce buffer: client.incr("scrape"); let responces = new buffer_1.Buffer(8); responces.fill(0); responces.writeUInt32BE(ACTION_SCRAPE, 0); // 0 32-bit integer action 2 -> scrape responces.writeUInt32BE(transaction_id, 4); // 4 32-bit integer transaction_id let bufferSum = []; // LOOP THROUGH REQUESTS for (let i = 16; i < (buf.length - 16); i += 20) { hash = buf.slice(i, i + 20); hash = hash.toString("hex"); client.mget([hash + type + ":seeders", hash + type + ":leechers", hash + type + ":completed"], (err, rply) => { if (err) { ERROR(); return; } // convert all addresses to a proper hex buffer: let addresses = addrToBuffer(rply[0], rply[1], 1); let responce = new buffer_1.Buffer(20); responce.fill(0); responce.writeUInt32BE(addresses[1], 8); // 8 + 12 * n 32-bit integer seeders responce.writeUInt32BE(rply[2], 12); // 12 + 12 * n 32-bit integer completed responce.writeUInt32BE(addresses[0], 16); // 16 + 12 * n 32-bit integer leechers bufferSum.push(responce); if ((i + 16) >= (buf.length - 16)) { let scrapes = buffer_1.Buffer.concat(bufferSum); responces = buffer_1.Buffer.concat([responces, scrapes]); cb(responces); } }); } break; default: ERROR(); } function ERROR() { responce = new buffer_1.Buffer(11); responce.fill(0); responce.writeUInt32BE(ACTION_ERROR, 0); responce.writeUInt32BE(transaction_id, 4); responce.write("900", 8); cb(responce); } function addPeer(peer, where) { client.get(where, (err, reply) => { if (err) { ERROR(); return; } else { if (!reply) reply = peer; else reply = peer + "," + reply; reply = reply.split(","); reply = _.uniq(reply); // Keep the list under MAX_PEER_SIZE; if (reply.length > MAX_PEER_SIZE) { reply = reply.slice(0, MAX_PEER_SIZE); } reply = reply.join(","); client.set(where, reply); } }); } function removePeer(peer, where) { client.get(where, (err, reply) => { if (err) { ERROR(); return; } else { if (!reply) return; else { reply = reply.split(","); let index = reply.indexOf(peer); if (index > -1) { reply.splice(index, 1); } reply = reply.join(","); client.set(where, reply); } } }); } function addrToBuffer(seeders, leechers, LEFT) { // Addresses return: 0 - leechers; 1 - seeders; 2 - hexedUp address-port pairs; 3 - resulting buffersize // Also we don't need to send the users own address // If peer is a leecher, send more seeders; if peer is a seeder, send only leechers let leecherCount = 0, seederCount = 0, peerBuffer = null, peerBufferSize = 0; if (LEFT === 0 || !seeders || seeders === "") seeders = new buffer_1.Buffer(0); else { seeders = seeders.split(","); seederCount = seeders.length; seeders = seeders.map((addressPort) => { let addr = addressPort.split(":")[0]; let port = addressPort.split(":")[1]; addr = addr.split("."); let b = new buffer_1.Buffer(6); b.fill(0); b.writeUInt8(addr[0], 0); b.writeUInt8(addr[1], 1); b.writeUInt8(addr[2], 2); b.writeUInt8(addr[3], 3); b.writeUInt16BE(port, 4); return b; }); seeders = buffer_1.Buffer.concat(seeders); } if (LEFT > 0 && seederCount > 50 && leechers > 15) leechers = leechers.slice(0, 15); if (!leechers || leechers === "") leechers = new buffer_1.Buffer(0); else { leechers = leechers.split(","); leecherCount = leechers.length; leechers = leechers.map((addressPort) => { let addr = addressPort.split(":")[0]; let port = addressPort.split(":")[1]; addr = addr.split("."); let b = new buffer_1.Buffer(6); b.fill(0); b.writeUInt8(addr[0], 0); b.writeUInt8(addr[1], 1); b.writeUInt8(addr[2], 2); b.writeUInt8(addr[3], 3); b.writeUInt16BE(port, 4); return b; }); leechers = buffer_1.Buffer.concat(leechers); } peerBuffer = buffer_1.Buffer.concat([seeders, leechers]); // Addresses return: 0 - leechers; 1 - seeders; 2 - hexedUp address-port pairs; 3 - resulting buffersize return [leecherCount, seederCount, peerBuffer]; } // Add a new hash to the swarm, ensure uniqeness function addHash(hash) { client.get("hashes", (err, reply) => { if (err) { ERROR(); return; } if (!reply) reply = hash; else reply = hash + "," + reply; reply = reply.split(","); reply = _.uniq(reply); reply = reply.join(","); client.set("hashes", reply); client.set(hash + ":time", Date.now()); }); } function getHashes() { let r = client.get("hashes", (err, reply) => { if (err) { ERROR(); return null; } reply = reply.split(","); return reply; }); return r; } } function binaryToHex(str) { if (typeof str !== "string") { str = String(str); } return buffer_1.Buffer.from(str, "binary").toString("hex"); } function hexToBinary(str) { if (typeof str !== "string") { str = String(str); } return buffer_1.Buffer.from(str, "hex").toString("binary"); } Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Server; //# sourceMappingURL=/Users/connor/Desktop/Programming/myModules/peer-tracker/ts-node/b80e7f10257a0a2b7f29aee28a53e164f19fc5f2/98a6883f88ed207a422bce14e041cea9032231df.js.map
CraigglesO/peer-tracker
ts-node/b80e7f10257a0a2b7f29aee28a53e164f19fc5f2/98a6883f88ed207a422bce14e041cea9032231df.js
JavaScript
isc
23,105
var parseString = require('xml2js').parseString; module.exports = function(req, res, next){ if (req.is('xml')){ var data = ''; req.setEncoding('utf8'); req.on('data', function(chunk){ data += chunk; }); req.on('end', function(){ if (!data){ return next(); } parseString(data, { trim: true, explicitArray: false }, function(err, result){ if (!err){ req.body = result || {}; } else { return res.error('BAD_REQUEST'); } next(); }); }); } else { next(); } };
shcoder-ru/rest-req-res
middleware/xml-parser.js
JavaScript
isc
602
# coding=utf-8 from django.utils.functional import SimpleLazyObject from mongo_auth import get_user as mongo_auth_get_user def get_user(request): if not hasattr(request, '_cached_user'): request._cached_user = mongo_auth_get_user(request) return request._cached_user class AuthenticationMiddleware(object): def process_request(self, request): assert hasattr(request, 'session'), ( "The Django authentication middleware requires session middleware " "to be installed. Edit your MIDDLEWARE_CLASSES setting to insert " "'django.contrib.sessions.middleware.SessionMiddleware' before " "'django.contrib.auth.middleware.AuthenticationMiddleware'." ) request.user = SimpleLazyObject(lambda: get_user(request)) class SessionAuthenticationMiddleware(object): """ Formerly, a middleware for invalidating a user's sessions that don't correspond to the user's current session authentication hash. However, it caused the "Vary: Cookie" header on all responses. Now a backwards compatibility shim that enables session verification in auth.get_user() if this middleware is in MIDDLEWARE_CLASSES. """ def process_request(self, request): pass
sv1jsb/django-angular
mongo_auth/middleware.py
Python
isc
1,264
/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018-19 gatecat <gatecat@ds0.me> * Copyright (C) 2020 Pepijn de Vos <pepijn@symbioticeda.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include <algorithm> #include <iostream> #include <iterator> #include "cells.h" #include "design_utils.h" #include "log.h" #include "util.h" NEXTPNR_NAMESPACE_BEGIN static void make_dummy_alu(Context *ctx, int alu_idx, CellInfo *ci, CellInfo *packed_head, std::vector<std::unique_ptr<CellInfo>> &new_cells) { if ((alu_idx % 2) == 0) { return; } std::unique_ptr<CellInfo> dummy = create_generic_cell(ctx, id_SLICE, ci->name.str(ctx) + "_DUMMY_ALULC"); if (ctx->verbose) { log_info("packed dummy ALU %s.\n", ctx->nameOf(dummy.get())); } dummy->params[id_ALU_MODE] = std::string("C2L"); // add to cluster dummy->cluster = packed_head->name; dummy->constr_z = alu_idx % 6; dummy->constr_x = alu_idx / 6; dummy->constr_y = 0; packed_head->constr_children.push_back(dummy.get()); new_cells.push_back(std::move(dummy)); } // replace ALU with LUT static void pack_alus(Context *ctx) { log_info("Packing ALUs..\n"); // cell name, CIN net name pool<std::pair<IdString, IdString>> alu_heads; // collect heads for (auto &cell : ctx->cells) { CellInfo *ci = cell.second.get(); if (is_alu(ctx, ci)) { NetInfo *cin = ci->ports.at(id_CIN).net; CellInfo *cin_ci = cin->driver.cell; if (cin == nullptr || cin_ci == nullptr) { log_error("CIN disconnected at ALU:%s\n", ctx->nameOf(ci)); continue; } if (!is_alu(ctx, cin_ci) || cin->users.size() > 1) { if (ctx->verbose) { log_info("ALU head found %s. CIN net is %s\n", ctx->nameOf(ci), ctx->nameOf(cin)); } alu_heads.insert(std::make_pair(ci->name, cin->name)); } } } pool<IdString> packed_cells; pool<IdString> delete_nets; std::vector<std::unique_ptr<CellInfo>> new_cells; for (auto &head : alu_heads) { CellInfo *ci = ctx->cells[head.first].get(); IdString cin_netId = head.second; if (ctx->verbose) { log_info("cell '%s' is of type '%s'\n", ctx->nameOf(ci), ci->type.c_str(ctx)); } std::unique_ptr<CellInfo> packed_head = create_generic_cell(ctx, id_SLICE, ci->name.str(ctx) + "_HEAD_ALULC"); if (ctx->verbose) { log_info("packed ALU head into %s. CIN net is %s\n", ctx->nameOf(packed_head.get()), ctx->nameOf(cin_netId)); } connect_port(ctx, ctx->nets[ctx->id("$PACKER_VCC_NET")].get(), packed_head.get(), id_C); if (cin_netId == ctx->id("$PACKER_GND_NET")) { // CIN = 0 packed_head->params[id_ALU_MODE] = std::string("C2L"); } else { if (cin_netId == ctx->id("$PACKER_VCC_NET")) { // CIN = 1 packed_head->params[id_ALU_MODE] = std::string("ONE2C"); } else { // CIN from logic connect_port(ctx, ctx->nets[cin_netId].get(), packed_head.get(), id_B); connect_port(ctx, ctx->nets[cin_netId].get(), packed_head.get(), id_D); packed_head->params[id_ALU_MODE] = std::string("0"); // ADD } } int alu_idx = 1; do { // go through the ALU chain auto alu_bel = ci->attrs.find(ctx->id("BEL")); if (alu_bel != ci->attrs.end()) { log_error("ALU %s placement restrictions are not supported.\n", ctx->nameOf(ci)); return; } // remove cell packed_cells.insert(ci->name); // CIN/COUT are hardwired, delete disconnect_port(ctx, ci, id_CIN); NetInfo *cout = ci->ports.at(id_COUT).net; disconnect_port(ctx, ci, id_COUT); std::unique_ptr<CellInfo> packed = create_generic_cell(ctx, id_SLICE, ci->name.str(ctx) + "_ALULC"); if (ctx->verbose) { log_info("packed ALU into %s. COUT net is %s\n", ctx->nameOf(packed.get()), ctx->nameOf(cout)); } int mode = int_or_default(ci->params, id_ALU_MODE); packed->params[id_ALU_MODE] = mode; if (mode == 9) { // MULT connect_port(ctx, ctx->nets[ctx->id("$PACKER_GND_NET")].get(), packed.get(), id_C); } else { connect_port(ctx, ctx->nets[ctx->id("$PACKER_VCC_NET")].get(), packed.get(), id_C); } // add to cluster packed->cluster = packed_head->name; packed->constr_z = alu_idx % 6; packed->constr_x = alu_idx / 6; packed->constr_y = 0; packed_head->constr_children.push_back(packed.get()); ++alu_idx; // connect all remainig ports replace_port(ci, id_SUM, packed.get(), id_F); switch (mode) { case 0: // ADD replace_port(ci, id_I0, packed.get(), id_B); replace_port(ci, id_I1, packed.get(), id_D); break; case 1: // SUB replace_port(ci, id_I0, packed.get(), id_A); replace_port(ci, id_I1, packed.get(), id_D); break; case 5: // LE replace_port(ci, id_I0, packed.get(), id_A); replace_port(ci, id_I1, packed.get(), id_B); break; case 9: // MULT replace_port(ci, id_I0, packed.get(), id_A); replace_port(ci, id_I1, packed.get(), id_B); disconnect_port(ctx, packed.get(), id_D); connect_port(ctx, ctx->nets[ctx->id("$PACKER_VCC_NET")].get(), packed.get(), id_D); break; default: replace_port(ci, id_I0, packed.get(), id_A); replace_port(ci, id_I1, packed.get(), id_B); replace_port(ci, id_I3, packed.get(), id_D); } new_cells.push_back(std::move(packed)); if (cout != nullptr && cout->users.size() > 0) { // if COUT used by logic if ((cout->users.size() > 1) || (!is_alu(ctx, cout->users.at(0).cell))) { if (ctx->verbose) { log_info("COUT is used by logic\n"); } // make gate C->logic std::unique_ptr<CellInfo> packed_tail = create_generic_cell(ctx, id_SLICE, ci->name.str(ctx) + "_TAIL_ALULC"); if (ctx->verbose) { log_info("packed ALU tail into %s. COUT net is %s\n", ctx->nameOf(packed_tail.get()), ctx->nameOf(cout)); } packed_tail->params[id_ALU_MODE] = std::string("C2L"); connect_port(ctx, cout, packed_tail.get(), id_F); // add to cluster packed_tail->cluster = packed_head->name; packed_tail->constr_z = alu_idx % 6; packed_tail->constr_x = alu_idx / 6; packed_tail->constr_y = 0; ++alu_idx; packed_head->constr_children.push_back(packed_tail.get()); new_cells.push_back(std::move(packed_tail)); make_dummy_alu(ctx, alu_idx, ci, packed_head.get(), new_cells); break; } // next ALU ci = cout->users.at(0).cell; // if ALU is too big if (alu_idx == (ctx->gridDimX - 2) * 6 - 1) { log_error("ALU %s is the %dth in the chain. Such long chains are not supported.\n", ctx->nameOf(ci), alu_idx); break; } } else { // COUT is unused if (ctx->verbose) { log_info("cell is the ALU tail. Index is %d\n", alu_idx); } make_dummy_alu(ctx, alu_idx, ci, packed_head.get(), new_cells); break; } } while (1); // add head to the cluster packed_head->cluster = packed_head->name; new_cells.push_back(std::move(packed_head)); } // actual delete, erase and move cells/nets for (auto pcell : packed_cells) { ctx->cells.erase(pcell); } for (auto dnet : delete_nets) { ctx->nets.erase(dnet); } for (auto &ncell : new_cells) { ctx->cells[ncell->name] = std::move(ncell); } } // pack MUX2_LUT5 static void pack_mux2_lut5(Context *ctx, CellInfo *ci, pool<IdString> &packed_cells, pool<IdString> &delete_nets, std::vector<std::unique_ptr<CellInfo>> &new_cells) { if (bool_or_default(ci->attrs, ctx->id("SINGLE_INPUT_MUX"))) { // find the muxed LUT NetInfo *i1 = ci->ports.at(id_I1).net; CellInfo *lut1 = net_driven_by(ctx, i1, is_lut, id_F); if (lut1 == nullptr) { log_error("MUX2_LUT5 '%s' port I1 isn't connected to the LUT\n", ctx->nameOf(ci)); return; } if (ctx->verbose) { log_info("found attached lut1 %s\n", ctx->nameOf(lut1)); } // XXX enable the placement constraints auto mux_bel = ci->attrs.find(ctx->id("BEL")); auto lut1_bel = lut1->attrs.find(ctx->id("BEL")); if (lut1_bel != lut1->attrs.end() || mux_bel != ci->attrs.end()) { log_error("MUX2_LUT5 '%s' placement restrictions are not supported yet\n", ctx->nameOf(ci)); return; } std::unique_ptr<CellInfo> packed = create_generic_cell(ctx, ctx->id("GW_MUX2_LUT5"), ci->name.str(ctx) + "_LC"); if (ctx->verbose) { log_info("packed cell %s into %s\n", ctx->nameOf(ci), ctx->nameOf(packed.get())); } // mux is the cluster root packed->cluster = packed->name; lut1->cluster = packed->name; lut1->constr_z = -ctx->mux_0_z + 1; packed->constr_children.clear(); // reconnect MUX ports replace_port(ci, id_O, packed.get(), id_OF); replace_port(ci, id_I1, packed.get(), id_I1); // remove cells packed_cells.insert(ci->name); // new MUX cell new_cells.push_back(std::move(packed)); } else { // find the muxed LUTs NetInfo *i0 = ci->ports.at(id_I0).net; NetInfo *i1 = ci->ports.at(id_I1).net; CellInfo *lut0 = net_driven_by(ctx, i0, is_lut, id_F); CellInfo *lut1 = net_driven_by(ctx, i1, is_lut, id_F); if (lut0 == nullptr || lut1 == nullptr) { log_error("MUX2_LUT5 '%s' port I0 or I1 isn't connected to the LUT\n", ctx->nameOf(ci)); return; } if (ctx->verbose) { log_info("found attached lut0 %s\n", ctx->nameOf(lut0)); log_info("found attached lut1 %s\n", ctx->nameOf(lut1)); } // XXX enable the placement constraints auto mux_bel = ci->attrs.find(ctx->id("BEL")); auto lut0_bel = lut0->attrs.find(ctx->id("BEL")); auto lut1_bel = lut1->attrs.find(ctx->id("BEL")); if (lut0_bel != lut0->attrs.end() || lut1_bel != lut1->attrs.end() || mux_bel != ci->attrs.end()) { log_error("MUX2_LUT5 '%s' placement restrictions are not supported yet\n", ctx->nameOf(ci)); return; } std::unique_ptr<CellInfo> packed = create_generic_cell(ctx, ctx->id("GW_MUX2_LUT5"), ci->name.str(ctx) + "_LC"); if (ctx->verbose) { log_info("packed cell %s into %s\n", ctx->nameOf(ci), ctx->nameOf(packed.get())); } // mux is the cluster root packed->cluster = packed->name; lut0->cluster = packed->name; lut0->constr_z = -ctx->mux_0_z; lut1->cluster = packed->name; lut1->constr_z = -ctx->mux_0_z + 1; packed->constr_children.clear(); // reconnect MUX ports replace_port(ci, id_O, packed.get(), id_OF); replace_port(ci, id_S0, packed.get(), id_SEL); replace_port(ci, id_I0, packed.get(), id_I0); replace_port(ci, id_I1, packed.get(), id_I1); // remove cells packed_cells.insert(ci->name); // new MUX cell new_cells.push_back(std::move(packed)); } } // Common MUX2 packing routine static void pack_mux2_lut(Context *ctx, CellInfo *ci, bool (*pred)(const BaseCtx *, const CellInfo *), char const type_suffix, IdString const type_id, int const x[2], int const z[2], pool<IdString> &packed_cells, pool<IdString> &delete_nets, std::vector<std::unique_ptr<CellInfo>> &new_cells) { // find the muxed LUTs NetInfo *i0 = ci->ports.at(id_I0).net; NetInfo *i1 = ci->ports.at(id_I1).net; CellInfo *mux0 = net_driven_by(ctx, i0, pred, id_OF); CellInfo *mux1 = net_driven_by(ctx, i1, pred, id_OF); if (mux0 == nullptr || mux1 == nullptr) { log_error("MUX2_LUT%c '%s' port I0 or I1 isn't connected to the MUX\n", type_suffix, ctx->nameOf(ci)); return; } if (ctx->verbose) { log_info("found attached mux0 %s\n", ctx->nameOf(mux0)); log_info("found attached mux1 %s\n", ctx->nameOf(mux1)); } // XXX enable the placement constraints auto mux_bel = ci->attrs.find(ctx->id("BEL")); auto mux0_bel = mux0->attrs.find(ctx->id("BEL")); auto mux1_bel = mux1->attrs.find(ctx->id("BEL")); if (mux0_bel != mux0->attrs.end() || mux1_bel != mux1->attrs.end() || mux_bel != ci->attrs.end()) { log_error("MUX2_LUT%c '%s' placement restrictions are not supported yet\n", type_suffix, ctx->nameOf(ci)); return; } std::unique_ptr<CellInfo> packed = create_generic_cell(ctx, type_id, ci->name.str(ctx) + "_LC"); if (ctx->verbose) { log_info("packed cell %s into %s\n", ctx->nameOf(ci), ctx->nameOf(packed.get())); } // mux is the cluster root packed->cluster = packed->name; mux0->cluster = packed->name; mux0->constr_x = x[0]; mux0->constr_y = 0; mux0->constr_z = z[0]; for (auto &child : mux0->constr_children) { child->cluster = packed->name; child->constr_x += mux0->constr_x; child->constr_z += mux0->constr_z; packed->constr_children.push_back(child); } mux0->constr_children.clear(); mux1->cluster = packed->name; mux1->constr_x = x[1]; mux0->constr_y = 0; mux1->constr_z = z[1]; for (auto &child : mux1->constr_children) { child->cluster = packed->name; child->constr_x += mux1->constr_x; child->constr_z += mux1->constr_z; packed->constr_children.push_back(child); } mux1->constr_children.clear(); packed->constr_children.push_back(mux0); packed->constr_children.push_back(mux1); // reconnect MUX ports replace_port(ci, id_O, packed.get(), id_OF); replace_port(ci, id_S0, packed.get(), id_SEL); replace_port(ci, id_I0, packed.get(), id_I0); replace_port(ci, id_I1, packed.get(), id_I1); // remove cells packed_cells.insert(ci->name); // new MUX cell new_cells.push_back(std::move(packed)); } // pack MUX2_LUT6 static void pack_mux2_lut6(Context *ctx, CellInfo *ci, pool<IdString> &packed_cells, pool<IdString> &delete_nets, std::vector<std::unique_ptr<CellInfo>> &new_cells) { static int x[] = {0, 0}; static int z[] = {+1, -1}; pack_mux2_lut(ctx, ci, is_gw_mux2_lut5, '6', id_GW_MUX2_LUT6, x, z, packed_cells, delete_nets, new_cells); } // pack MUX2_LUT7 static void pack_mux2_lut7(Context *ctx, CellInfo *ci, pool<IdString> &packed_cells, pool<IdString> &delete_nets, std::vector<std::unique_ptr<CellInfo>> &new_cells) { static int x[] = {0, 0}; static int z[] = {+2, -2}; pack_mux2_lut(ctx, ci, is_gw_mux2_lut6, '7', id_GW_MUX2_LUT7, x, z, packed_cells, delete_nets, new_cells); } // pack MUX2_LUT8 static void pack_mux2_lut8(Context *ctx, CellInfo *ci, pool<IdString> &packed_cells, pool<IdString> &delete_nets, std::vector<std::unique_ptr<CellInfo>> &new_cells) { static int x[] = {1, 0}; static int z[] = {-4, -4}; pack_mux2_lut(ctx, ci, is_gw_mux2_lut7, '8', id_GW_MUX2_LUT8, x, z, packed_cells, delete_nets, new_cells); } // Pack wide LUTs static void pack_wideluts(Context *ctx) { log_info("Packing wide LUTs..\n"); pool<IdString> packed_cells; pool<IdString> delete_nets; std::vector<std::unique_ptr<CellInfo>> new_cells; pool<IdString> mux2lut6; pool<IdString> mux2lut7; pool<IdString> mux2lut8; // do MUX2_LUT5 and collect LUT6/7/8 log_info("Packing LUT5s..\n"); for (auto &cell : ctx->cells) { CellInfo *ci = cell.second.get(); if (ctx->verbose) { log_info("cell '%s' is of type '%s'\n", ctx->nameOf(ci), ci->type.c_str(ctx)); } if (is_widelut(ctx, ci)) { if (is_mux2_lut5(ctx, ci)) { pack_mux2_lut5(ctx, ci, packed_cells, delete_nets, new_cells); } else { if (is_mux2_lut6(ctx, ci)) { mux2lut6.insert(ci->name); } else { if (is_mux2_lut7(ctx, ci)) { mux2lut7.insert(ci->name); } else { if (is_mux2_lut8(ctx, ci)) { mux2lut8.insert(ci->name); } } } } } } // do MUX_LUT6 log_info("Packing LUT6s..\n"); for (auto &cell_name : mux2lut6) { pack_mux2_lut6(ctx, ctx->cells[cell_name].get(), packed_cells, delete_nets, new_cells); } // do MUX_LUT7 log_info("Packing LUT7s..\n"); for (auto &cell_name : mux2lut7) { pack_mux2_lut7(ctx, ctx->cells[cell_name].get(), packed_cells, delete_nets, new_cells); } // do MUX_LUT8 log_info("Packing LUT8s..\n"); for (auto &cell_name : mux2lut8) { pack_mux2_lut8(ctx, ctx->cells[cell_name].get(), packed_cells, delete_nets, new_cells); } // actual delete, erase and move cells/nets for (auto pcell : packed_cells) { ctx->cells.erase(pcell); } for (auto dnet : delete_nets) { ctx->nets.erase(dnet); } for (auto &ncell : new_cells) { ctx->cells[ncell->name] = std::move(ncell); } } // Pack LUTs and LUT-FF pairs static void pack_lut_lutffs(Context *ctx) { log_info("Packing LUT-FFs..\n"); pool<IdString> packed_cells; std::vector<std::unique_ptr<CellInfo>> new_cells; for (auto &cell : ctx->cells) { CellInfo *ci = cell.second.get(); if (ctx->verbose) log_info("cell '%s' is of type '%s'\n", ctx->nameOf(ci), ci->type.c_str(ctx)); if (is_lut(ctx, ci)) { std::unique_ptr<CellInfo> packed = create_generic_cell(ctx, ctx->id("SLICE"), ci->name.str(ctx) + "_LC"); for (auto &attr : ci->attrs) packed->attrs[attr.first] = attr.second; packed_cells.insert(ci->name); if (ctx->verbose) log_info("packed cell %s into %s\n", ctx->nameOf(ci), ctx->nameOf(packed.get())); // See if we can pack into a DFF // TODO: LUT cascade NetInfo *o = ci->ports.at(ctx->id("F")).net; CellInfo *dff = net_only_drives(ctx, o, is_ff, ctx->id("D"), true); auto lut_bel = ci->attrs.find(ctx->id("BEL")); bool packed_dff = false; if (dff) { if (ctx->verbose) log_info("found attached dff %s\n", ctx->nameOf(dff)); auto dff_bel = dff->attrs.find(ctx->id("BEL")); if (lut_bel != ci->attrs.end() && dff_bel != dff->attrs.end() && lut_bel->second != dff_bel->second) { // Locations don't match, can't pack } else { lut_to_lc(ctx, ci, packed.get(), false); dff_to_lc(ctx, dff, packed.get(), false); ctx->nets.erase(o->name); if (dff_bel != dff->attrs.end()) packed->attrs[ctx->id("BEL")] = dff_bel->second; packed_cells.insert(dff->name); if (ctx->verbose) log_info("packed cell %s into %s\n", ctx->nameOf(dff), ctx->nameOf(packed.get())); packed_dff = true; } } if (!packed_dff) { lut_to_lc(ctx, ci, packed.get(), true); } new_cells.push_back(std::move(packed)); } } for (auto pcell : packed_cells) { ctx->cells.erase(pcell); } for (auto &ncell : new_cells) { ctx->cells[ncell->name] = std::move(ncell); } } // Pack FFs not packed as LUTFFs static void pack_nonlut_ffs(Context *ctx) { log_info("Packing non-LUT FFs..\n"); pool<IdString> packed_cells; std::vector<std::unique_ptr<CellInfo>> new_cells; for (auto &cell : ctx->cells) { CellInfo *ci = cell.second.get(); if (is_ff(ctx, ci)) { std::unique_ptr<CellInfo> packed = create_generic_cell(ctx, ctx->id("SLICE"), ci->name.str(ctx) + "_DFFLC"); for (auto &attr : ci->attrs) packed->attrs[attr.first] = attr.second; if (ctx->verbose) log_info("packed cell %s into %s\n", ctx->nameOf(ci), ctx->nameOf(packed.get())); packed_cells.insert(ci->name); dff_to_lc(ctx, ci, packed.get(), true); new_cells.push_back(std::move(packed)); } } for (auto pcell : packed_cells) { ctx->cells.erase(pcell); } for (auto &ncell : new_cells) { ctx->cells[ncell->name] = std::move(ncell); } } // Merge a net into a constant net static void set_net_constant(const Context *ctx, NetInfo *orig, NetInfo *constnet, bool constval) { orig->driver.cell = nullptr; for (auto user : orig->users) { if (user.cell != nullptr) { CellInfo *uc = user.cell; if (ctx->verbose) log_info("%s user %s\n", ctx->nameOf(orig), ctx->nameOf(uc)); if ((is_lut(ctx, uc) || is_lc(ctx, uc)) && (user.port.str(ctx).at(0) == 'I') && !constval) { uc->ports[user.port].net = nullptr; } else { uc->ports[user.port].net = constnet; constnet->users.push_back(user); } } } orig->users.clear(); } // Pack constants (simple implementation) static void pack_constants(Context *ctx) { log_info("Packing constants..\n"); std::unique_ptr<CellInfo> gnd_cell = create_generic_cell(ctx, ctx->id("SLICE"), "$PACKER_GND"); gnd_cell->params[ctx->id("INIT")] = Property(0, 1 << 4); std::unique_ptr<NetInfo> gnd_net = std::unique_ptr<NetInfo>(new NetInfo); gnd_net->name = ctx->id("$PACKER_GND_NET"); gnd_net->driver.cell = gnd_cell.get(); gnd_net->driver.port = ctx->id("F"); gnd_cell->ports.at(ctx->id("F")).net = gnd_net.get(); std::unique_ptr<CellInfo> vcc_cell = create_generic_cell(ctx, ctx->id("SLICE"), "$PACKER_VCC"); // Fill with 1s vcc_cell->params[ctx->id("INIT")] = Property(Property::S1).extract(0, (1 << 4), Property::S1); std::unique_ptr<NetInfo> vcc_net = std::unique_ptr<NetInfo>(new NetInfo); vcc_net->name = ctx->id("$PACKER_VCC_NET"); vcc_net->driver.cell = vcc_cell.get(); vcc_net->driver.port = ctx->id("F"); vcc_cell->ports.at(ctx->id("F")).net = vcc_net.get(); std::vector<IdString> dead_nets; bool gnd_used = false; for (auto &net : ctx->nets) { NetInfo *ni = net.second.get(); if (ni->driver.cell != nullptr && ni->driver.cell->type == ctx->id("GND")) { IdString drv_cell = ni->driver.cell->name; set_net_constant(ctx, ni, gnd_net.get(), false); gnd_used = true; dead_nets.push_back(net.first); ctx->cells.erase(drv_cell); } else if (ni->driver.cell != nullptr && ni->driver.cell->type == ctx->id("VCC")) { IdString drv_cell = ni->driver.cell->name; set_net_constant(ctx, ni, vcc_net.get(), true); dead_nets.push_back(net.first); ctx->cells.erase(drv_cell); } } if (gnd_used) { ctx->cells[gnd_cell->name] = std::move(gnd_cell); ctx->nets[gnd_net->name] = std::move(gnd_net); } // Vcc cell always inserted for now, as it may be needed during carry legalisation (TODO: trim later if actually // never used?) ctx->cells[vcc_cell->name] = std::move(vcc_cell); ctx->nets[vcc_net->name] = std::move(vcc_net); for (auto dn : dead_nets) { ctx->nets.erase(dn); } } static bool is_nextpnr_iob(const Context *ctx, CellInfo *cell) { return cell->type == ctx->id("$nextpnr_ibuf") || cell->type == ctx->id("$nextpnr_obuf") || cell->type == ctx->id("$nextpnr_iobuf"); } static bool is_gowin_iob(const Context *ctx, const CellInfo *cell) { switch (cell->type.index) { case ID_IBUF: case ID_OBUF: case ID_IOBUF: case ID_TBUF: return true; default: return false; } } // Pack IO buffers static void pack_io(Context *ctx) { pool<IdString> packed_cells; pool<IdString> delete_nets; std::vector<std::unique_ptr<CellInfo>> new_cells; log_info("Packing IOs..\n"); for (auto &cell : ctx->cells) { CellInfo *ci = cell.second.get(); if (is_gowin_iob(ctx, ci)) { CellInfo *iob = nullptr; switch (ci->type.index) { case ID_IBUF: iob = net_driven_by(ctx, ci->ports.at(id_I).net, is_nextpnr_iob, id_O); break; case ID_OBUF: iob = net_only_drives(ctx, ci->ports.at(id_O).net, is_nextpnr_iob, id_I); break; case ID_IOBUF: iob = net_driven_by(ctx, ci->ports.at(id_IO).net, is_nextpnr_iob, id_O); break; case ID_TBUF: iob = net_only_drives(ctx, ci->ports.at(id_O).net, is_nextpnr_iob, id_I); break; default: break; } if (iob != nullptr) { // delete the $nexpnr_[io]buf for (auto &p : iob->ports) { IdString netname = p.second.net->name; disconnect_port(ctx, iob, p.first); delete_nets.insert(netname); } packed_cells.insert(iob->name); } // Create a IOB buffer std::unique_ptr<CellInfo> ice_cell = create_generic_cell(ctx, id_IOB, ci->name.str(ctx) + "$iob"); gwio_to_iob(ctx, ci, ice_cell.get(), packed_cells); new_cells.push_back(std::move(ice_cell)); auto gwiob = new_cells.back().get(); packed_cells.insert(ci->name); if (iob != nullptr) { // in Gowin .CST port attributes take precedence over cell attributes. // first copy cell attrs related to IO for (auto &attr : ci->attrs) { if (attr.first == IdString(ID_BEL) || attr.first.str(ctx)[0] == '&') { gwiob->setAttr(attr.first, attr.second); } } // rewrite attributes from the port for (auto &attr : iob->attrs) { gwiob->setAttr(attr.first, attr.second); } } } } for (auto pcell : packed_cells) { ctx->cells.erase(pcell); } for (auto dnet : delete_nets) { ctx->nets.erase(dnet); } for (auto &ncell : new_cells) { ctx->cells[ncell->name] = std::move(ncell); } } // Main pack function bool Arch::pack() { Context *ctx = getCtx(); try { log_break(); pack_constants(ctx); pack_io(ctx); pack_wideluts(ctx); pack_alus(ctx); pack_lut_lutffs(ctx); pack_nonlut_ffs(ctx); ctx->settings[ctx->id("pack")] = 1; ctx->assignArchInfo(); log_info("Checksum: 0x%08x\n", ctx->checksum()); return true; } catch (log_execution_error_exception) { return false; } } NEXTPNR_NAMESPACE_END
SymbiFlow/nextpnr
gowin/pack.cc
C++
isc
29,471
"use strict"; var CustomError = require('custom-error-instance'); var inventory = require('./inventory'); var menu = require('./menu'); var OrderError = CustomError('OrderError'); module.exports = function() { var done = false; var factory = {}; var store = {}; /** * Add an item from the menu to the order. * @param {string} name The name of the menu item to add. */ factory.add = function(name) { var item = menu.get(name); if (done) throw new OrderError('Order has been closed.', { code: 'EDONE' }); if (!item) throw new OrderError('Menu item does not exist: ' + name, { code: 'EDNE' }); if (!menu.available(name)) throw new OrderError('Insufficient inventory', { code: 'EINV' }); if (!store.hasOwnProperty(name)) store[name] = 0; store[name]++; item.ingredients.forEach(function(ingredient) { inventory.changeQuantity(ingredient.name, -1 * ingredient.quantity); }); return factory; }; factory.checkout = function() { done = true; console.log('Order complete. Income: $' + factory.cost()); }; factory.cost = function() { var total = 0; Object.keys(store).forEach(function(menuItemName) { var item = menu.get(menuItemName); if (item) { total += item.cost; } else { factory.remove(menuItemName); } }); return total; }; factory.remove = function(name) { var item; if (done) throw new OrderError('Order has been closed.', { code: 'EDONE' }); if (!store.hasOwnProperty(name)) return; store[name]--; if (store[name] <= 0) delete store[name]; item = menu.get(name); item.ingredients.forEach(function(ingredient) { inventory.changeQuantity(ingredient.name, ingredient.quantity); }); return factory; }; return factory; };
Gi60s/IT410
restaurant/order.js
JavaScript
isc
2,025
import Key from './key'; import SubscriberPayload from './subscriber-payload'; import Transition from './transition'; import TransitionHistory from './transition-history'; import TransitionSet from './transition-set'; /** * A class responsible for performing the transition between states. */ export default class Transitioner { private history: TransitionHistory; private transitions: TransitionSet; /** * @param transitions - The set of transitions to manage */ constructor(transitions: TransitionSet, history: TransitionHistory) { this.transitions = transitions; this.history = history; } /** * Check if it is possible to transition to a state from another state * @param toState - The state to transition to * @param fromState - The state to transition from * @return True if it is possible to transition */ canTransition(toState: Key, fromState: Key): boolean { return this.findExecutableTransition(toState, fromState) !== undefined; } /** * Check if it is possible to perform an undo * @return True if it is possible to undo */ canUndo(): boolean { return this.getTransitionForUndo() !== undefined; } /** * Check if it is possible to perform a redo * @return True if it is possible to redo */ canRedo(): boolean { return this.getTransitionForRedo() !== undefined; } /** * Transition to a state from another state. Fire the callback once the * transition is completed. If the to/from state does not exist, an error * will be thrown. * @param toState - The state to transition to * @param fromState - The state to transition from * @param [data] - The meta data associated with the transition * @param [callback] - The callback to fire once the transition is completed */ transition(toState: Key, fromState: Key, data?: any, callback?: (payload: SubscriberPayload) => void): void { if (!this.transitions.hasTransition({ from: fromState }) || !this.transitions.hasTransition({ to: toState })) { throw new Error(`Unable to transition from "${fromState}" to "${toState}"`); } const transition = this.findExecutableTransition(toState, fromState); if (transition) { this.history.addRecord({ data, state: transition.to }); if (callback) { callback({ from: transition.from, to: transition.to }); } } } /** * Transition to a new state by triggering an event. If the event or state * does not exist, an error will be thrown. * @param event - The event to trigger * @param fromState - The state to transition from * @param [data] - The meta data associated with the transition * @param [callback] - The callback to fire once the transition is completed */ triggerEvent(event: Key, fromState: Key, data?: any, callback?: (payload: SubscriberPayload) => void): void { if (!this.transitions.hasEvent(event) || !this.transitions.hasTransition({ from: fromState })) { throw new Error(`Unable to trigger "${event}" and transition from "${fromState}"`); } const transition = this.findExecutableTransitionByEvent(event, fromState); if (transition) { this.history.addRecord({ data, event, state: transition.to }); if (callback) { callback({ event: transition.event, from: transition.from, to: transition.to }); } } } /** * Undo a state transition. Fire the callback if it is possible to undo * @param [callback] - The callback to fire once the transition is completed */ undoTransition(callback?: (payload: SubscriberPayload) => void): void { const transition = this.getTransitionForUndo(); const record = this.history.getPreviousRecord(); if (!transition || !record) { return; } this.history.rewindHistory(); if (callback) { callback({ data: record.data, event: transition.event, from: transition.to, to: transition.from, }); } } /** * Redo a state transition. Fire the callback if it is possible to redo * @param [callback] - The callback to fire once the transition is completed */ redoTransition(callback?: (payload: SubscriberPayload) => void): void { const transition = this.getTransitionForRedo(); const record = this.history.getNextRecord(); if (!transition || !record) { return; } this.history.forwardHistory(); if (callback) { callback({ data: record.data, event: transition.event, from: transition.from, to: transition.to, }); } } /** * Find the first executable transition based on to/from state * @param toState - The state to transition to * @param fromState - The state to transition from * @return The executable transition */ private findExecutableTransition(toState: Key, fromState: Key): Transition | undefined { const transitions = this.transitions.filterExecutableTransitions({ from: fromState, to: toState, }); return transitions[0]; } /** * Find the first executable transition by event * @param toState - The state to transition to * @param fromState - The state to transition from * @return The executable transition */ private findExecutableTransitionByEvent(event: Key, fromState: Key): Transition | undefined { const transitions = this.transitions.filterExecutableTransitions({ event, from: fromState, }); return transitions[0]; } /** * Get a transition that can undo the current state * @return The undoable transition */ private getTransitionForUndo(): Transition | undefined { if (!this.history.getPreviousRecord()) { return; } const currentState = this.history.getCurrentRecord().state; const { state } = this.history.getPreviousRecord()!; const transition = this.findExecutableTransition(currentState, state); if (!transition || !transition.undoable) { return; } return transition; } /** * Get a transition that can redo the previous state * @return The redoable transition */ private getTransitionForRedo(): Transition | undefined { if (!this.history.getNextRecord()) { return; } const currentState = this.history.getCurrentRecord().state; const { state } = this.history.getNextRecord()!; const transition = this.findExecutableTransition(state, currentState); if (!transition || !transition.undoable) { return; } return transition; } }
davidchin/switchhub
src/state-machine/transitioner.ts
TypeScript
isc
7,148
// Copyright (c) 2016 The btcsuite developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package rpctest import ( "errors" "math" "math/big" "runtime" "time" "github.com/ltcsuite/ltcd/blockchain" "github.com/ltcsuite/ltcd/chaincfg" "github.com/ltcsuite/ltcd/chaincfg/chainhash" "github.com/ltcsuite/ltcd/ltcutil" "github.com/ltcsuite/ltcd/mining" "github.com/ltcsuite/ltcd/txscript" "github.com/ltcsuite/ltcd/wire" ) // solveBlock attempts to find a nonce which makes the passed block header hash // to a value less than the target difficulty. When a successful solution is // found true is returned and the nonce field of the passed header is updated // with the solution. False is returned if no solution exists. func solveBlock(header *wire.BlockHeader, targetDifficulty *big.Int) bool { // sbResult is used by the solver goroutines to send results. type sbResult struct { found bool nonce uint32 } // solver accepts a block header and a nonce range to test. It is // intended to be run as a goroutine. quit := make(chan bool) results := make(chan sbResult) solver := func(hdr wire.BlockHeader, startNonce, stopNonce uint32) { // We need to modify the nonce field of the header, so make sure // we work with a copy of the original header. for i := startNonce; i >= startNonce && i <= stopNonce; i++ { select { case <-quit: return default: hdr.Nonce = i hash := hdr.PowHash() if blockchain.HashToBig(&hash).Cmp(targetDifficulty) <= 0 { select { case results <- sbResult{true, i}: return case <-quit: return } } } } select { case results <- sbResult{false, 0}: case <-quit: return } } startNonce := uint32(0) stopNonce := uint32(math.MaxUint32) numCores := uint32(runtime.NumCPU()) noncesPerCore := (stopNonce - startNonce) / numCores for i := uint32(0); i < numCores; i++ { rangeStart := startNonce + (noncesPerCore * i) rangeStop := startNonce + (noncesPerCore * (i + 1)) - 1 if i == numCores-1 { rangeStop = stopNonce } go solver(*header, rangeStart, rangeStop) } for i := uint32(0); i < numCores; i++ { result := <-results if result.found { close(quit) header.Nonce = result.nonce return true } } return false } // standardCoinbaseScript returns a standard script suitable for use as the // signature script of the coinbase transaction of a new block. In particular, // it starts with the block height that is required by version 2 blocks. func standardCoinbaseScript(nextBlockHeight int32, extraNonce uint64) ([]byte, error) { return txscript.NewScriptBuilder().AddInt64(int64(nextBlockHeight)). AddInt64(int64(extraNonce)).Script() } // createCoinbaseTx returns a coinbase transaction paying an appropriate // subsidy based on the passed block height to the provided address. func createCoinbaseTx(coinbaseScript []byte, nextBlockHeight int32, addr ltcutil.Address, mineTo []wire.TxOut, net *chaincfg.Params) (*ltcutil.Tx, error) { // Create the script to pay to the provided payment address. pkScript, err := txscript.PayToAddrScript(addr) if err != nil { return nil, err } tx := wire.NewMsgTx(wire.TxVersion) tx.AddTxIn(&wire.TxIn{ // Coinbase transactions have no inputs, so previous outpoint is // zero hash and max index. PreviousOutPoint: *wire.NewOutPoint(&chainhash.Hash{}, wire.MaxPrevOutIndex), SignatureScript: coinbaseScript, Sequence: wire.MaxTxInSequenceNum, }) if len(mineTo) == 0 { tx.AddTxOut(&wire.TxOut{ Value: blockchain.CalcBlockSubsidy(nextBlockHeight, net), PkScript: pkScript, }) } else { for i := range mineTo { tx.AddTxOut(&mineTo[i]) } } return ltcutil.NewTx(tx), nil } // CreateBlock creates a new block building from the previous block with a // specified blockversion and timestamp. If the timestamp passed is zero (not // initialized), then the timestamp of the previous block will be used plus 1 // second is used. Passing nil for the previous block results in a block that // builds off of the genesis block for the specified chain. func CreateBlock(prevBlock *ltcutil.Block, inclusionTxs []*ltcutil.Tx, blockVersion int32, blockTime time.Time, miningAddr ltcutil.Address, mineTo []wire.TxOut, net *chaincfg.Params) (*ltcutil.Block, error) { var ( prevHash *chainhash.Hash blockHeight int32 prevBlockTime time.Time ) // If the previous block isn't specified, then we'll construct a block // that builds off of the genesis block for the chain. if prevBlock == nil { prevHash = net.GenesisHash blockHeight = 1 prevBlockTime = net.GenesisBlock.Header.Timestamp.Add(time.Minute) } else { prevHash = prevBlock.Hash() blockHeight = prevBlock.Height() + 1 prevBlockTime = prevBlock.MsgBlock().Header.Timestamp } // If a target block time was specified, then use that as the header's // timestamp. Otherwise, add one second to the previous block unless // it's the genesis block in which case use the current time. var ts time.Time switch { case !blockTime.IsZero(): ts = blockTime default: ts = prevBlockTime.Add(time.Second) } extraNonce := uint64(0) coinbaseScript, err := standardCoinbaseScript(blockHeight, extraNonce) if err != nil { return nil, err } coinbaseTx, err := createCoinbaseTx(coinbaseScript, blockHeight, miningAddr, mineTo, net) if err != nil { return nil, err } // Create a new block ready to be solved. blockTxns := []*ltcutil.Tx{coinbaseTx} if inclusionTxs != nil { blockTxns = append(blockTxns, inclusionTxs...) } // We must add the witness commitment to the coinbase if any // transactions are segwit. witnessIncluded := false for i := 1; i < len(blockTxns); i++ { if blockTxns[i].MsgTx().HasWitness() { witnessIncluded = true break } } if witnessIncluded { _ = mining.AddWitnessCommitment(coinbaseTx, blockTxns) } merkles := blockchain.BuildMerkleTreeStore(blockTxns, false) var block wire.MsgBlock block.Header = wire.BlockHeader{ Version: blockVersion, PrevBlock: *prevHash, MerkleRoot: *merkles[len(merkles)-1], Timestamp: ts, Bits: net.PowLimitBits, } for _, tx := range blockTxns { if err := block.AddTransaction(tx.MsgTx()); err != nil { return nil, err } } found := solveBlock(&block.Header, net.PowLimit) if !found { return nil, errors.New("Unable to solve block") } utilBlock := ltcutil.NewBlock(&block) utilBlock.SetHeight(blockHeight) return utilBlock, nil }
ltcsuite/ltcd
integration/rpctest/blockgen.go
GO
isc
6,534
export const DEFAULTS = { API_BASE_URI: 'http://localhost:3000/axway', granularity: 'monthly', startDate: '2010-01-01', cacheExpirySeconds: 300//5 minutes }; export class Settings { /** * @param {string} setting * @returns {*} */ getSetting(setting) { return DEFAULTS[setting]; } /** * @param {string} customerNumber * @param {string} meterType * @returns {string} usageEndpoint */ getUsageEndpoint(customerNumber, meterType) { return `/v1/customers/${customerNumber}/usage/${meterType}`; } } export default new Settings;
scopevale/carpers-paradise
src/client/js/utils/Settings.js
JavaScript
isc
616
// // Created by 王耀 on 2017/11/14. // #include <gtest/gtest.h> #include "functable.h" TEST(FuncTableTest, FuncTableTest_OPERATION_Test) { Func func1(2, 3, 5, 9); FuncTable table; EXPECT_EQ(0, table.getSize()); table.append(func1); EXPECT_EQ(1, table.getSize()); EXPECT_EQ(0, table.getFunction(1).uiEntryPoint); EXPECT_EQ(9, table.getFunction(0).uiStackFrameSize); }
Forec/FoldScript
tests/fvm/test_framework/test_functable.cpp
C++
isc
399
#include "ThinObject.h" #include "Object.h" #include "SnowString.h" #include "Exception.h" namespace snow { static volatile uintx global_object_id_counter = 1; void ThinObject::init() { m_Info.frozen = false; m_Info.gc_lock = false; // XXX: With multithreading, this will most certainly go wrong. #ifdef ARCH_IS_64_BIT ASSERT(global_object_id_counter < (1LU<<61)); #else ASSERT(global_object_id_counter < (1<<29)); #endif m_Info.id = global_object_id_counter++; } Value ThinObject::get_raw(Symbol name) const { return prototype()->get_raw(name); } Value ThinObject::set_raw(Symbol name, const Value&) { throw_exception(new String("Thin objects cannot have members assigned. Modify the prototype, or create a wrapper.")); return nil(); } Value ThinObject::set(const Value& self, Symbol member, const Value& val) { return prototype()->set(self, member, val); } Value ThinObject::get(const Value& self, Symbol member) const { return prototype()->get(self, member); } }
simonask/snow-deprecated
src/runtime/ThinObject.cpp
C++
isc
1,014
package keyring import ( "errors" "sync" ) var ( // ErrNotFound means the requested password was not found ErrNotFound = errors.New("keyring: Password not found") // ErrNoDefault means that no default keyring provider has been found ErrNoDefault = errors.New("keyring: No suitable keyring provider found (check your build flags)") providerInitOnce sync.Once defaultProvider provider providerInitError error ) // provider provides a simple interface to keychain sevice type provider interface { Get(service, username string) (string, error) Set(service, username, password string) error } func setupProvider() (provider, error) { providerInitOnce.Do(func() { defaultProvider, providerInitError = initializeProvider() }) if providerInitError != nil { return nil, providerInitError } else if defaultProvider == nil { return nil, ErrNoDefault } return defaultProvider, nil } // Get gets the password for a paricular Service and Username using the // default keyring provider. func Get(service, username string) (string, error) { p, err := setupProvider() if err != nil { return "", err } return p.Get(service, username) } // Set sets the password for a particular Service and Username using the // default keyring provider. func Set(service, username, password string) error { p, err := setupProvider() if err != nil { return err } return p.Set(service, username, password) }
tmc/keyring
keyring.go
GO
isc
1,420
import {takeEvery} from 'redux-saga' import {call, put, take, fork, select, cancel} from 'redux-saga/effects' import * as Actions from './actions/actions' let ws = null const getUsername = state => state.username function* createWebSocket(url) { ws = new WebSocket(url) let deferred, open_deferred, close_deferred, error_deferred; ws.onopen = event => { if (open_deferred) { open_deferred.resolve(event) open_deferred = null } } ws.onmessage = event => { if (deferred) { deferred.resolve(JSON.parse(event.data)) deferred = null } } ws.onerror = event => { if (error_deferred) { error_deferred.resolve(JSON.parse(event.data)) error_deferred = null } } ws.onclose = event => { if (close_deferred) { close_deferred.resolve(event) close_deferred = null } } return { open: { nextMessage() { if (!open_deferred) { open_deferred = {} open_deferred.promise = new Promise(resolve => open_deferred.resolve = resolve) } return open_deferred.promise } }, message: { nextMessage() { if (!deferred) { deferred = {} deferred.promise = new Promise(resolve => deferred.resolve = resolve) } return deferred.promise } }, error: { nextMessage() { if (!error_deferred) { error_deferred = {} error_deferred.promise = new Promise(resolve => error_deferred.resolve = resolve) } return error_deferred.promise } }, close: { nextMessage() { if (!close_deferred) { close_deferred = {} close_deferred.promise = new Promise(resolve => close_deferred.resolve = resolve) } return close_deferred.promise } } } } function* watchOpen(ws) { let msg = yield call(ws.nextMessage) while (msg) { yield put(Actions.connected(msg.srcElement)) msg = yield call(ws.nextMessage) } } function* watchClose(ws) { let msg = yield call(ws.nextMessage) yield put(Actions.disconnected()) ws = null } function* watchErrors(ws) { let msg = yield call(ws.nextMessage) while (msg) { msg = yield call(ws.nextMessage) } } function* watchMessages(ws) { let msg = yield call(ws.nextMessage) while (msg) { yield put(msg) msg = yield call(ws.nextMessage) } } function* connect() { let openTask, msgTask, errTask, closeTask while (true) { const {ws_url} = yield take('connect') const ws = yield call(createWebSocket, ws_url) if (openTask) { yield cancel(openTask) yield cancel(msgTask) yield cancel(errTask) yield cancel(closeTask) } openTask = yield fork(watchOpen, ws.open) msgTask = yield fork(watchMessages, ws.message) errTask = yield fork(watchErrors, ws.error) closeTask = yield fork(watchClose, ws.close) } } const send = (data) => { try { ws.send(JSON.stringify(data)) } catch (error) { alert("Send error: " + error) } } function* login() { while (true) { const login_action = yield take('login') send(login_action) } } function* hello() { while (true) { const hello_action = yield take('hello') const username = yield select(getUsername) if (username) { send(Actions.login(username)) } } } function* disconnected() { while (true) { yield take('disconnected') } } export default function* rootSaga() { yield [ connect(), hello(), login(), disconnected() ] }
anyley/chat-sinatra-react
frontend/src/sagas.js
JavaScript
isc
4,180
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.SpaServices.AngularCli; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace angular_portal_azure_2018_10 { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); // In production, the Angular files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseSpaStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action=Index}/{id?}"); }); app.UseSpa(spa => { // To learn more about options for serving an Angular SPA from ASP.NET Core, // see https://go.microsoft.com/fwlink/?linkid=864501 spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { spa.UseAngularCliServer(npmScript: "start"); } }); } } }
ardimedia/angular-portal-azure
angular-portal-azure-2018-10/Startup.cs
C#
isc
2,227
import * as babylon from "@babylonjs/core" export const createCubeMesh = (scene: babylon.Scene): babylon.Mesh => { const material = new babylon.StandardMaterial("cube-material", scene) material.emissiveColor = new babylon.Color3(0.1, 0.6, 0.9) const mesh = babylon.Mesh.CreateBox("cube-mesh", 1, scene) mesh.material = material return mesh }
monarch-games/engine
source-archive/game/entities/cube/create-cube-mesh.ts
TypeScript
isc
350
import React from 'react'; const isArray = x => Array.isArray(x); const isString = x => typeof x === 'string' && x.length > 0; const isSelector = x => isString(x) && (startsWith(x, '.') || startsWith(x, '#')); const isChildren = x => /string|number|boolean/.test(typeof x) || isArray(x); const startsWith = (string, start) => string.indexOf(start) === 0; const split = (string, separator) => string.split(separator); const subString = (string, start, end) => string.substring(start, end); const parseSelector = selector => { const classIdSplit = /([\.#]?[a-zA-Z0-9\u007F-\uFFFF_:-]+)/; const parts = split(selector, classIdSplit); return parts.reduce((acc, part) => { if (startsWith(part, '#')) { acc.id = subString(part, 1); } else if (startsWith(part, '.')) { acc.className = `${acc.className} ${subString(part, 1)}`.trim(); } return acc; }, { className: '' }); }; const createElement = (nameOrType, properties = {}, children = []) => { if (properties.isRendered !== undefined && !properties.isRendered) { return null; } const { isRendered, ...props } = properties; const args = [nameOrType, props]; if (!isArray(children)) { args.push(children); } else { args.push(...children); } return React.createElement.apply(React, args); }; export const hh = nameOrType => (first, second, third) => { if (isSelector(first)) { const selector = parseSelector(first); // selector, children if (isChildren(second)) { return createElement(nameOrType, selector, second); } // selector, props, children let { className = '' } = second || {}; className = `${selector.className} ${className} `.trim(); const props = { ...second, ...selector, className }; if (isChildren(third)) { return createElement(nameOrType, props, third); } return createElement(nameOrType, props); } // children if (isChildren(first)) { return createElement(nameOrType, {}, first); } // props, children if (isChildren(second)) { return createElement(nameOrType, first, second); } return createElement(nameOrType, first); }; const h = (nameOrType, ...rest) => hh(nameOrType)(...rest); const TAG_NAMES = [ 'a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'video', 'wbr', 'circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan' ]; module.exports = TAG_NAMES.reduce((exported, type) => { exported[type] = hh(type); return exported; }, { h, hh });
Jador/react-hyperscript-helpers
src/index.js
JavaScript
isc
3,497
/** * Created by Stefan on 9/19/2017 */ /** * Created by Stefan Endres on 08/16/2017. */ 'use strict' var http = require('http'), https = require('https'), url = require('url'), util = require('util'), fs = require('fs'), path = require('path'), sessions = require('./sessions'), EventEmitter = require('events').EventEmitter; function LHServer() { this.fnStack = []; this.defaultPort = 3000; this.options = {}; this.viewEngine = null; EventEmitter.call(this); } util.inherits(LHServer, EventEmitter); LHServer.prototype.use = function(path, options, fn) { if(typeof path === 'function') { fn = path; } if(typeof options === 'function') { fn = options; } if(!fn) return; var fnObj = { fn: fn, method: null, path: typeof path === 'string' ? path : null, options: typeof options === 'object' ? options : {}, } this.fnStack.push(fnObj); } LHServer.prototype.execute = function(req, res) { var self = this; var url_parts = url.parse(req.url); var callbackStack = this.getFunctionList(url_parts.pathname, req.method); if(callbackStack.length === 0) { return; } var func = callbackStack.shift(); // add session capabilities if(this.options['session']) { var session = sessions.lookupOrCreate(req,{ lifetime: this.options['session'].lifetime || 604800, secret: this.options['session'].secret || '', }); if(!res.finished) { res.setHeader('Set-Cookie', session.getSetCookieHeaderValue()); } req.session = session; } // add template rendering if(typeof this.options['view engine'] !== 'undefined') { res.render = render.bind(this,res); } res.statusCode = 200; res.send = send.bind(this,res); res.redirect = redirect.bind(this,res); res.status = status.bind(this,res); res.header = header.bind(this,res); try{ func.apply(this,[req,res, function(){self.callbackNextFunction(req,res,callbackStack)}]); } catch (e) { this.emit('error', e, res, req); } } LHServer.prototype.callbackNextFunction = function(req,res,callbackStack) { var self = this; if(callbackStack.length === 0) { return; } callbackStack[0] && callbackStack[0].apply && callbackStack[0].apply(this,[req,res,function() { callbackStack.shift(); self.callbackNextFunction(req,res,callbackStack) }]); } LHServer.prototype.listen = function(options, cb) { var opt = {}; if(typeof options === 'number' || typeof options === 'string'){ opt.port = options; } else { opt = Object.assign(opt,options) } var httpServer; if(opt.cert && opt.key) { httpServer = https.createServer(opt, this.execute.bind(this)).listen(opt.port || this.defaultPort); } else { httpServer = http.createServer(this.execute.bind(this)).listen(opt.port || this.defaultPort); } if(httpServer) { this.emit('ready'); }; cb && cb(httpServer); } LHServer.prototype.set = function(option, value) { this.options[option] = value; if(option === 'view engine' && value && value !== '') { try { this.viewEngine = require(value); } catch (err) { this.emit('error',err); } } } LHServer.prototype.getFunctionList = function(requestPath, method) { var ret = []; if(this.options['static']) { ret.push(readStaticFile.bind(this)); } for(var i in this.fnStack) { var pathMatch = ( this.fnStack[i].options && this.fnStack[i].options.partialPath ? this.fnStack[i].path === requestPath.substr(0, this.fnStack[i].path.length) : this.fnStack[i].path === requestPath ) || this.fnStack[i].path === null; if((this.fnStack[i].method === method || this.fnStack[i].method === null) && pathMatch) { if(this.fnStack[i].fn) { ret.push(this.fnStack[i].fn); } } } return ret; } LHServer.prototype.get = LHServer.prototype.post = LHServer.prototype.put = LHServer.prototype.delete = function() {}; var methods = ['get', 'put', 'post', 'delete',]; methods.map(function(method) { LHServer.prototype[method] = function(path, options, fn) { if(typeof path === 'function') { fn = path; } if(typeof options === 'function') { fn = options; } if(!fn) return; var fnObj = { fn: fn, method: method.toUpperCase(), path: typeof path === 'string' ? path : null, options: typeof options === 'object' ? options : {}, } this.fnStack.push(fnObj); } }) function readStaticFile(req,res,next) { if(res.finished){ return next && next(); } var self = this; var url_parts = url.parse(req.url); var requestPath = path.normalize(url_parts.pathname ).replace(/^(\.\.(\/|\\|$))+/, ''); if(requestPath === '/'){ requestPath = '/index.html' } var filePath = path.join(this.options['static'],requestPath); const contentTypes = { '.ico': 'image/x-icon', '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.css': 'text/css', '.png': 'image/png', '.jpg': 'image/jpeg', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.svg': 'image/svg+xml', '.pdf': 'application/pdf', '.doc': 'application/msword' }; var fExt = path.extname(filePath); var contentType; if(fExt && contentTypes.hasOwnProperty(fExt)) { contentType = contentTypes[fExt]; } else { return next && next(); } fs.readFile(filePath, function(err, content) { if (err) { return next && next(); } else { res.header('Content-Type', contentType); res.header('Content-Length', Buffer.byteLength(content)); res.writeHead( res.statusCode, res.headerValues ); res.end(content, 'utf-8'); return next && next(); } }); } function send(res, data) { if(res.finished){ return; } var contentType = 'text/html'; var responseBody = data; if(typeof data === 'object') { contentType = 'application/json' responseBody = JSON.stringify(data); } res.header('Content-Type', contentType) res.header('Content-Length', Buffer.byteLength(responseBody)) res.writeHead( res.statusCode, res.headerValues ); res.end(responseBody); } function render(res,template,options,callback){ if(res.finished){ return; } var self = this; if(typeof self.viewEngine === 'undefined') { return callback && callback(); } if(self.viewEngine.renderFile) { return self.viewEngine.renderFile( (self.options['views'] || '') + '/'+template+'.pug', options, function(err, result) { if(err){ self.emit('error',err); } if(result){ res.header('Content-Type', 'text/html') res.header('Content-Length', Buffer.byteLength(result)) res.writeHead( res.statusCode, res.headerValues ); res.end(result); } callback && callback(err,result); } ) } } function status(res,code) { res.statusCode = code; } function header(res, key, value) { if(typeof res.headerValues === 'undefined'){ res.headerValues = {}; } res.headerValues[key] = value } function redirect(res,url) { var address = url; var status = 302; if (arguments.length === 3) { if (typeof arguments[1] === 'number') { status = arguments[1]; address = arguments[2]; } } var responseBody = 'Redirecting to ' + address; res.header('Content-Type', 'text/html') res.header('Cache-Control', 'no-cache') res.header('Content-Length', Buffer.byteLength(responseBody)) res.header('Location', address) res.writeHead( status, res.headerValues ); res.end(responseBody); }; module.exports = new LHServer();
endresstefan/light-http-server
lib/server.js
JavaScript
isc
8,582
'use strict'; import path from 'path'; import webpack, { optimize, HotModuleReplacementPlugin, NoErrorsPlugin } from 'webpack'; export default { devtool: 'eval-cheap-module-source-map', entry: [ 'webpack-hot-middleware/client', './app/js/bootstrap' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new optimize.OccurenceOrderPlugin(), new HotModuleReplacementPlugin(), new NoErrorsPlugin() ], module: { loaders: [ { test: /\.js$/, loaders: ['babel'], exclude: path.resolve(__dirname, 'node_modules'), include: [ path.resolve(__dirname) ] } ] } };
hyphenbash/movies-search
webpack.config.js
JavaScript
isc
668
using ReactiveUI; using System; using System.Diagnostics; using System.IO; using System.Reactive; using System.Reactive.Disposables; using System.Reactive.Linq; using Microsoft.Win32; namespace VisualStudioCleanup { static class OperatingSystemTasks { public static IObservable<Unit> TurnOffHyperV() { return Observable.Start(() => { using (var dism = Process.Start("dism.exe", "/Online /Disable-Feature:Microsoft-Hyper-V-All")) { dism?.WaitForExit(); } }, RxApp.TaskpoolScheduler); } public static IObservable<Unit> CleanSetupLogs() { return Observable.Start(() => { var tempDir = Path.GetTempPath(); Observable.Concat( Directory.EnumerateFiles(tempDir, "dd_*.*").ToObservable(), Directory.EnumerateFiles(tempDir, "VSIXInstaller_*.log").ToObservable(), Directory.EnumerateFiles(tempDir, "MSI*.LOG").ToObservable(), Directory.EnumerateFiles(tempDir, "sql*.*").ToObservable()) .Subscribe(file => File.Delete(file)); }, RxApp.TaskpoolScheduler); } public static IObservable<Unit> MovePackageCache(string destinationRoot) { return Observable.Start(() => { var dest = Path.Combine(destinationRoot, "Package Cache"); MoveDirectory(PackageCachePath, dest); Directory.Delete(PackageCachePath); CreateJunction(PackageCachePath, dest); }, RxApp.TaskpoolScheduler); } public static void Uninstall(string program) { ExecProg(program); } public static IObservable<Uninstallable> GetUninstallables() { return Observable.Create<Uninstallable>(o => { Observable.Start(() => { try { using (var localMachine = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default)) { GetUninstallablesCore(localMachine, o); } if (Environment.Is64BitProcess) { using (var localMachine32 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)) { GetUninstallablesCore(localMachine32, o); } } o.OnCompleted(); } catch (Exception ex) { o.OnError(ex); } }, RxApp.TaskpoolScheduler); return Disposable.Create(() => { }); }); } private static void GetUninstallablesCore(RegistryKey baseKey, IObserver<Uninstallable> outcome) { using (var uninstallKey = baseKey.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall")) { if (uninstallKey == null) return; var subKeys = uninstallKey.GetSubKeyNames(); foreach(var subkeyName in subKeys) { using (var subkey = uninstallKey.OpenSubKey(subkeyName)) { if (subkey == null) continue; var name = (string)subkey.GetValue("DisplayName"); var command = (string)subkey.GetValue("UninstallString"); var source = (string)subkey.GetValue("InstallSource", ""); if (!string.IsNullOrEmpty(source) && source.IndexOf(PackageCachePath, StringComparison.OrdinalIgnoreCase) == 0) { var uninstallable = new Uninstallable(name, command); outcome.OnNext(uninstallable); } } } } } private static void CreateJunction(string sourceDir, string destDir) { ExecProg($"mklink /j \"{sourceDir}\" \"{destDir}\""); } private static void ExecProg(string program) { var psi = new ProcessStartInfo("cmd.exe", $"/c {program}") { WindowStyle = ProcessWindowStyle.Hidden }; using (var proc = Process.Start(psi)) { proc?.WaitForExit(); } } private static void MoveDirectory(string sourceDir, string destDir) { // Get the subdirectories for the specified directory. var dir = new DirectoryInfo(sourceDir); // create target dir (we may have just recursed into it if (!Directory.Exists(destDir)) { Directory.CreateDirectory(destDir); } // Move files foreach (var file in dir.GetFiles()) { file.MoveTo(Path.Combine(destDir, file.Name)); } // Move sub-dirs foreach (var subdir in dir.GetDirectories()) { var temp = Path.Combine(destDir, subdir.Name); MoveDirectory(subdir.FullName, temp); Directory.Delete(subdir.FullName); } } private static readonly string PackageCachePath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Package Cache"); } }
teobugslayer/VisualStudioCleanup
VisualStudioCleanup/OperatingSystemTasks.cs
C#
isc
5,785
<?php namespace Dictionary; //---------------------------------------------------------------------------- require_once __DIR__ . '/node_interface.php'; interface Node_With_Phrases extends Node_Interface { function add_phrase(); function get_phrase(); function get_phrases(); } //---------------------------------------------------------------------------- require_once __DIR__ . '/../phrase.php'; trait Has_Phrases { private $phrases = []; private $phrase_iterator = 0; //------------------------------------------------------------------------ // phrase management //------------------------------------------------------------------------ function add_phrase(){ $phrase = new Phrase($this->dictionary); $this->phrases[] = $phrase; return $phrase; } function get_phrase(){ if(!isset($this->phrases[$this->phrase_iterator])){ $this->phrase_iterator = 0; return false; } $phrase = $this->phrases[$this->phrase_iterator]; $this->phrase_iterator++; return $phrase; } function get_phrases(){ return $this->phrases; } }
lkorczewski/dictionary-dev
traits/has_phrases.php
PHP
isc
1,081
'use strict'; var expect = chai.expect; function run(scope,done) { done(); } describe('SendCtrl', function(){ var rootScope, scope, controller_injector, dependencies, ctrl, sendForm, network, timeout, spy, stub, mock, res, transaction, data; beforeEach(module("rp")); beforeEach(inject(function($rootScope, $controller, $q, $timeout, rpNetwork) { network = rpNetwork; rootScope = rootScope; timeout = $timeout; scope = $rootScope.$new(); scope.currencies_all = [{ name: 'XRP - Ripples', value: 'XRP'}]; controller_injector = $controller; // Stub the sendForm, which should perhaps be tested using // End To End tests scope.sendForm = { send_destination: { $setValidity: function(){} }, $setPristine: function(){}, $setValidity: function(){} }; scope.$apply = function(func){func()}; scope.saveAddressForm = { $setPristine: function () {} } scope.check_dt_visibility = function () {}; dependencies = { $scope: scope, $element: null, $network: network, rpId: { loginStatus: true, account: 'r4EwBWxrx5HxYRyisfGzMto3AT8FZiYdWk' } } ctrl = controller_injector("SendCtrl", dependencies); })); it('should be initialized with defaults', function (done) { assert.equal(scope.mode, 'form'); assert.isObject(scope.send); assert.equal(scope.send.currency, 'XRP - Ripples'); assert.isFalse(scope.show_save_address_form); assert.isFalse(scope.addressSaved); assert.equal(scope.saveAddressName, ''); assert.isFalse(scope.addressSaving); done() }); it('should reset destination dependencies', function (done) { assert.isFunction(scope.reset_destination_deps); done(); }); describe('updating the destination', function (done) { beforeEach(function () { scope.send.recipient_address = 'r4EwBWxrx5HxYRyisfGzMto3AT8FZiYdWk'; }) it('should have a function to do so', function (done) { assert.isFunction(scope.update_destination); done(); }); describe('when the recipient is the same as last time', function (done) { beforeEach(function () { scope.send.last_recipient = scope.send.recipient_address; }); it('should not reset destination dependencies', function (done) { spy = sinon.spy(scope, 'reset_destination_deps'); scope.update_destination(); assert(spy.notCalled); done(); }); it('should not check destination tag visibility', function (done) { spy = sinon.spy(scope, 'check_dt_visibility'); scope.update_destination(); assert(spy.notCalled); done(); }); }); describe('when the recipient is new', function (done) { beforeEach(function () { scope.send.last_recipient = null; }); it('should reset destination dependencies', function (done) { spy = sinon.spy(scope, 'reset_destination_deps'); scope.update_destination(); assert(spy.called); done(); }); it('should check destination tag visibility', function (done) { spy = sinon.spy(scope, 'check_dt_visibility'); scope.update_destination(); assert(spy.called); done(); }); }); }) describe('updating the destination remote', function (done) { it('should have a function to do so', function (done) { assert.isFunction(scope.update_destination_remote); done(); }); it('should validate the federation field by default', function (done) { var setValiditySpy = sinon.spy( scope.sendForm.send_destination, '$setValidity'); scope.update_destination_remote(); assert(setValiditySpy.withArgs('federation', true).called); done(); }) describe('when it is not bitcoin', function (done) { beforeEach(function () { scope.send.bitcoin = null }) it('should check destination', function (done) { var spy = sinon.spy(scope, 'check_destination'); scope.update_destination_remote(); assert(spy.calledOnce); done(); }); }); describe('when it is bitcoin', function (done) { beforeEach(function () { scope.send.bitcoin = true; }); it('should update currency constraints', function (done) { var spy = sinon.spy(scope, 'update_currency_constraints'); scope.update_destination_remote(); spy.should.have.been.calledOnce; done(); }); it('should not check destination', function (done) { var spy = sinon.spy(scope, 'check_destination'); scope.update_destination_remote(); assert(!spy.called); done(); }); }) }) it('should check the destination', function (done) { assert.isFunction(scope.check_destination); done(); }) it('should handle paths', function (done) { assert.isFunction(scope.handle_paths); done(); }); it('should update paths', function (done) { assert.isFunction(scope.update_paths); done(); }); describe('updating currency constraints', function () { it('should have a function to do so', function (done) { assert.isFunction(scope.update_currency_constraints); done(); }); it('should update the currency', function (done) { stub = sinon.stub(scope, 'update_currency'); scope.update_currency_constraints(); assert(spy.called); done(); }); describe('when recipient info is not loaded', function () { it('should not update the currency', function (done) { stub = sinon.stub(scope, 'update_currency'); scope.send.recipient_info.loaded = false; scope.update_currency_constraints(); assert(spy.called); done(); }); }); }); it('should reset the currency dependencies', function (done) { assert.isFunction(scope.reset_currency_deps); var spy = sinon.spy(scope, 'reset_amount_deps'); scope.reset_currency_deps(); assert(spy.calledOnce); done(); }); it('should update the currency', function (done) { assert.isFunction(scope.update_currency); done(); }); describe('resetting the amount dependencies', function (done) { it('should have a function to do so', function (done) { assert.isFunction(scope.reset_amount_deps); done(); }); it('should set the quote to false', function (done) { scope.send.quote = true; scope.reset_amount_deps(); assert.isFalse(scope.send.quote); done(); }); it('should falsify the sender insufficient xrp flag', function (done) { scope.send.sender_insufficient_xrp = true; scope.reset_amount_deps(); assert.isFalse(scope.send.sender_insufficient_xrp); done(); }); it('should reset the paths', function (done) { spy = sinon.spy(scope, 'reset_paths'); scope.reset_amount_deps(); assert(spy.calledOnce); done(); }); }); it('should update the amount', function (done) { assert.isFunction(scope.update_amount); done(); }); it('should update the quote', function (done) { assert.isFunction(scope.update_quote); done(); }); describe('resetting paths', function (done) { it('should have a function to do so', function (done) { assert.isFunction(scope.reset_paths); done(); }); it('should set the send alternatives to an empty array', function (done) { scope.send.alternatives = ['not_an_empty_array']; scope.reset_paths(); assert(Array.isArray(scope.send.alternatives)); assert.equal(scope.send.alternatives.length, 0); done(); }); }); it('should rest the paths', function (done) { assert.isFunction(scope.reset_paths); done(); }); it('should cancel the form', function (done) { assert.isFunction(scope.cancelConfirm); scope.send.alt = ''; scope.mode = null; scope.cancelConfirm(); assert.equal(scope.mode, 'form'); assert.isNull(scope.send.alt); done(); }); describe('resetting the address form', function () { it('should have a function to do so', function (done) { assert.isFunction(scope.resetAddressForm); done(); }); it('should falsify show_save_address_form field', function (done) { scope.show_save_address_form = true scope.resetAddressForm(); assert.isFalse(scope.show_save_address_form); done(); }); it('should falsify the addressSaved field', function (done) { scope.addressSaved = true; scope.resetAddressForm(); assert.isFalse(scope.addressSaved); done(); }); it('should falsify the addressSaving field', function (done) { scope.saveAddressName = null; scope.resetAddressForm(); assert.equal(scope.saveAddressName, ''); done(); }); it('should empty the saveAddressName field', function (done) { scope.addressSaving = true; scope.resetAddressForm(); assert.isFalse(scope.addressSaving); done(); }); it('should set the form to pristine state', function (done) { spy = sinon.spy(scope.saveAddressForm, '$setPristine'); scope.resetAddressForm(); assert(spy.calledOnce); done(); }); }); describe('performing reset goto', function () { it('should have a function to do so', function (done) { assert.isFunction(scope.reset_goto); done(); }); it('should reset the scope', function (done) { spy = sinon.spy(scope, 'reset'); scope.reset_goto(); assert(spy.calledOnce); done(); }); it('should navigate the page to the tabname provide', function (done) { var tabName = 'someAwesomeTab'; scope.reset_goto(tabName); assert.equal(document.location.hash, '#' + tabName); done(); }); }) it('should perform a reset goto', function (done) { var mock = sinon.mock(scope); mock.expects('reset').once(); scope.reset_goto(); mock.verify(); done(); }); describe("handling when the send is prepared", function () { it('should have a function to do so', function (done) { assert.isFunction(scope.send_prepared); done(); }); it('should set confirm wait to true', function (done) { scope.send_prepared(); assert.isTrue(scope.confirm_wait); done(); }); it("should set the mode to 'confirm'", function (done) { assert.notEqual(scope.mode, 'confirm'); scope.send_prepared(); assert.equal(scope.mode, 'confirm'); done(); }) it('should set confirm_wait to false after a timeout', function (done) { scope.send_prepared(); assert.isTrue(scope.confirm_wait); // For some reason $timeout.flush() works but then raises an exception try { timeout.flush() } catch (e) {} assert.isFalse(scope.confirm_wait); done(); }); }); describe('handling when a transaction send is confirmed', function (done) { beforeEach(function () { scope.send.recipient_address = 'r4EwBWxrx5HxYRyisfGzMto3AT8FZiYdWk'; }); describe("handling a 'propose' event from ripple-lib", function (done) { beforeEach(function () { scope.send = { amount_feedback: { currency: function () { function to_human () { return 'somestring'; } return { to_human: to_human } } } } transaction = { hash: 'E64165A4ED2BF36E5922B11C4E192DF068E2ADC21836087DE5E0B1FDDCC9D82F' } res = { engine_result: 'arbitrary_engine_result', engine_result_message: 'arbitrary_engine_result_message' } }); it('should call send with the transaction hash', function (done) { spy = sinon.spy(scope, 'sent'); scope.onTransactionProposed(res, transaction); assert(spy.calledWith(transaction.hash)); done(); }); it('should set the engine status with the response', function (done) { spy = sinon.spy(scope, 'setEngineStatus'); scope.onTransactionProposed(res, transaction); assert(spy.called); done(); }); }); describe("handling errors from the server", function () { describe("any error", function (done) { it('should set the mode to error', function (done) { var res = { error: null }; scope.onTransactionError(res, null); setTimeout(function (){ assert.equal(scope.mode, "error"); done(); }, 10) }); }); }); it('should have a function to handle send confirmed', function (done) { assert.isFunction(scope.send_confirmed); done(); }); it('should create a transaction', function (done) { spy = sinon.spy(network.remote, 'transaction'); scope.send_confirmed(); assert(spy.called); done(); }); }) describe('saving an address', function () { beforeEach(function () { scope.userBlob = { data: { contacts: [] } }; }); it('should have a function to do so', function (done) { assert.isFunction(scope.saveAddress); done(); }); it("should set the addressSaving property to true", function (done) { assert.isFalse(scope.addressSaving); scope.saveAddress(); assert.isTrue(scope.addressSaving); done(); }) it("should listen for blobSave event", function (done) { var onBlobSaveSpy = sinon.spy(scope, '$on'); scope.saveAddress(); assert(onBlobSaveSpy.withArgs('$blobSave').calledOnce); done(); }); it("should add the contact to the blob's contacts", function (done) { assert(scope.userBlob.data.contacts.length == 0); scope.saveAddress(); assert(scope.userBlob.data.contacts.length == 1); done(); }); describe('handling a blobSave event', function () { describe('having called saveAddress', function () { beforeEach(function () { scope.saveAddress(); }); it('should set addressSaved to true', function (done) { assert.isFalse(scope.addressSaved); scope.$emit('$blobSave'); assert.isTrue(scope.addressSaved); done(); }); it("should set the contact as the scope's contact", function (done) { assert.isUndefined(scope.contact); scope.$emit('$blobSave'); assert.isObject(scope.contact); done(); }); }) describe('without having called saveAddress', function () { it('should not set addressSaved', function (done) { assert.isFalse(scope.addressSaved); scope.$emit('$blobSave'); assert.isFalse(scope.addressSaved); done(); }); }) }) }); describe('setting engine status', function () { beforeEach(function () { res = { engine_result: 'arbitrary_engine_result', engine_result_message: 'arbitrary_engine_result_message' } }); describe("when the response code is 'tes'", function() { beforeEach(function () { res.engine_result = 'tes'; }) describe('when the transaction is accepted', function () { it("should set the transaction result to cleared", function (done) { var accepted = true; scope.setEngineStatus(res, accepted); assert.equal(scope.tx_result, 'cleared'); done(); }); }); describe('when the transaction not accepted', function () { it("should set the transaction result to pending", function (done) { var accepted = false; scope.setEngineStatus(res, accepted); assert.equal(scope.tx_result, 'pending'); done(); }); }); }); describe("when the response code is 'tep'", function() { beforeEach(function () { res.engine_result = 'tep'; }) it("should set the transaction result to partial", function (done) { scope.setEngineStatus(res, true); assert.equal(scope.tx_result, 'partial'); done(); }); }); }); describe('handling sent transactions', function () { it('should update the mode to status', function (done) { assert.isFunction(scope.sent); assert.equal(scope.mode, 'form'); scope.sent(); assert.equal(scope.mode, 'status'); done(); }) it('should listen for transactions on the network', function (done) { var remoteListenerSpy = sinon.spy(network.remote, 'on'); scope.sent(); assert(remoteListenerSpy.calledWith('transaction')); done(); }) describe('handling a transaction event', function () { beforeEach(function () { var hash = 'testhash'; scope.sent(hash); data = { transaction: { hash: hash } } stub = sinon.stub(scope, 'setEngineStatus'); }); afterEach(function () { scope.setEngineStatus.restore(); }) it('should set the engine status', function (done) { network.remote.emit('transaction', data); assert(stub.called); done(); }); it('should stop listening for transactions', function (done) { spy = sinon.spy(network.remote, 'removeListener'); network.remote.emit('transaction', data); assert(spy.called); done(); }) }) }) });
yxxyun/ripple-client
test/unit/tabs/sendControllerSpec.js
JavaScript
isc
17,667
<?php namespace Primus; /** * A quick and dirty dispatcher based on Aura.Dispatcher * Using this cheap dispatcher since we need to support PHP 5.3. If we ever move to PHP 5.4 we should swap this out * with Aura.Dispatcher * * @package Primus */ class Dispatcher { protected $methodParam = ''; protected $objects = array(); protected $objectParam = ''; public function dispatch($object, $params) { // Get the method from the params $method = $params[$this->methodParam]; // Invoke it if(is_callable(array($object, $method))) { $result = $object->$method(); } else if($object instanceof \Closure) { $result = $object($params); } else if(is_object($object) && is_callable($object)) { $result = $object->__invoke($params); } else { return $object; } $this->dispatch($result, $params); } public function setMethodParam($methodParam) { $this->methodParam = $methodParam; } public function setObject($identifier, $object) { $this->objects[$identifier] = $object; } public function setObjectParam($objectParam) { $this->objectParam = $objectParam; } public function __invoke($params = array()) { $identifier = $params[$this->objectParam]; if(isset($this->objects[$identifier])) { $object = $this->objects[$identifier]; $this->dispatch($object, $params); } } }
dragonmantank/primus
src/Primus/Dispatcher.php
PHP
isc
1,529
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\IMethodRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; /// <summary> /// The interface IWorkbookFunctionsDollarDeRequest. /// </summary> public partial interface IWorkbookFunctionsDollarDeRequest : IBaseRequest { /// <summary> /// Gets the request body. /// </summary> WorkbookFunctionsDollarDeRequestBody RequestBody { get; } /// <summary> /// Issues the POST request. /// </summary> System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync(); /// <summary> /// Issues the POST request. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await for async call.</returns> System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync( CancellationToken cancellationToken); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> IWorkbookFunctionsDollarDeRequest Expand(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IWorkbookFunctionsDollarDeRequest Select(string value); } }
ginach/msgraph-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/IWorkbookFunctionsDollarDeRequest.cs
C#
mit
2,083
"use strict"; (function (ConflictType) { ConflictType[ConflictType["IndividualAttendeeConflict"] = 0] = "IndividualAttendeeConflict"; ConflictType[ConflictType["GroupConflict"] = 1] = "GroupConflict"; ConflictType[ConflictType["GroupTooBigConflict"] = 2] = "GroupTooBigConflict"; ConflictType[ConflictType["UnknownAttendeeConflict"] = 3] = "UnknownAttendeeConflict"; })(exports.ConflictType || (exports.ConflictType = {})); var ConflictType = exports.ConflictType;
eino-makitalo/ews-javascript-npmbuild
js/Enumerations/ConflictType.js
JavaScript
mit
481
<?php /* * This file is part of the Ivory Http Adapter package. * * (c) Eric GELOEN <geloen.eric@gmail.com> * * For the full copyright and license information, please read the LICENSE * file that was distributed with this source code. */ namespace Ivory\Tests\HttpAdapter; use GuzzleHttp\Handler\CurlHandler; /** * @author GeLo <geloen.eric@gmail.com> */ class Guzzle6CurlHttpAdapterTest extends AbstractGuzzle6CurlHttpAdapterTest { /** * {@inheritdoc} */ protected function setUp() { if (PHP_VERSION_ID < 50500) { $this->markTestSkipped(); } parent::setUp(); } /** * {@inheritdoc} */ protected function createHandler() { return new CurlHandler(); } }
egeloen/ivory-http-adapter
tests/Guzzle6CurlHttpAdapterTest.php
PHP
mit
763
// Package staticcheck contains a linter for Go source code. package staticcheck // import "honnef.co/go/tools/staticcheck" import ( "fmt" "go/ast" "go/constant" "go/token" "go/types" htmltemplate "html/template" "net/http" "regexp" "sort" "strconv" "strings" "sync" texttemplate "text/template" "honnef.co/go/tools/functions" "honnef.co/go/tools/internal/sharedcheck" "honnef.co/go/tools/lint" "honnef.co/go/tools/ssa" "honnef.co/go/tools/staticcheck/vrp" "golang.org/x/tools/go/ast/astutil" ) func validRegexp(call *Call) { arg := call.Args[0] err := ValidateRegexp(arg.Value) if err != nil { arg.Invalid(err.Error()) } } type runeSlice []rune func (rs runeSlice) Len() int { return len(rs) } func (rs runeSlice) Less(i int, j int) bool { return rs[i] < rs[j] } func (rs runeSlice) Swap(i int, j int) { rs[i], rs[j] = rs[j], rs[i] } func utf8Cutset(call *Call) { arg := call.Args[1] if InvalidUTF8(arg.Value) { arg.Invalid(MsgInvalidUTF8) } } func uniqueCutset(call *Call) { arg := call.Args[1] if !UniqueStringCutset(arg.Value) { arg.Invalid(MsgNonUniqueCutset) } } func unmarshalPointer(name string, arg int) CallCheck { return func(call *Call) { if !Pointer(call.Args[arg].Value) { call.Args[arg].Invalid(fmt.Sprintf("%s expects to unmarshal into a pointer, but the provided value is not a pointer", name)) } } } func pointlessIntMath(call *Call) { if ConvertedFromInt(call.Args[0].Value) { call.Invalid(fmt.Sprintf("calling %s on a converted integer is pointless", lint.CallName(call.Instr.Common()))) } } func checkValidHostPort(arg int) CallCheck { return func(call *Call) { if !ValidHostPort(call.Args[arg].Value) { call.Args[arg].Invalid(MsgInvalidHostPort) } } } var ( checkRegexpRules = map[string]CallCheck{ "regexp.MustCompile": validRegexp, "regexp.Compile": validRegexp, } checkTimeParseRules = map[string]CallCheck{ "time.Parse": func(call *Call) { arg := call.Args[0] err := ValidateTimeLayout(arg.Value) if err != nil { arg.Invalid(err.Error()) } }, } checkEncodingBinaryRules = map[string]CallCheck{ "encoding/binary.Write": func(call *Call) { arg := call.Args[2] if !CanBinaryMarshal(call.Job, arg.Value) { arg.Invalid(fmt.Sprintf("value of type %s cannot be used with binary.Write", arg.Value.Value.Type())) } }, } checkURLsRules = map[string]CallCheck{ "net/url.Parse": func(call *Call) { arg := call.Args[0] err := ValidateURL(arg.Value) if err != nil { arg.Invalid(err.Error()) } }, } checkSyncPoolValueRules = map[string]CallCheck{ "(*sync.Pool).Put": func(call *Call) { arg := call.Args[0] typ := arg.Value.Value.Type() if !lint.IsPointerLike(typ) { arg.Invalid("argument should be pointer-like to avoid allocations") } }, } checkRegexpFindAllRules = map[string]CallCheck{ "(*regexp.Regexp).FindAll": RepeatZeroTimes("a FindAll method", 1), "(*regexp.Regexp).FindAllIndex": RepeatZeroTimes("a FindAll method", 1), "(*regexp.Regexp).FindAllString": RepeatZeroTimes("a FindAll method", 1), "(*regexp.Regexp).FindAllStringIndex": RepeatZeroTimes("a FindAll method", 1), "(*regexp.Regexp).FindAllStringSubmatch": RepeatZeroTimes("a FindAll method", 1), "(*regexp.Regexp).FindAllStringSubmatchIndex": RepeatZeroTimes("a FindAll method", 1), "(*regexp.Regexp).FindAllSubmatch": RepeatZeroTimes("a FindAll method", 1), "(*regexp.Regexp).FindAllSubmatchIndex": RepeatZeroTimes("a FindAll method", 1), } checkUTF8CutsetRules = map[string]CallCheck{ "strings.IndexAny": utf8Cutset, "strings.LastIndexAny": utf8Cutset, "strings.ContainsAny": utf8Cutset, "strings.Trim": utf8Cutset, "strings.TrimLeft": utf8Cutset, "strings.TrimRight": utf8Cutset, } checkUniqueCutsetRules = map[string]CallCheck{ "strings.Trim": uniqueCutset, "strings.TrimLeft": uniqueCutset, "strings.TrimRight": uniqueCutset, } checkUnmarshalPointerRules = map[string]CallCheck{ "encoding/xml.Unmarshal": unmarshalPointer("xml.Unmarshal", 1), "(*encoding/xml.Decoder).Decode": unmarshalPointer("Decode", 0), "encoding/json.Unmarshal": unmarshalPointer("json.Unmarshal", 1), "(*encoding/json.Decoder).Decode": unmarshalPointer("Decode", 0), } checkUnbufferedSignalChanRules = map[string]CallCheck{ "os/signal.Notify": func(call *Call) { arg := call.Args[0] if UnbufferedChannel(arg.Value) { arg.Invalid("the channel used with signal.Notify should be buffered") } }, } checkMathIntRules = map[string]CallCheck{ "math.Ceil": pointlessIntMath, "math.Floor": pointlessIntMath, "math.IsNaN": pointlessIntMath, "math.Trunc": pointlessIntMath, "math.IsInf": pointlessIntMath, } checkStringsReplaceZeroRules = map[string]CallCheck{ "strings.Replace": RepeatZeroTimes("strings.Replace", 3), "bytes.Replace": RepeatZeroTimes("bytes.Replace", 3), } checkListenAddressRules = map[string]CallCheck{ "net/http.ListenAndServe": checkValidHostPort(0), "net/http.ListenAndServeTLS": checkValidHostPort(0), } checkBytesEqualIPRules = map[string]CallCheck{ "bytes.Equal": func(call *Call) { if ConvertedFrom(call.Args[0].Value, "net.IP") && ConvertedFrom(call.Args[1].Value, "net.IP") { call.Invalid("use net.IP.Equal to compare net.IPs, not bytes.Equal") } }, } checkRegexpMatchLoopRules = map[string]CallCheck{ "regexp.Match": loopedRegexp("regexp.Match"), "regexp.MatchReader": loopedRegexp("regexp.MatchReader"), "regexp.MatchString": loopedRegexp("regexp.MatchString"), } ) type Checker struct { CheckGenerated bool funcDescs *functions.Descriptions deprecatedObjs map[types.Object]string nodeFns map[ast.Node]*ssa.Function } func NewChecker() *Checker { return &Checker{} } func (c *Checker) Funcs() map[string]lint.Func { return map[string]lint.Func{ "SA1000": c.callChecker(checkRegexpRules), "SA1001": c.CheckTemplate, "SA1002": c.callChecker(checkTimeParseRules), "SA1003": c.callChecker(checkEncodingBinaryRules), "SA1004": c.CheckTimeSleepConstant, "SA1005": c.CheckExec, "SA1006": c.CheckUnsafePrintf, "SA1007": c.callChecker(checkURLsRules), "SA1008": c.CheckCanonicalHeaderKey, "SA1009": nil, "SA1010": c.callChecker(checkRegexpFindAllRules), "SA1011": c.callChecker(checkUTF8CutsetRules), "SA1012": c.CheckNilContext, "SA1013": c.CheckSeeker, "SA1014": c.callChecker(checkUnmarshalPointerRules), "SA1015": c.CheckLeakyTimeTick, "SA1016": c.CheckUntrappableSignal, "SA1017": c.callChecker(checkUnbufferedSignalChanRules), "SA1018": c.callChecker(checkStringsReplaceZeroRules), "SA1019": c.CheckDeprecated, "SA1020": c.callChecker(checkListenAddressRules), "SA1021": c.callChecker(checkBytesEqualIPRules), "SA1022": nil, "SA1023": c.CheckWriterBufferModified, "SA1024": c.callChecker(checkUniqueCutsetRules), "SA2000": c.CheckWaitgroupAdd, "SA2001": c.CheckEmptyCriticalSection, "SA2002": c.CheckConcurrentTesting, "SA2003": c.CheckDeferLock, "SA3000": c.CheckTestMainExit, "SA3001": c.CheckBenchmarkN, "SA4000": c.CheckLhsRhsIdentical, "SA4001": c.CheckIneffectiveCopy, "SA4002": c.CheckDiffSizeComparison, "SA4003": c.CheckUnsignedComparison, "SA4004": c.CheckIneffectiveLoop, "SA4005": c.CheckIneffectiveFieldAssignments, "SA4006": c.CheckUnreadVariableValues, // "SA4007": c.CheckPredeterminedBooleanExprs, "SA4007": nil, "SA4008": c.CheckLoopCondition, "SA4009": c.CheckArgOverwritten, "SA4010": c.CheckIneffectiveAppend, "SA4011": c.CheckScopedBreak, "SA4012": c.CheckNaNComparison, "SA4013": c.CheckDoubleNegation, "SA4014": c.CheckRepeatedIfElse, "SA4015": c.callChecker(checkMathIntRules), "SA4016": c.CheckSillyBitwiseOps, "SA4017": c.CheckPureFunctions, "SA4018": c.CheckSelfAssignment, "SA4019": c.CheckDuplicateBuildConstraints, "SA5000": c.CheckNilMaps, "SA5001": c.CheckEarlyDefer, "SA5002": c.CheckInfiniteEmptyLoop, "SA5003": c.CheckDeferInInfiniteLoop, "SA5004": c.CheckLoopEmptyDefault, "SA5005": c.CheckCyclicFinalizer, // "SA5006": c.CheckSliceOutOfBounds, "SA5007": c.CheckInfiniteRecursion, "SA6000": c.callChecker(checkRegexpMatchLoopRules), "SA6001": c.CheckMapBytesKey, "SA6002": c.callChecker(checkSyncPoolValueRules), "SA6003": c.CheckRangeStringRunes, "SA6004": nil, "SA9000": nil, "SA9001": c.CheckDubiousDeferInChannelRangeLoop, "SA9002": c.CheckNonOctalFileMode, "SA9003": c.CheckEmptyBranch, } } func (c *Checker) filterGenerated(files []*ast.File) []*ast.File { if c.CheckGenerated { return files } var out []*ast.File for _, f := range files { if !lint.IsGenerated(f) { out = append(out, f) } } return out } func (c *Checker) Init(prog *lint.Program) { c.funcDescs = functions.NewDescriptions(prog.SSA) c.deprecatedObjs = map[types.Object]string{} c.nodeFns = map[ast.Node]*ssa.Function{} for _, fn := range prog.AllFunctions { if fn.Blocks != nil { applyStdlibKnowledge(fn) ssa.OptimizeBlocks(fn) } } c.nodeFns = lint.NodeFns(prog.Packages) deprecated := []map[types.Object]string{} wg := &sync.WaitGroup{} for _, pkginfo := range prog.Prog.AllPackages { pkginfo := pkginfo scope := pkginfo.Pkg.Scope() names := scope.Names() wg.Add(1) m := map[types.Object]string{} deprecated = append(deprecated, m) go func(m map[types.Object]string) { for _, name := range names { obj := scope.Lookup(name) msg := c.deprecationMessage(pkginfo.Files, prog.SSA.Fset, obj) if msg != "" { m[obj] = msg } if typ, ok := obj.Type().Underlying().(*types.Struct); ok { n := typ.NumFields() for i := 0; i < n; i++ { // FIXME(dh): This code will not find deprecated // fields in anonymous structs. field := typ.Field(i) msg := c.deprecationMessage(pkginfo.Files, prog.SSA.Fset, field) if msg != "" { m[field] = msg } } } } wg.Done() }(m) } wg.Wait() for _, m := range deprecated { for k, v := range m { c.deprecatedObjs[k] = v } } } // TODO(adonovan): make this a method: func (*token.File) Contains(token.Pos) func tokenFileContainsPos(f *token.File, pos token.Pos) bool { p := int(pos) base := f.Base() return base <= p && p < base+f.Size() } func pathEnclosingInterval(files []*ast.File, fset *token.FileSet, start, end token.Pos) (path []ast.Node, exact bool) { for _, f := range files { if f.Pos() == token.NoPos { // This can happen if the parser saw // too many errors and bailed out. // (Use parser.AllErrors to prevent that.) continue } if !tokenFileContainsPos(fset.File(f.Pos()), start) { continue } if path, exact := astutil.PathEnclosingInterval(f, start, end); path != nil { return path, exact } } return nil, false } func (c *Checker) deprecationMessage(files []*ast.File, fset *token.FileSet, obj types.Object) (message string) { path, _ := pathEnclosingInterval(files, fset, obj.Pos(), obj.Pos()) if len(path) <= 2 { return "" } var docs []*ast.CommentGroup switch n := path[1].(type) { case *ast.FuncDecl: docs = append(docs, n.Doc) case *ast.Field: docs = append(docs, n.Doc) case *ast.ValueSpec: docs = append(docs, n.Doc) if len(path) >= 3 { if n, ok := path[2].(*ast.GenDecl); ok { docs = append(docs, n.Doc) } } case *ast.TypeSpec: docs = append(docs, n.Doc) if len(path) >= 3 { if n, ok := path[2].(*ast.GenDecl); ok { docs = append(docs, n.Doc) } } default: return "" } for _, doc := range docs { if doc == nil { continue } parts := strings.Split(doc.Text(), "\n\n") last := parts[len(parts)-1] if !strings.HasPrefix(last, "Deprecated: ") { continue } alt := last[len("Deprecated: "):] alt = strings.Replace(alt, "\n", " ", -1) return alt } return "" } func (c *Checker) isInLoop(b *ssa.BasicBlock) bool { sets := c.funcDescs.Get(b.Parent()).Loops for _, set := range sets { if set[b] { return true } } return false } func applyStdlibKnowledge(fn *ssa.Function) { if len(fn.Blocks) == 0 { return } // comma-ok receiving from a time.Tick channel will never return // ok == false, so any branching on the value of ok can be // replaced with an unconditional jump. This will primarily match // `for range time.Tick(x)` loops, but it can also match // user-written code. for _, block := range fn.Blocks { if len(block.Instrs) < 3 { continue } if len(block.Succs) != 2 { continue } var instrs []*ssa.Instruction for i, ins := range block.Instrs { if _, ok := ins.(*ssa.DebugRef); ok { continue } instrs = append(instrs, &block.Instrs[i]) } for i, ins := range instrs { unop, ok := (*ins).(*ssa.UnOp) if !ok || unop.Op != token.ARROW { continue } call, ok := unop.X.(*ssa.Call) if !ok { continue } if !lint.IsCallTo(call.Common(), "time.Tick") { continue } ex, ok := (*instrs[i+1]).(*ssa.Extract) if !ok || ex.Tuple != unop || ex.Index != 1 { continue } ifstmt, ok := (*instrs[i+2]).(*ssa.If) if !ok || ifstmt.Cond != ex { continue } *instrs[i+2] = ssa.NewJump(block) succ := block.Succs[1] block.Succs = block.Succs[0:1] succ.RemovePred(block) } } } func hasType(j *lint.Job, expr ast.Expr, name string) bool { return types.TypeString(j.Program.Info.TypeOf(expr), nil) == name } func (c *Checker) CheckUntrappableSignal(j *lint.Job) { fn := func(node ast.Node) bool { call, ok := node.(*ast.CallExpr) if !ok { return true } if !j.IsCallToAnyAST(call, "os/signal.Ignore", "os/signal.Notify", "os/signal.Reset") { return true } for _, arg := range call.Args { if conv, ok := arg.(*ast.CallExpr); ok && isName(j, conv.Fun, "os.Signal") { arg = conv.Args[0] } if isName(j, arg, "os.Kill") || isName(j, arg, "syscall.SIGKILL") { j.Errorf(arg, "%s cannot be trapped (did you mean syscall.SIGTERM?)", j.Render(arg)) } if isName(j, arg, "syscall.SIGSTOP") { j.Errorf(arg, "%s signal cannot be trapped", j.Render(arg)) } } return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func (c *Checker) CheckTemplate(j *lint.Job) { fn := func(node ast.Node) bool { call, ok := node.(*ast.CallExpr) if !ok { return true } var kind string if j.IsCallToAST(call, "(*text/template.Template).Parse") { kind = "text" } else if j.IsCallToAST(call, "(*html/template.Template).Parse") { kind = "html" } else { return true } sel := call.Fun.(*ast.SelectorExpr) if !j.IsCallToAST(sel.X, "text/template.New") && !j.IsCallToAST(sel.X, "html/template.New") { // TODO(dh): this is a cheap workaround for templates with // different delims. A better solution with less false // negatives would use data flow analysis to see where the // template comes from and where it has been return true } s, ok := j.ExprToString(call.Args[0]) if !ok { return true } var err error switch kind { case "text": _, err = texttemplate.New("").Parse(s) case "html": _, err = htmltemplate.New("").Parse(s) } if err != nil { // TODO(dominikh): whitelist other parse errors, if any if strings.Contains(err.Error(), "unexpected") { j.Errorf(call.Args[0], "%s", err) } } return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func (c *Checker) CheckTimeSleepConstant(j *lint.Job) { fn := func(node ast.Node) bool { call, ok := node.(*ast.CallExpr) if !ok { return true } if !j.IsCallToAST(call, "time.Sleep") { return true } lit, ok := call.Args[0].(*ast.BasicLit) if !ok { return true } n, err := strconv.Atoi(lit.Value) if err != nil { return true } if n == 0 || n > 120 { // time.Sleep(0) is a seldomly used pattern in concurrency // tests. >120 might be intentional. 120 was chosen // because the user could've meant 2 minutes. return true } recommendation := "time.Sleep(time.Nanosecond)" if n != 1 { recommendation = fmt.Sprintf("time.Sleep(%d * time.Nanosecond)", n) } j.Errorf(call.Args[0], "sleeping for %d nanoseconds is probably a bug. Be explicit if it isn't: %s", n, recommendation) return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func (c *Checker) CheckWaitgroupAdd(j *lint.Job) { fn := func(node ast.Node) bool { g, ok := node.(*ast.GoStmt) if !ok { return true } fun, ok := g.Call.Fun.(*ast.FuncLit) if !ok { return true } if len(fun.Body.List) == 0 { return true } stmt, ok := fun.Body.List[0].(*ast.ExprStmt) if !ok { return true } call, ok := stmt.X.(*ast.CallExpr) if !ok { return true } sel, ok := call.Fun.(*ast.SelectorExpr) if !ok { return true } fn, ok := j.Program.Info.ObjectOf(sel.Sel).(*types.Func) if !ok { return true } if fn.FullName() == "(*sync.WaitGroup).Add" { j.Errorf(sel, "should call %s before starting the goroutine to avoid a race", j.Render(stmt)) } return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func (c *Checker) CheckInfiniteEmptyLoop(j *lint.Job) { fn := func(node ast.Node) bool { loop, ok := node.(*ast.ForStmt) if !ok || len(loop.Body.List) != 0 || loop.Post != nil { return true } if loop.Init != nil { // TODO(dh): this isn't strictly necessary, it just makes // the check easier. return true } // An empty loop is bad news in two cases: 1) The loop has no // condition. In that case, it's just a loop that spins // forever and as fast as it can, keeping a core busy. 2) The // loop condition only consists of variable or field reads and // operators on those. The only way those could change their // value is with unsynchronised access, which constitutes a // data race. // // If the condition contains any function calls, its behaviour // is dynamic and the loop might terminate. Similarly for // channel receives. if loop.Cond != nil && hasSideEffects(loop.Cond) { return true } j.Errorf(loop, "this loop will spin, using 100%% CPU") if loop.Cond != nil { j.Errorf(loop, "loop condition never changes or has a race condition") } return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func (c *Checker) CheckDeferInInfiniteLoop(j *lint.Job) { fn := func(node ast.Node) bool { mightExit := false var defers []ast.Stmt loop, ok := node.(*ast.ForStmt) if !ok || loop.Cond != nil { return true } fn2 := func(node ast.Node) bool { switch stmt := node.(type) { case *ast.ReturnStmt: mightExit = true case *ast.BranchStmt: // TODO(dominikh): if this sees a break in a switch or // select, it doesn't check if it breaks the loop or // just the select/switch. This causes some false // negatives. if stmt.Tok == token.BREAK { mightExit = true } case *ast.DeferStmt: defers = append(defers, stmt) case *ast.FuncLit: // Don't look into function bodies return false } return true } ast.Inspect(loop.Body, fn2) if mightExit { return true } for _, stmt := range defers { j.Errorf(stmt, "defers in this infinite loop will never run") } return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func (c *Checker) CheckDubiousDeferInChannelRangeLoop(j *lint.Job) { fn := func(node ast.Node) bool { loop, ok := node.(*ast.RangeStmt) if !ok { return true } typ := j.Program.Info.TypeOf(loop.X) _, ok = typ.Underlying().(*types.Chan) if !ok { return true } fn2 := func(node ast.Node) bool { switch stmt := node.(type) { case *ast.DeferStmt: j.Errorf(stmt, "defers in this range loop won't run unless the channel gets closed") case *ast.FuncLit: // Don't look into function bodies return false } return true } ast.Inspect(loop.Body, fn2) return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func (c *Checker) CheckTestMainExit(j *lint.Job) { fn := func(node ast.Node) bool { if !isTestMain(j, node) { return true } arg := j.Program.Info.ObjectOf(node.(*ast.FuncDecl).Type.Params.List[0].Names[0]) callsRun := false fn2 := func(node ast.Node) bool { call, ok := node.(*ast.CallExpr) if !ok { return true } sel, ok := call.Fun.(*ast.SelectorExpr) if !ok { return true } ident, ok := sel.X.(*ast.Ident) if !ok { return true } if arg != j.Program.Info.ObjectOf(ident) { return true } if sel.Sel.Name == "Run" { callsRun = true return false } return true } ast.Inspect(node.(*ast.FuncDecl).Body, fn2) callsExit := false fn3 := func(node ast.Node) bool { if j.IsCallToAST(node, "os.Exit") { callsExit = true return false } return true } ast.Inspect(node.(*ast.FuncDecl).Body, fn3) if !callsExit && callsRun { j.Errorf(node, "TestMain should call os.Exit to set exit code") } return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func isTestMain(j *lint.Job, node ast.Node) bool { decl, ok := node.(*ast.FuncDecl) if !ok { return false } if decl.Name.Name != "TestMain" { return false } if len(decl.Type.Params.List) != 1 { return false } arg := decl.Type.Params.List[0] if len(arg.Names) != 1 { return false } typ := j.Program.Info.TypeOf(arg.Type) return typ != nil && typ.String() == "*testing.M" } func (c *Checker) CheckExec(j *lint.Job) { fn := func(node ast.Node) bool { call, ok := node.(*ast.CallExpr) if !ok { return true } if !j.IsCallToAST(call, "os/exec.Command") { return true } val, ok := j.ExprToString(call.Args[0]) if !ok { return true } if !strings.Contains(val, " ") || strings.Contains(val, `\`) || strings.Contains(val, "/") { return true } j.Errorf(call.Args[0], "first argument to exec.Command looks like a shell command, but a program name or path are expected") return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func (c *Checker) CheckLoopEmptyDefault(j *lint.Job) { fn := func(node ast.Node) bool { loop, ok := node.(*ast.ForStmt) if !ok || len(loop.Body.List) != 1 || loop.Cond != nil || loop.Init != nil { return true } sel, ok := loop.Body.List[0].(*ast.SelectStmt) if !ok { return true } for _, c := range sel.Body.List { if comm, ok := c.(*ast.CommClause); ok && comm.Comm == nil && len(comm.Body) == 0 { j.Errorf(comm, "should not have an empty default case in a for+select loop. The loop will spin.") } } return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func (c *Checker) CheckLhsRhsIdentical(j *lint.Job) { fn := func(node ast.Node) bool { op, ok := node.(*ast.BinaryExpr) if !ok { return true } switch op.Op { case token.EQL, token.NEQ: if basic, ok := j.Program.Info.TypeOf(op.X).(*types.Basic); ok { if kind := basic.Kind(); kind == types.Float32 || kind == types.Float64 { // f == f and f != f might be used to check for NaN return true } } case token.SUB, token.QUO, token.AND, token.REM, token.OR, token.XOR, token.AND_NOT, token.LAND, token.LOR, token.LSS, token.GTR, token.LEQ, token.GEQ: default: // For some ops, such as + and *, it can make sense to // have identical operands return true } if j.Render(op.X) != j.Render(op.Y) { return true } j.Errorf(op, "identical expressions on the left and right side of the '%s' operator", op.Op) return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func (c *Checker) CheckScopedBreak(j *lint.Job) { fn := func(node ast.Node) bool { var body *ast.BlockStmt switch node := node.(type) { case *ast.ForStmt: body = node.Body case *ast.RangeStmt: body = node.Body default: return true } for _, stmt := range body.List { var blocks [][]ast.Stmt switch stmt := stmt.(type) { case *ast.SwitchStmt: for _, c := range stmt.Body.List { blocks = append(blocks, c.(*ast.CaseClause).Body) } case *ast.SelectStmt: for _, c := range stmt.Body.List { blocks = append(blocks, c.(*ast.CommClause).Body) } default: continue } for _, body := range blocks { if len(body) == 0 { continue } lasts := []ast.Stmt{body[len(body)-1]} // TODO(dh): unfold all levels of nested block // statements, not just a single level if statement if ifs, ok := lasts[0].(*ast.IfStmt); ok { if len(ifs.Body.List) == 0 { continue } lasts[0] = ifs.Body.List[len(ifs.Body.List)-1] if block, ok := ifs.Else.(*ast.BlockStmt); ok { if len(block.List) != 0 { lasts = append(lasts, block.List[len(block.List)-1]) } } } for _, last := range lasts { branch, ok := last.(*ast.BranchStmt) if !ok || branch.Tok != token.BREAK || branch.Label != nil { continue } j.Errorf(branch, "ineffective break statement. Did you mean to break out of the outer loop?") } } } return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func (c *Checker) CheckUnsafePrintf(j *lint.Job) { fn := func(node ast.Node) bool { call, ok := node.(*ast.CallExpr) if !ok { return true } if !j.IsCallToAnyAST(call, "fmt.Printf", "fmt.Sprintf", "log.Printf") { return true } if len(call.Args) != 1 { return true } switch call.Args[0].(type) { case *ast.CallExpr, *ast.Ident: default: return true } j.Errorf(call.Args[0], "printf-style function with dynamic first argument and no further arguments should use print-style function instead") return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func (c *Checker) CheckEarlyDefer(j *lint.Job) { fn := func(node ast.Node) bool { block, ok := node.(*ast.BlockStmt) if !ok { return true } if len(block.List) < 2 { return true } for i, stmt := range block.List { if i == len(block.List)-1 { break } assign, ok := stmt.(*ast.AssignStmt) if !ok { continue } if len(assign.Rhs) != 1 { continue } if len(assign.Lhs) < 2 { continue } if lhs, ok := assign.Lhs[len(assign.Lhs)-1].(*ast.Ident); ok && lhs.Name == "_" { continue } call, ok := assign.Rhs[0].(*ast.CallExpr) if !ok { continue } sig, ok := j.Program.Info.TypeOf(call.Fun).(*types.Signature) if !ok { continue } if sig.Results().Len() < 2 { continue } last := sig.Results().At(sig.Results().Len() - 1) // FIXME(dh): check that it's error from universe, not // another type of the same name if last.Type().String() != "error" { continue } lhs, ok := assign.Lhs[0].(*ast.Ident) if !ok { continue } def, ok := block.List[i+1].(*ast.DeferStmt) if !ok { continue } sel, ok := def.Call.Fun.(*ast.SelectorExpr) if !ok { continue } ident, ok := selectorX(sel).(*ast.Ident) if !ok { continue } if ident.Obj != lhs.Obj { continue } if sel.Sel.Name != "Close" { continue } j.Errorf(def, "should check returned error before deferring %s", j.Render(def.Call)) } return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func selectorX(sel *ast.SelectorExpr) ast.Node { switch x := sel.X.(type) { case *ast.SelectorExpr: return selectorX(x) default: return x } } func (c *Checker) CheckEmptyCriticalSection(j *lint.Job) { // Initially it might seem like this check would be easier to // implement in SSA. After all, we're only checking for two // consecutive method calls. In reality, however, there may be any // number of other instructions between the lock and unlock, while // still constituting an empty critical section. For example, // given `m.x().Lock(); m.x().Unlock()`, there will be a call to // x(). In the AST-based approach, this has a tiny potential for a // false positive (the second call to x might be doing work that // is protected by the mutex). In an SSA-based approach, however, // it would miss a lot of real bugs. mutexParams := func(s ast.Stmt) (x ast.Expr, funcName string, ok bool) { expr, ok := s.(*ast.ExprStmt) if !ok { return nil, "", false } call, ok := expr.X.(*ast.CallExpr) if !ok { return nil, "", false } sel, ok := call.Fun.(*ast.SelectorExpr) if !ok { return nil, "", false } fn, ok := j.Program.Info.ObjectOf(sel.Sel).(*types.Func) if !ok { return nil, "", false } sig := fn.Type().(*types.Signature) if sig.Params().Len() != 0 || sig.Results().Len() != 0 { return nil, "", false } return sel.X, fn.Name(), true } fn := func(node ast.Node) bool { block, ok := node.(*ast.BlockStmt) if !ok { return true } if len(block.List) < 2 { return true } for i := range block.List[:len(block.List)-1] { sel1, method1, ok1 := mutexParams(block.List[i]) sel2, method2, ok2 := mutexParams(block.List[i+1]) if !ok1 || !ok2 || j.Render(sel1) != j.Render(sel2) { continue } if (method1 == "Lock" && method2 == "Unlock") || (method1 == "RLock" && method2 == "RUnlock") { j.Errorf(block.List[i+1], "empty critical section") } } return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } // cgo produces code like fn(&*_Cvar_kSomeCallbacks) which we don't // want to flag. var cgoIdent = regexp.MustCompile(`^_C(func|var)_.+$`) func (c *Checker) CheckIneffectiveCopy(j *lint.Job) { fn := func(node ast.Node) bool { if unary, ok := node.(*ast.UnaryExpr); ok { if star, ok := unary.X.(*ast.StarExpr); ok && unary.Op == token.AND { ident, ok := star.X.(*ast.Ident) if !ok || !cgoIdent.MatchString(ident.Name) { j.Errorf(unary, "&*x will be simplified to x. It will not copy x.") } } } if star, ok := node.(*ast.StarExpr); ok { if unary, ok := star.X.(*ast.UnaryExpr); ok && unary.Op == token.AND { j.Errorf(star, "*&x will be simplified to x. It will not copy x.") } } return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func (c *Checker) CheckDiffSizeComparison(j *lint.Job) { for _, ssafn := range j.Program.InitialFunctions { for _, b := range ssafn.Blocks { for _, ins := range b.Instrs { binop, ok := ins.(*ssa.BinOp) if !ok { continue } if binop.Op != token.EQL && binop.Op != token.NEQ { continue } _, ok1 := binop.X.(*ssa.Slice) _, ok2 := binop.Y.(*ssa.Slice) if !ok1 && !ok2 { continue } r := c.funcDescs.Get(ssafn).Ranges r1, ok1 := r.Get(binop.X).(vrp.StringInterval) r2, ok2 := r.Get(binop.Y).(vrp.StringInterval) if !ok1 || !ok2 { continue } if r1.Length.Intersection(r2.Length).Empty() { j.Errorf(binop, "comparing strings of different sizes for equality will always return false") } } } } } func (c *Checker) CheckCanonicalHeaderKey(j *lint.Job) { fn := func(node ast.Node) bool { assign, ok := node.(*ast.AssignStmt) if ok { // TODO(dh): This risks missing some Header reads, for // example in `h1["foo"] = h2["foo"]` – these edge // cases are probably rare enough to ignore for now. for _, expr := range assign.Lhs { op, ok := expr.(*ast.IndexExpr) if !ok { continue } if hasType(j, op.X, "net/http.Header") { return false } } return true } op, ok := node.(*ast.IndexExpr) if !ok { return true } if !hasType(j, op.X, "net/http.Header") { return true } s, ok := j.ExprToString(op.Index) if !ok { return true } if s == http.CanonicalHeaderKey(s) { return true } j.Errorf(op, "keys in http.Header are canonicalized, %q is not canonical; fix the constant or use http.CanonicalHeaderKey", s) return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func (c *Checker) CheckBenchmarkN(j *lint.Job) { fn := func(node ast.Node) bool { assign, ok := node.(*ast.AssignStmt) if !ok { return true } if len(assign.Lhs) != 1 || len(assign.Rhs) != 1 { return true } sel, ok := assign.Lhs[0].(*ast.SelectorExpr) if !ok { return true } if sel.Sel.Name != "N" { return true } if !hasType(j, sel.X, "*testing.B") { return true } j.Errorf(assign, "should not assign to %s", j.Render(sel)) return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func (c *Checker) CheckIneffectiveFieldAssignments(j *lint.Job) { for _, ssafn := range j.Program.InitialFunctions { // fset := j.Program.SSA.Fset // if fset.File(f.File.Pos()) != fset.File(ssafn.Pos()) { // continue // } if ssafn.Signature.Recv() == nil { continue } if len(ssafn.Blocks) == 0 { // External function continue } reads := map[*ssa.BasicBlock]map[ssa.Value]bool{} writes := map[*ssa.BasicBlock]map[ssa.Value]bool{} recv := ssafn.Params[0] if _, ok := recv.Type().Underlying().(*types.Struct); !ok { continue } recvPtrs := map[ssa.Value]bool{ recv: true, } if len(ssafn.Locals) == 0 || ssafn.Locals[0].Heap { continue } blocks := ssafn.DomPreorder() for _, block := range blocks { if writes[block] == nil { writes[block] = map[ssa.Value]bool{} } if reads[block] == nil { reads[block] = map[ssa.Value]bool{} } for _, ins := range block.Instrs { switch ins := ins.(type) { case *ssa.Store: if recvPtrs[ins.Val] { recvPtrs[ins.Addr] = true } fa, ok := ins.Addr.(*ssa.FieldAddr) if !ok { continue } if !recvPtrs[fa.X] { continue } writes[block][fa] = true case *ssa.UnOp: if ins.Op != token.MUL { continue } if recvPtrs[ins.X] { reads[block][ins] = true continue } fa, ok := ins.X.(*ssa.FieldAddr) if !ok { continue } if !recvPtrs[fa.X] { continue } reads[block][fa] = true } } } for block, writes := range writes { seen := map[*ssa.BasicBlock]bool{} var hasRead func(block *ssa.BasicBlock, write *ssa.FieldAddr) bool hasRead = func(block *ssa.BasicBlock, write *ssa.FieldAddr) bool { seen[block] = true for read := range reads[block] { switch ins := read.(type) { case *ssa.FieldAddr: if ins.Field == write.Field && read.Pos() > write.Pos() { return true } case *ssa.UnOp: if ins.Pos() >= write.Pos() { return true } } } for _, succ := range block.Succs { if !seen[succ] { if hasRead(succ, write) { return true } } } return false } for write := range writes { fa := write.(*ssa.FieldAddr) if !hasRead(block, fa) { name := recv.Type().Underlying().(*types.Struct).Field(fa.Field).Name() j.Errorf(fa, "ineffective assignment to field %s", name) } } } } } func (c *Checker) CheckUnreadVariableValues(j *lint.Job) { fn := func(node ast.Node) bool { switch node.(type) { case *ast.FuncDecl, *ast.FuncLit: default: return true } ssafn := c.nodeFns[node] if ssafn == nil { return true } if lint.IsExample(ssafn) { return true } ast.Inspect(node, func(node ast.Node) bool { assign, ok := node.(*ast.AssignStmt) if !ok { return true } if len(assign.Lhs) > 1 && len(assign.Rhs) == 1 { // Either a function call with multiple return values, // or a comma-ok assignment val, _ := ssafn.ValueForExpr(assign.Rhs[0]) if val == nil { return true } refs := val.Referrers() if refs == nil { return true } for _, ref := range *refs { ex, ok := ref.(*ssa.Extract) if !ok { continue } exrefs := ex.Referrers() if exrefs == nil { continue } if len(lint.FilterDebug(*exrefs)) == 0 { lhs := assign.Lhs[ex.Index] if ident, ok := lhs.(*ast.Ident); !ok || ok && ident.Name == "_" { continue } j.Errorf(lhs, "this value of %s is never used", lhs) } } return true } for i, lhs := range assign.Lhs { rhs := assign.Rhs[i] if ident, ok := lhs.(*ast.Ident); !ok || ok && ident.Name == "_" { continue } val, _ := ssafn.ValueForExpr(rhs) if val == nil { continue } refs := val.Referrers() if refs == nil { // TODO investigate why refs can be nil return true } if len(lint.FilterDebug(*refs)) == 0 { j.Errorf(lhs, "this value of %s is never used", lhs) } } return true }) return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func (c *Checker) CheckPredeterminedBooleanExprs(j *lint.Job) { for _, ssafn := range j.Program.InitialFunctions { for _, block := range ssafn.Blocks { for _, ins := range block.Instrs { ssabinop, ok := ins.(*ssa.BinOp) if !ok { continue } switch ssabinop.Op { case token.GTR, token.LSS, token.EQL, token.NEQ, token.LEQ, token.GEQ: default: continue } xs, ok1 := consts(ssabinop.X, nil, nil) ys, ok2 := consts(ssabinop.Y, nil, nil) if !ok1 || !ok2 || len(xs) == 0 || len(ys) == 0 { continue } trues := 0 for _, x := range xs { for _, y := range ys { if x.Value == nil { if y.Value == nil { trues++ } continue } if constant.Compare(x.Value, ssabinop.Op, y.Value) { trues++ } } } b := trues != 0 if trues == 0 || trues == len(xs)*len(ys) { j.Errorf(ssabinop, "binary expression is always %t for all possible values (%s %s %s)", b, xs, ssabinop.Op, ys) } } } } } func (c *Checker) CheckNilMaps(j *lint.Job) { for _, ssafn := range j.Program.InitialFunctions { for _, block := range ssafn.Blocks { for _, ins := range block.Instrs { mu, ok := ins.(*ssa.MapUpdate) if !ok { continue } c, ok := mu.Map.(*ssa.Const) if !ok { continue } if c.Value != nil { continue } j.Errorf(mu, "assignment to nil map") } } } } func (c *Checker) CheckUnsignedComparison(j *lint.Job) { fn := func(node ast.Node) bool { expr, ok := node.(*ast.BinaryExpr) if !ok { return true } tx := j.Program.Info.TypeOf(expr.X) basic, ok := tx.Underlying().(*types.Basic) if !ok { return true } if (basic.Info() & types.IsUnsigned) == 0 { return true } lit, ok := expr.Y.(*ast.BasicLit) if !ok || lit.Value != "0" { return true } switch expr.Op { case token.GEQ: j.Errorf(expr, "unsigned values are always >= 0") case token.LSS: j.Errorf(expr, "unsigned values are never < 0") } return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func consts(val ssa.Value, out []*ssa.Const, visitedPhis map[string]bool) ([]*ssa.Const, bool) { if visitedPhis == nil { visitedPhis = map[string]bool{} } var ok bool switch val := val.(type) { case *ssa.Phi: if visitedPhis[val.Name()] { break } visitedPhis[val.Name()] = true vals := val.Operands(nil) for _, phival := range vals { out, ok = consts(*phival, out, visitedPhis) if !ok { return nil, false } } case *ssa.Const: out = append(out, val) case *ssa.Convert: out, ok = consts(val.X, out, visitedPhis) if !ok { return nil, false } default: return nil, false } if len(out) < 2 { return out, true } uniq := []*ssa.Const{out[0]} for _, val := range out[1:] { if val.Value == uniq[len(uniq)-1].Value { continue } uniq = append(uniq, val) } return uniq, true } func (c *Checker) CheckLoopCondition(j *lint.Job) { fn := func(node ast.Node) bool { loop, ok := node.(*ast.ForStmt) if !ok { return true } if loop.Init == nil || loop.Cond == nil || loop.Post == nil { return true } init, ok := loop.Init.(*ast.AssignStmt) if !ok || len(init.Lhs) != 1 || len(init.Rhs) != 1 { return true } cond, ok := loop.Cond.(*ast.BinaryExpr) if !ok { return true } x, ok := cond.X.(*ast.Ident) if !ok { return true } lhs, ok := init.Lhs[0].(*ast.Ident) if !ok { return true } if x.Obj != lhs.Obj { return true } if _, ok := loop.Post.(*ast.IncDecStmt); !ok { return true } ssafn := c.nodeFns[cond] if ssafn == nil { return true } v, isAddr := ssafn.ValueForExpr(cond.X) if v == nil || isAddr { return true } switch v := v.(type) { case *ssa.Phi: ops := v.Operands(nil) if len(ops) != 2 { return true } _, ok := (*ops[0]).(*ssa.Const) if !ok { return true } sigma, ok := (*ops[1]).(*ssa.Sigma) if !ok { return true } if sigma.X != v { return true } case *ssa.UnOp: return true } j.Errorf(cond, "variable in loop condition never changes") return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func (c *Checker) CheckArgOverwritten(j *lint.Job) { fn := func(node ast.Node) bool { var typ *ast.FuncType var body *ast.BlockStmt switch fn := node.(type) { case *ast.FuncDecl: typ = fn.Type body = fn.Body case *ast.FuncLit: typ = fn.Type body = fn.Body } if body == nil { return true } ssafn := c.nodeFns[node] if ssafn == nil { return true } if len(typ.Params.List) == 0 { return true } for _, field := range typ.Params.List { for _, arg := range field.Names { obj := j.Program.Info.ObjectOf(arg) var ssaobj *ssa.Parameter for _, param := range ssafn.Params { if param.Object() == obj { ssaobj = param break } } if ssaobj == nil { continue } refs := ssaobj.Referrers() if refs == nil { continue } if len(lint.FilterDebug(*refs)) != 0 { continue } assigned := false ast.Inspect(body, func(node ast.Node) bool { assign, ok := node.(*ast.AssignStmt) if !ok { return true } for _, lhs := range assign.Lhs { ident, ok := lhs.(*ast.Ident) if !ok { continue } if j.Program.Info.ObjectOf(ident) == obj { assigned = true return false } } return true }) if assigned { j.Errorf(arg, "argument %s is overwritten before first use", arg) } } } return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func (c *Checker) CheckIneffectiveLoop(j *lint.Job) { // This check detects some, but not all unconditional loop exits. // We give up in the following cases: // // - a goto anywhere in the loop. The goto might skip over our // return, and we don't check that it doesn't. // // - any nested, unlabelled continue, even if it is in another // loop or closure. fn := func(node ast.Node) bool { var body *ast.BlockStmt switch fn := node.(type) { case *ast.FuncDecl: body = fn.Body case *ast.FuncLit: body = fn.Body default: return true } if body == nil { return true } labels := map[*ast.Object]ast.Stmt{} ast.Inspect(body, func(node ast.Node) bool { label, ok := node.(*ast.LabeledStmt) if !ok { return true } labels[label.Label.Obj] = label.Stmt return true }) ast.Inspect(body, func(node ast.Node) bool { var loop ast.Node var body *ast.BlockStmt switch node := node.(type) { case *ast.ForStmt: body = node.Body loop = node case *ast.RangeStmt: typ := j.Program.Info.TypeOf(node.X) if _, ok := typ.Underlying().(*types.Map); ok { // looping once over a map is a valid pattern for // getting an arbitrary element. return true } body = node.Body loop = node default: return true } if len(body.List) < 2 { // avoid flagging the somewhat common pattern of using // a range loop to get the first element in a slice, // or the first rune in a string. return true } var unconditionalExit ast.Node hasBranching := false for _, stmt := range body.List { switch stmt := stmt.(type) { case *ast.BranchStmt: switch stmt.Tok { case token.BREAK: if stmt.Label == nil || labels[stmt.Label.Obj] == loop { unconditionalExit = stmt } case token.CONTINUE: if stmt.Label == nil || labels[stmt.Label.Obj] == loop { unconditionalExit = nil return false } } case *ast.ReturnStmt: unconditionalExit = stmt case *ast.IfStmt, *ast.ForStmt, *ast.RangeStmt, *ast.SwitchStmt, *ast.SelectStmt: hasBranching = true } } if unconditionalExit == nil || !hasBranching { return false } ast.Inspect(body, func(node ast.Node) bool { if branch, ok := node.(*ast.BranchStmt); ok { switch branch.Tok { case token.GOTO: unconditionalExit = nil return false case token.CONTINUE: if branch.Label != nil && labels[branch.Label.Obj] != loop { return true } unconditionalExit = nil return false } } return true }) if unconditionalExit != nil { j.Errorf(unconditionalExit, "the surrounding loop is unconditionally terminated") } return true }) return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func (c *Checker) CheckNilContext(j *lint.Job) { fn := func(node ast.Node) bool { call, ok := node.(*ast.CallExpr) if !ok { return true } if len(call.Args) == 0 { return true } if typ, ok := j.Program.Info.TypeOf(call.Args[0]).(*types.Basic); !ok || typ.Kind() != types.UntypedNil { return true } sig, ok := j.Program.Info.TypeOf(call.Fun).(*types.Signature) if !ok { return true } if sig.Params().Len() == 0 { return true } if types.TypeString(sig.Params().At(0).Type(), nil) != "context.Context" { return true } j.Errorf(call.Args[0], "do not pass a nil Context, even if a function permits it; pass context.TODO if you are unsure about which Context to use") return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func (c *Checker) CheckSeeker(j *lint.Job) { fn := func(node ast.Node) bool { call, ok := node.(*ast.CallExpr) if !ok { return true } sel, ok := call.Fun.(*ast.SelectorExpr) if !ok { return true } if sel.Sel.Name != "Seek" { return true } if len(call.Args) != 2 { return true } arg0, ok := call.Args[0].(*ast.SelectorExpr) if !ok { return true } switch arg0.Sel.Name { case "SeekStart", "SeekCurrent", "SeekEnd": default: return true } pkg, ok := arg0.X.(*ast.Ident) if !ok { return true } if pkg.Name != "io" { return true } j.Errorf(call, "the first argument of io.Seeker is the offset, but an io.Seek* constant is being used instead") return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func (c *Checker) CheckIneffectiveAppend(j *lint.Job) { isAppend := func(ins ssa.Value) bool { call, ok := ins.(*ssa.Call) if !ok { return false } if call.Call.IsInvoke() { return false } if builtin, ok := call.Call.Value.(*ssa.Builtin); !ok || builtin.Name() != "append" { return false } return true } for _, ssafn := range j.Program.InitialFunctions { for _, block := range ssafn.Blocks { for _, ins := range block.Instrs { val, ok := ins.(ssa.Value) if !ok || !isAppend(val) { continue } isUsed := false visited := map[ssa.Instruction]bool{} var walkRefs func(refs []ssa.Instruction) walkRefs = func(refs []ssa.Instruction) { loop: for _, ref := range refs { if visited[ref] { continue } visited[ref] = true if _, ok := ref.(*ssa.DebugRef); ok { continue } switch ref := ref.(type) { case *ssa.Phi: walkRefs(*ref.Referrers()) case *ssa.Sigma: walkRefs(*ref.Referrers()) case ssa.Value: if !isAppend(ref) { isUsed = true } else { walkRefs(*ref.Referrers()) } case ssa.Instruction: isUsed = true break loop } } } refs := val.Referrers() if refs == nil { continue } walkRefs(*refs) if !isUsed { j.Errorf(ins, "this result of append is never used, except maybe in other appends") } } } } } func (c *Checker) CheckConcurrentTesting(j *lint.Job) { for _, ssafn := range j.Program.InitialFunctions { for _, block := range ssafn.Blocks { for _, ins := range block.Instrs { gostmt, ok := ins.(*ssa.Go) if !ok { continue } var fn *ssa.Function switch val := gostmt.Call.Value.(type) { case *ssa.Function: fn = val case *ssa.MakeClosure: fn = val.Fn.(*ssa.Function) default: continue } if fn.Blocks == nil { continue } for _, block := range fn.Blocks { for _, ins := range block.Instrs { call, ok := ins.(*ssa.Call) if !ok { continue } if call.Call.IsInvoke() { continue } callee := call.Call.StaticCallee() if callee == nil { continue } recv := callee.Signature.Recv() if recv == nil { continue } if types.TypeString(recv.Type(), nil) != "*testing.common" { continue } fn, ok := call.Call.StaticCallee().Object().(*types.Func) if !ok { continue } name := fn.Name() switch name { case "FailNow", "Fatal", "Fatalf", "SkipNow", "Skip", "Skipf": default: continue } j.Errorf(gostmt, "the goroutine calls T.%s, which must be called in the same goroutine as the test", name) } } } } } } func (c *Checker) CheckCyclicFinalizer(j *lint.Job) { for _, ssafn := range j.Program.InitialFunctions { node := c.funcDescs.CallGraph.CreateNode(ssafn) for _, edge := range node.Out { if edge.Callee.Func.RelString(nil) != "runtime.SetFinalizer" { continue } arg0 := edge.Site.Common().Args[0] if iface, ok := arg0.(*ssa.MakeInterface); ok { arg0 = iface.X } unop, ok := arg0.(*ssa.UnOp) if !ok { continue } v, ok := unop.X.(*ssa.Alloc) if !ok { continue } arg1 := edge.Site.Common().Args[1] if iface, ok := arg1.(*ssa.MakeInterface); ok { arg1 = iface.X } mc, ok := arg1.(*ssa.MakeClosure) if !ok { continue } for _, b := range mc.Bindings { if b == v { pos := j.Program.SSA.Fset.Position(mc.Fn.Pos()) j.Errorf(edge.Site, "the finalizer closes over the object, preventing the finalizer from ever running (at %s)", pos) } } } } } func (c *Checker) CheckSliceOutOfBounds(j *lint.Job) { for _, ssafn := range j.Program.InitialFunctions { for _, block := range ssafn.Blocks { for _, ins := range block.Instrs { ia, ok := ins.(*ssa.IndexAddr) if !ok { continue } if _, ok := ia.X.Type().Underlying().(*types.Slice); !ok { continue } sr, ok1 := c.funcDescs.Get(ssafn).Ranges[ia.X].(vrp.SliceInterval) idxr, ok2 := c.funcDescs.Get(ssafn).Ranges[ia.Index].(vrp.IntInterval) if !ok1 || !ok2 || !sr.IsKnown() || !idxr.IsKnown() || sr.Length.Empty() || idxr.Empty() { continue } if idxr.Lower.Cmp(sr.Length.Upper) >= 0 { j.Errorf(ia, "index out of bounds") } } } } } func (c *Checker) CheckDeferLock(j *lint.Job) { for _, ssafn := range j.Program.InitialFunctions { for _, block := range ssafn.Blocks { instrs := lint.FilterDebug(block.Instrs) if len(instrs) < 2 { continue } for i, ins := range instrs[:len(instrs)-1] { call, ok := ins.(*ssa.Call) if !ok { continue } if !lint.IsCallTo(call.Common(), "(*sync.Mutex).Lock") && !lint.IsCallTo(call.Common(), "(*sync.RWMutex).RLock") { continue } nins, ok := instrs[i+1].(*ssa.Defer) if !ok { continue } if !lint.IsCallTo(&nins.Call, "(*sync.Mutex).Lock") && !lint.IsCallTo(&nins.Call, "(*sync.RWMutex).RLock") { continue } if call.Common().Args[0] != nins.Call.Args[0] { continue } name := shortCallName(call.Common()) alt := "" switch name { case "Lock": alt = "Unlock" case "RLock": alt = "RUnlock" } j.Errorf(nins, "deferring %s right after having locked already; did you mean to defer %s?", name, alt) } } } } func (c *Checker) CheckNaNComparison(j *lint.Job) { isNaN := func(v ssa.Value) bool { call, ok := v.(*ssa.Call) if !ok { return false } return lint.IsCallTo(call.Common(), "math.NaN") } for _, ssafn := range j.Program.InitialFunctions { for _, block := range ssafn.Blocks { for _, ins := range block.Instrs { ins, ok := ins.(*ssa.BinOp) if !ok { continue } if isNaN(ins.X) || isNaN(ins.Y) { j.Errorf(ins, "no value is equal to NaN, not even NaN itself") } } } } } func (c *Checker) CheckInfiniteRecursion(j *lint.Job) { for _, ssafn := range j.Program.InitialFunctions { node := c.funcDescs.CallGraph.CreateNode(ssafn) for _, edge := range node.Out { if edge.Callee != node { continue } block := edge.Site.Block() canReturn := false for _, b := range ssafn.Blocks { if block.Dominates(b) { continue } if len(b.Instrs) == 0 { continue } if _, ok := b.Instrs[len(b.Instrs)-1].(*ssa.Return); ok { canReturn = true break } } if canReturn { continue } j.Errorf(edge.Site, "infinite recursive call") } } } func objectName(obj types.Object) string { if obj == nil { return "<nil>" } var name string if obj.Pkg() != nil && obj.Pkg().Scope().Lookup(obj.Name()) == obj { var s string s = obj.Pkg().Path() if s != "" { name += s + "." } } name += obj.Name() return name } func isName(j *lint.Job, expr ast.Expr, name string) bool { var obj types.Object switch expr := expr.(type) { case *ast.Ident: obj = j.Program.Info.ObjectOf(expr) case *ast.SelectorExpr: obj = j.Program.Info.ObjectOf(expr.Sel) } return objectName(obj) == name } func (c *Checker) CheckLeakyTimeTick(j *lint.Job) { for _, ssafn := range j.Program.InitialFunctions { if j.IsInMain(ssafn) || j.IsInTest(ssafn) { continue } for _, block := range ssafn.Blocks { for _, ins := range block.Instrs { call, ok := ins.(*ssa.Call) if !ok || !lint.IsCallTo(call.Common(), "time.Tick") { continue } if c.funcDescs.Get(call.Parent()).Infinite { continue } j.Errorf(call, "using time.Tick leaks the underlying ticker, consider using it only in endless functions, tests and the main package, and use time.NewTicker here") } } } } func (c *Checker) CheckDoubleNegation(j *lint.Job) { fn := func(node ast.Node) bool { unary1, ok := node.(*ast.UnaryExpr) if !ok { return true } unary2, ok := unary1.X.(*ast.UnaryExpr) if !ok { return true } if unary1.Op != token.NOT || unary2.Op != token.NOT { return true } j.Errorf(unary1, "negating a boolean twice has no effect; is this a typo?") return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func hasSideEffects(node ast.Node) bool { dynamic := false ast.Inspect(node, func(node ast.Node) bool { switch node := node.(type) { case *ast.CallExpr: dynamic = true return false case *ast.UnaryExpr: if node.Op == token.ARROW { dynamic = true return false } } return true }) return dynamic } func (c *Checker) CheckRepeatedIfElse(j *lint.Job) { seen := map[ast.Node]bool{} var collectConds func(ifstmt *ast.IfStmt, inits []ast.Stmt, conds []ast.Expr) ([]ast.Stmt, []ast.Expr) collectConds = func(ifstmt *ast.IfStmt, inits []ast.Stmt, conds []ast.Expr) ([]ast.Stmt, []ast.Expr) { seen[ifstmt] = true if ifstmt.Init != nil { inits = append(inits, ifstmt.Init) } conds = append(conds, ifstmt.Cond) if elsestmt, ok := ifstmt.Else.(*ast.IfStmt); ok { return collectConds(elsestmt, inits, conds) } return inits, conds } fn := func(node ast.Node) bool { ifstmt, ok := node.(*ast.IfStmt) if !ok { return true } if seen[ifstmt] { return true } inits, conds := collectConds(ifstmt, nil, nil) if len(inits) > 0 { return true } for _, cond := range conds { if hasSideEffects(cond) { return true } } counts := map[string]int{} for _, cond := range conds { s := j.Render(cond) counts[s]++ if counts[s] == 2 { j.Errorf(cond, "this condition occurs multiple times in this if/else if chain") } } return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func (c *Checker) CheckSillyBitwiseOps(j *lint.Job) { for _, ssafn := range j.Program.InitialFunctions { for _, block := range ssafn.Blocks { for _, ins := range block.Instrs { ins, ok := ins.(*ssa.BinOp) if !ok { continue } if c, ok := ins.Y.(*ssa.Const); !ok || c.Value == nil || c.Value.Kind() != constant.Int || c.Uint64() != 0 { continue } switch ins.Op { case token.AND, token.OR, token.XOR: default: // we do not flag shifts because too often, x<<0 is part // of a pattern, x<<0, x<<8, x<<16, ... continue } path, _ := astutil.PathEnclosingInterval(j.File(ins), ins.Pos(), ins.Pos()) if len(path) == 0 { continue } if node, ok := path[0].(*ast.BinaryExpr); !ok || !lint.IsZero(node.Y) { continue } switch ins.Op { case token.AND: j.Errorf(ins, "x & 0 always equals 0") case token.OR, token.XOR: j.Errorf(ins, "x %s 0 always equals x", ins.Op) } } } } } func (c *Checker) CheckNonOctalFileMode(j *lint.Job) { fn := func(node ast.Node) bool { call, ok := node.(*ast.CallExpr) if !ok { return true } sig, ok := j.Program.Info.TypeOf(call.Fun).(*types.Signature) if !ok { return true } n := sig.Params().Len() var args []int for i := 0; i < n; i++ { typ := sig.Params().At(i).Type() if types.TypeString(typ, nil) == "os.FileMode" { args = append(args, i) } } for _, i := range args { lit, ok := call.Args[i].(*ast.BasicLit) if !ok { continue } if len(lit.Value) == 3 && lit.Value[0] != '0' && lit.Value[0] >= '0' && lit.Value[0] <= '7' && lit.Value[1] >= '0' && lit.Value[1] <= '7' && lit.Value[2] >= '0' && lit.Value[2] <= '7' { v, err := strconv.ParseInt(lit.Value, 10, 64) if err != nil { continue } j.Errorf(call.Args[i], "file mode '%s' evaluates to %#o; did you mean '0%s'?", lit.Value, v, lit.Value) } } return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func (c *Checker) CheckPureFunctions(j *lint.Job) { fnLoop: for _, ssafn := range j.Program.InitialFunctions { if j.IsInTest(ssafn) { params := ssafn.Signature.Params() for i := 0; i < params.Len(); i++ { param := params.At(i) if types.TypeString(param.Type(), nil) == "*testing.B" { // Ignore discarded pure functions in code related // to benchmarks. Instead of matching BenchmarkFoo // functions, we match any function accepting a // *testing.B. Benchmarks sometimes call generic // functions for doing the actual work, and // checking for the parameter is a lot easier and // faster than analyzing call trees. continue fnLoop } } } for _, b := range ssafn.Blocks { for _, ins := range b.Instrs { ins, ok := ins.(*ssa.Call) if !ok { continue } refs := ins.Referrers() if refs == nil || len(lint.FilterDebug(*refs)) > 0 { continue } callee := ins.Common().StaticCallee() if callee == nil { continue } if c.funcDescs.Get(callee).Pure { j.Errorf(ins, "%s is a pure function but its return value is ignored", callee.Name()) continue } } } } } func enclosingFunction(j *lint.Job, node ast.Node) *ast.FuncDecl { f := j.File(node) path, _ := astutil.PathEnclosingInterval(f, node.Pos(), node.Pos()) for _, e := range path { fn, ok := e.(*ast.FuncDecl) if !ok { continue } if fn.Name == nil { continue } return fn } return nil } func (c *Checker) isDeprecated(j *lint.Job, ident *ast.Ident) (bool, string) { obj := j.Program.Info.ObjectOf(ident) if obj.Pkg() == nil { return false, "" } alt := c.deprecatedObjs[obj] return alt != "", alt } func (c *Checker) CheckDeprecated(j *lint.Job) { fn := func(node ast.Node) bool { sel, ok := node.(*ast.SelectorExpr) if !ok { return true } if fn := enclosingFunction(j, sel); fn != nil { if ok, _ := c.isDeprecated(j, fn.Name); ok { // functions that are deprecated may use deprecated // symbols return true } } obj := j.Program.Info.ObjectOf(sel.Sel) if obj.Pkg() == nil { return true } nodePkg := j.NodePackage(node).Pkg if nodePkg == obj.Pkg() || obj.Pkg().Path()+"_test" == nodePkg.Path() { // Don't flag stuff in our own package return true } if ok, alt := c.isDeprecated(j, sel.Sel); ok { j.Errorf(sel, "%s is deprecated: %s", j.Render(sel), alt) return true } return true } for _, f := range j.Program.Files { ast.Inspect(f, fn) } } func (c *Checker) callChecker(rules map[string]CallCheck) func(j *lint.Job) { return func(j *lint.Job) { c.checkCalls(j, rules) } } func (c *Checker) checkCalls(j *lint.Job, rules map[string]CallCheck) { for _, ssafn := range j.Program.InitialFunctions { node := c.funcDescs.CallGraph.CreateNode(ssafn) for _, edge := range node.Out { callee := edge.Callee.Func obj, ok := callee.Object().(*types.Func) if !ok { continue } r, ok := rules[obj.FullName()] if !ok { continue } var args []*Argument ssaargs := edge.Site.Common().Args if callee.Signature.Recv() != nil { ssaargs = ssaargs[1:] } for _, arg := range ssaargs { if iarg, ok := arg.(*ssa.MakeInterface); ok { arg = iarg.X } vr := c.funcDescs.Get(edge.Site.Parent()).Ranges[arg] args = append(args, &Argument{Value: Value{arg, vr}}) } call := &Call{ Job: j, Instr: edge.Site, Args: args, Checker: c, Parent: edge.Site.Parent(), } r(call) for idx, arg := range call.Args { _ = idx for _, e := range arg.invalids { // path, _ := astutil.PathEnclosingInterval(f.File, edge.Site.Pos(), edge.Site.Pos()) // if len(path) < 2 { // continue // } // astcall, ok := path[0].(*ast.CallExpr) // if !ok { // continue // } // j.Errorf(astcall.Args[idx], "%s", e) j.Errorf(edge.Site, "%s", e) } } for _, e := range call.invalids { j.Errorf(call.Instr.Common(), "%s", e) } } } } func unwrapFunction(val ssa.Value) *ssa.Function { switch val := val.(type) { case *ssa.Function: return val case *ssa.MakeClosure: return val.Fn.(*ssa.Function) default: return nil } } func shortCallName(call *ssa.CallCommon) string { if call.IsInvoke() { return "" } switch v := call.Value.(type) { case *ssa.Function: fn, ok := v.Object().(*types.Func) if !ok { return "" } return fn.Name() case *ssa.Builtin: return v.Name() } return "" } func hasCallTo(block *ssa.BasicBlock, name string) bool { for _, ins := range block.Instrs { call, ok := ins.(*ssa.Call) if !ok { continue } if lint.IsCallTo(call.Common(), name) { return true } } return false } // deref returns a pointer's element type; otherwise it returns typ. func deref(typ types.Type) types.Type { if p, ok := typ.Underlying().(*types.Pointer); ok { return p.Elem() } return typ } func (c *Checker) CheckWriterBufferModified(j *lint.Job) { // TODO(dh): this might be a good candidate for taint analysis. // Taint the argument as MUST_NOT_MODIFY, then propagate that // through functions like bytes.Split for _, ssafn := range j.Program.InitialFunctions { sig := ssafn.Signature if ssafn.Name() != "Write" || sig.Recv() == nil || sig.Params().Len() != 1 || sig.Results().Len() != 2 { continue } tArg, ok := sig.Params().At(0).Type().(*types.Slice) if !ok { continue } if basic, ok := tArg.Elem().(*types.Basic); !ok || basic.Kind() != types.Byte { continue } if basic, ok := sig.Results().At(0).Type().(*types.Basic); !ok || basic.Kind() != types.Int { continue } if named, ok := sig.Results().At(1).Type().(*types.Named); !ok || types.TypeString(named, nil) != "error" { continue } for _, block := range ssafn.Blocks { for _, ins := range block.Instrs { switch ins := ins.(type) { case *ssa.Store: addr, ok := ins.Addr.(*ssa.IndexAddr) if !ok { continue } if addr.X != ssafn.Params[1] { continue } j.Errorf(ins, "io.Writer.Write must not modify the provided buffer, not even temporarily") case *ssa.Call: if !lint.IsCallTo(ins.Common(), "append") { continue } if ins.Common().Args[0] != ssafn.Params[1] { continue } j.Errorf(ins, "io.Writer.Write must not modify the provided buffer, not even temporarily") } } } } } func loopedRegexp(name string) CallCheck { return func(call *Call) { if len(extractConsts(call.Args[0].Value.Value)) == 0 { return } if !call.Checker.isInLoop(call.Instr.Block()) { return } call.Invalid(fmt.Sprintf("calling %s in a loop has poor performance, consider using regexp.Compile", name)) } } func (c *Checker) CheckEmptyBranch(j *lint.Job) { fn := func(node ast.Node) bool { ifstmt, ok := node.(*ast.IfStmt) if !ok { return true } ssafn := c.nodeFns[node] if lint.IsExample(ssafn) { return true } if ifstmt.Else != nil { b, ok := ifstmt.Else.(*ast.BlockStmt) if !ok || len(b.List) != 0 { return true } j.Errorf(ifstmt.Else, "empty branch") } if len(ifstmt.Body.List) != 0 { return true } j.Errorf(ifstmt, "empty branch") return true } for _, f := range c.filterGenerated(j.Program.Files) { ast.Inspect(f, fn) } } func (c *Checker) CheckMapBytesKey(j *lint.Job) { for _, fn := range j.Program.InitialFunctions { for _, b := range fn.Blocks { insLoop: for _, ins := range b.Instrs { // find []byte -> string conversions conv, ok := ins.(*ssa.Convert) if !ok || conv.Type() != types.Universe.Lookup("string").Type() { continue } if s, ok := conv.X.Type().(*types.Slice); !ok || s.Elem() != types.Universe.Lookup("byte").Type() { continue } refs := conv.Referrers() // need at least two (DebugRef) references: the // conversion and the *ast.Ident if refs == nil || len(*refs) < 2 { continue } ident := false // skip first reference, that's the conversion itself for _, ref := range (*refs)[1:] { switch ref := ref.(type) { case *ssa.DebugRef: if _, ok := ref.Expr.(*ast.Ident); !ok { // the string seems to be used somewhere // unexpected; the default branch should // catch this already, but be safe continue insLoop } else { ident = true } case *ssa.Lookup: default: // the string is used somewhere else than a // map lookup continue insLoop } } // the result of the conversion wasn't assigned to an // identifier if !ident { continue } j.Errorf(conv, "m[string(key)] would be more efficient than k := string(key); m[k]") } } } } func (c *Checker) CheckRangeStringRunes(j *lint.Job) { sharedcheck.CheckRangeStringRunes(c.nodeFns, j) } func (c *Checker) CheckSelfAssignment(j *lint.Job) { fn := func(node ast.Node) bool { assign, ok := node.(*ast.AssignStmt) if !ok { return true } if assign.Tok != token.ASSIGN || len(assign.Lhs) != len(assign.Rhs) { return true } for i, stmt := range assign.Lhs { rlh := j.Render(stmt) rrh := j.Render(assign.Rhs[i]) if rlh == rrh { j.Errorf(assign, "self-assignment of %s to %s", rrh, rlh) } } return true } for _, f := range c.filterGenerated(j.Program.Files) { ast.Inspect(f, fn) } } func buildTagsIdentical(s1, s2 []string) bool { if len(s1) != len(s2) { return false } s1s := make([]string, len(s1)) copy(s1s, s1) sort.Strings(s1s) s2s := make([]string, len(s2)) copy(s2s, s2) sort.Strings(s2s) for i, s := range s1s { if s != s2s[i] { return false } } return true } func (c *Checker) CheckDuplicateBuildConstraints(job *lint.Job) { for _, f := range c.filterGenerated(job.Program.Files) { constraints := buildTags(f) for i, constraint1 := range constraints { for j, constraint2 := range constraints { if i >= j { continue } if buildTagsIdentical(constraint1, constraint2) { job.Errorf(f, "identical build constraints %q and %q", strings.Join(constraint1, " "), strings.Join(constraint2, " ")) } } } } }
variadico/etercli
vendor/honnef.co/go/tools/staticcheck/lint.go
GO
mit
68,888
# -*- coding: utf-8 -*- """The initialization file for the Pywikibot framework.""" # # (C) Pywikibot team, 2008-2014 # # Distributed under the terms of the MIT license. # from __future__ import unicode_literals __release__ = '2.0rc4' __version__ = '$Id: e26392a530582f286edf2d99e729218b2e93405e $' import datetime import math import re import sys import threading import json if sys.version_info[0] > 2: from queue import Queue long = int else: from Queue import Queue from warnings import warn # Use pywikibot. prefix for all in-package imports; this is to prevent # confusion with similarly-named modules in version 1 framework, for users # who want to continue using both from pywikibot import config2 as config from pywikibot.bot import ( output, warning, error, critical, debug, stdout, exception, input, input_choice, input_yn, inputChoice, handle_args, showHelp, ui, log, calledModuleName, Bot, CurrentPageBot, WikidataBot, QuitKeyboardInterrupt, # the following are flagged as deprecated on usage handleArgs, ) from pywikibot.exceptions import ( Error, InvalidTitle, BadTitle, NoPage, SectionError, SiteDefinitionError, NoSuchSite, UnknownSite, UnknownFamily, UnknownExtension, NoUsername, UserBlocked, PageRelatedError, IsRedirectPage, IsNotRedirectPage, PageSaveRelatedError, PageNotSaved, OtherPageSaveError, LockedPage, CascadeLockedPage, LockedNoPage, NoCreateError, EditConflict, PageDeletedConflict, PageCreatedConflict, ServerError, FatalServerError, Server504Error, CaptchaError, SpamfilterError, CircularRedirect, InterwikiRedirectPage, WikiBaseError, CoordinateGlobeUnknownException, ) from pywikibot.tools import UnicodeMixin, redirect_func from pywikibot.i18n import translate from pywikibot.data.api import UploadWarning from pywikibot.diff import PatchManager import pywikibot.textlib as textlib import pywikibot.tools textlib_methods = ( 'unescape', 'replaceExcept', 'removeDisabledParts', 'removeHTMLParts', 'isDisabled', 'interwikiFormat', 'interwikiSort', 'getLanguageLinks', 'replaceLanguageLinks', 'removeLanguageLinks', 'removeLanguageLinksAndSeparator', 'getCategoryLinks', 'categoryFormat', 'replaceCategoryLinks', 'removeCategoryLinks', 'removeCategoryLinksAndSeparator', 'replaceCategoryInPlace', 'compileLinkR', 'extract_templates_and_params', 'TimeStripper', ) # pep257 doesn't understand when the first entry is on the next line __all__ = ('config', 'ui', 'UnicodeMixin', 'translate', 'Page', 'FilePage', 'Category', 'Link', 'User', 'ItemPage', 'PropertyPage', 'Claim', 'html2unicode', 'url2unicode', 'unicode2html', 'stdout', 'output', 'warning', 'error', 'critical', 'debug', 'exception', 'input_choice', 'input', 'input_yn', 'inputChoice', 'handle_args', 'handleArgs', 'showHelp', 'ui', 'log', 'calledModuleName', 'Bot', 'CurrentPageBot', 'WikidataBot', 'Error', 'InvalidTitle', 'BadTitle', 'NoPage', 'SectionError', 'SiteDefinitionError', 'NoSuchSite', 'UnknownSite', 'UnknownFamily', 'UnknownExtension', 'NoUsername', 'UserBlocked', 'UserActionRefuse', 'PageRelatedError', 'IsRedirectPage', 'IsNotRedirectPage', 'PageSaveRelatedError', 'PageNotSaved', 'OtherPageSaveError', 'LockedPage', 'CascadeLockedPage', 'LockedNoPage', 'NoCreateError', 'EditConflict', 'PageDeletedConflict', 'PageCreatedConflict', 'UploadWarning', 'ServerError', 'FatalServerError', 'Server504Error', 'CaptchaError', 'SpamfilterError', 'CircularRedirect', 'InterwikiRedirectPage', 'WikiBaseError', 'CoordinateGlobeUnknownException', 'QuitKeyboardInterrupt', ) # flake8 is unable to detect concatenation in the same operation # like: # ) + textlib_methods # pep257 also doesn't support __all__ multiple times in a document # so instead use this trick globals()['__all__'] = globals()['__all__'] + textlib_methods if sys.version_info[0] == 2: # T111615: Python 2 requires __all__ is bytes globals()['__all__'] = tuple(bytes(item) for item in __all__) for _name in textlib_methods: target = getattr(textlib, _name) wrapped_func = redirect_func(target) globals()[_name] = wrapped_func deprecated = redirect_func(pywikibot.tools.deprecated) deprecate_arg = redirect_func(pywikibot.tools.deprecate_arg) class Timestamp(datetime.datetime): """Class for handling MediaWiki timestamps. This inherits from datetime.datetime, so it can use all of the methods and operations of a datetime object. To ensure that the results of any operation are also a Timestamp object, be sure to use only Timestamp objects (and datetime.timedeltas) in any operation. Use Timestamp.fromISOformat() and Timestamp.fromtimestampformat() to create Timestamp objects from MediaWiki string formats. As these constructors are typically used to create objects using data passed provided by site and page methods, some of which return a Timestamp when previously they returned a MediaWiki string representation, these methods also accept a Timestamp object, in which case they return a clone. Use Site.getcurrenttime() for the current time; this is more reliable than using Timestamp.utcnow(). """ mediawikiTSFormat = "%Y%m%d%H%M%S" ISO8601Format = "%Y-%m-%dT%H:%M:%SZ" def clone(self): """Clone this instance.""" return self.replace(microsecond=self.microsecond) @classmethod def fromISOformat(cls, ts): """Convert an ISO 8601 timestamp to a Timestamp object.""" # If inadvertantly passed a Timestamp object, use replace() # to create a clone. if isinstance(ts, cls): return ts.clone() return cls.strptime(ts, cls.ISO8601Format) @classmethod def fromtimestampformat(cls, ts): """Convert a MediaWiki internal timestamp to a Timestamp object.""" # If inadvertantly passed a Timestamp object, use replace() # to create a clone. if isinstance(ts, cls): return ts.clone() return cls.strptime(ts, cls.mediawikiTSFormat) def isoformat(self): """ Convert object to an ISO 8601 timestamp accepted by MediaWiki. datetime.datetime.isoformat does not postfix the ISO formatted date with a 'Z' unless a timezone is included, which causes MediaWiki ~1.19 and earlier to fail. """ return self.strftime(self.ISO8601Format) toISOformat = redirect_func(isoformat, old_name='toISOformat', class_name='Timestamp') def totimestampformat(self): """Convert object to a MediaWiki internal timestamp.""" return self.strftime(self.mediawikiTSFormat) def __str__(self): """Return a string format recognized by the API.""" return self.isoformat() def __add__(self, other): """Perform addition, returning a Timestamp instead of datetime.""" newdt = super(Timestamp, self).__add__(other) if isinstance(newdt, datetime.datetime): return Timestamp(newdt.year, newdt.month, newdt.day, newdt.hour, newdt.minute, newdt.second, newdt.microsecond, newdt.tzinfo) else: return newdt def __sub__(self, other): """Perform substraction, returning a Timestamp instead of datetime.""" newdt = super(Timestamp, self).__sub__(other) if isinstance(newdt, datetime.datetime): return Timestamp(newdt.year, newdt.month, newdt.day, newdt.hour, newdt.minute, newdt.second, newdt.microsecond, newdt.tzinfo) else: return newdt class Coordinate(object): """ Class for handling and storing Coordinates. For now its just being used for DataSite, but in the future we can use it for the GeoData extension. """ def __init__(self, lat, lon, alt=None, precision=None, globe='earth', typ="", name="", dim=None, site=None, entity=''): """ Represent a geo coordinate. @param lat: Latitude @type lat: float @param lon: Longitude @type lon: float @param alt: Altitute? TODO FIXME @param precision: precision @type precision: float @param globe: Which globe the point is on @type globe: str @param typ: The type of coordinate point @type typ: str @param name: The name @type name: str @param dim: Dimension (in meters) @type dim: int @param entity: The URL entity of a Wikibase item @type entity: str """ self.lat = lat self.lon = lon self.alt = alt self._precision = precision if globe: globe = globe.lower() self.globe = globe self._entity = entity self.type = typ self.name = name self._dim = dim if not site: self.site = Site().data_repository() else: self.site = site def __repr__(self): string = 'Coordinate(%s, %s' % (self.lat, self.lon) if self.globe != 'earth': string += ', globe="%s"' % self.globe string += ')' return string @property def entity(self): if self._entity: return self._entity return self.site.globes()[self.globe] def toWikibase(self): """ Export the data to a JSON object for the Wikibase API. FIXME: Should this be in the DataSite object? """ if self.globe not in self.site.globes(): raise CoordinateGlobeUnknownException( u"%s is not supported in Wikibase yet." % self.globe) return {'latitude': self.lat, 'longitude': self.lon, 'altitude': self.alt, 'globe': self.entity, 'precision': self.precision, } @classmethod def fromWikibase(cls, data, site): """Constructor to create an object from Wikibase's JSON output.""" globes = {} for k in site.globes(): globes[site.globes()[k]] = k globekey = data['globe'] if globekey: globe = globes.get(data['globe']) else: # Default to earth or should we use None here? globe = 'earth' return cls(data['latitude'], data['longitude'], data['altitude'], data['precision'], globe, site=site, entity=data['globe']) @property def precision(self): u""" Return the precision of the geo coordinate. The biggest error (in degrees) will be given by the longitudinal error; the same error in meters becomes larger (in degrees) further up north. We can thus ignore the latitudinal error. The longitudinal can be derived as follows: In small angle approximation (and thus in radians): M{Δλ ≈ Δpos / r_φ}, where r_φ is the radius of earth at the given latitude. Δλ is the error in longitude. M{r_φ = r cos φ}, where r is the radius of earth, φ the latitude Therefore:: precision = math.degrees(self._dim/(radius*math.cos(math.radians(self.lat)))) """ if not self._precision: radius = 6378137 # TODO: Support other globes self._precision = math.degrees( self._dim / (radius * math.cos(math.radians(self.lat)))) return self._precision def precisionToDim(self): """Convert precision from Wikibase to GeoData's dim.""" raise NotImplementedError class WbTime(object): """A Wikibase time representation.""" PRECISION = {'1000000000': 0, '100000000': 1, '10000000': 2, '1000000': 3, '100000': 4, '10000': 5, 'millenia': 6, 'century': 7, 'decade': 8, 'year': 9, 'month': 10, 'day': 11, 'hour': 12, 'minute': 13, 'second': 14 } FORMATSTR = '{0:+012d}-{1:02d}-{2:02d}T{3:02d}:{4:02d}:{5:02d}Z' def __init__(self, year=None, month=None, day=None, hour=None, minute=None, second=None, precision=None, before=0, after=0, timezone=0, calendarmodel=None, site=None): """ Create a new WbTime object. The precision can be set by the Wikibase int value (0-14) or by a human readable string, e.g., 'hour'. If no precision is given, it is set according to the given time units. """ if year is None: raise ValueError('no year given') self.precision = self.PRECISION['second'] if second is None: self.precision = self.PRECISION['minute'] second = 0 if minute is None: self.precision = self.PRECISION['hour'] minute = 0 if hour is None: self.precision = self.PRECISION['day'] hour = 0 if day is None: self.precision = self.PRECISION['month'] day = 1 if month is None: self.precision = self.PRECISION['year'] month = 1 self.year = long(year) self.month = month self.day = day self.hour = hour self.minute = minute self.second = second self.after = after self.before = before self.timezone = timezone if calendarmodel is None: if site is None: site = Site().data_repository() calendarmodel = site.calendarmodel() self.calendarmodel = calendarmodel # if precision is given it overwrites the autodetection above if precision is not None: if (isinstance(precision, int) and precision in self.PRECISION.values()): self.precision = precision elif precision in self.PRECISION: self.precision = self.PRECISION[precision] else: raise ValueError('Invalid precision: "%s"' % precision) @classmethod def fromTimestr(cls, datetimestr, precision=14, before=0, after=0, timezone=0, calendarmodel=None, site=None): match = re.match(r'([-+]?\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+)Z', datetimestr) if not match: raise ValueError(u"Invalid format: '%s'" % datetimestr) t = match.groups() return cls(long(t[0]), int(t[1]), int(t[2]), int(t[3]), int(t[4]), int(t[5]), precision, before, after, timezone, calendarmodel, site) def toTimestr(self): """ Convert the data to a UTC date/time string. @return: str """ return self.FORMATSTR.format(self.year, self.month, self.day, self.hour, self.minute, self.second) def toWikibase(self): """ Convert the data to a JSON object for the Wikibase API. @return: dict """ json = {'time': self.toTimestr(), 'precision': self.precision, 'after': self.after, 'before': self.before, 'timezone': self.timezone, 'calendarmodel': self.calendarmodel } return json @classmethod def fromWikibase(cls, ts): return cls.fromTimestr(ts[u'time'], ts[u'precision'], ts[u'before'], ts[u'after'], ts[u'timezone'], ts[u'calendarmodel']) def __str__(self): return json.dumps(self.toWikibase(), indent=4, sort_keys=True, separators=(',', ': ')) def __eq__(self, other): return self.__dict__ == other.__dict__ def __repr__(self): return u"WbTime(year=%(year)d, month=%(month)d, day=%(day)d, " \ u"hour=%(hour)d, minute=%(minute)d, second=%(second)d, " \ u"precision=%(precision)d, before=%(before)d, after=%(after)d, " \ u"timezone=%(timezone)d, calendarmodel='%(calendarmodel)s')" \ % self.__dict__ class WbQuantity(object): """A Wikibase quantity representation.""" def __init__(self, amount, unit=None, error=None): u""" Create a new WbQuantity object. @param amount: number representing this quantity @type amount: float @param unit: not used (only unit-less quantities are supported) @param error: the uncertainty of the amount (e.g. ±1) @type error: float, or tuple of two floats, where the first value is the upper error and the second is the lower error value. """ if amount is None: raise ValueError('no amount given') if unit is None: unit = '1' self.amount = amount self.unit = unit upperError = lowerError = 0 if isinstance(error, tuple): upperError, lowerError = error elif error is not None: upperError = lowerError = error self.upperBound = self.amount + upperError self.lowerBound = self.amount - lowerError def toWikibase(self): """Convert the data to a JSON object for the Wikibase API.""" json = {'amount': self.amount, 'upperBound': self.upperBound, 'lowerBound': self.lowerBound, 'unit': self.unit } return json @classmethod def fromWikibase(cls, wb): """ Create a WbQuanity from the JSON data given by the Wikibase API. @param wb: Wikibase JSON """ amount = eval(wb['amount']) upperBound = eval(wb['upperBound']) lowerBound = eval(wb['lowerBound']) error = (upperBound - amount, amount - lowerBound) return cls(amount, wb['unit'], error) def __str__(self): return json.dumps(self.toWikibase(), indent=4, sort_keys=True, separators=(',', ': ')) def __eq__(self, other): return self.__dict__ == other.__dict__ def __repr__(self): return (u"WbQuantity(amount=%(amount)s, upperBound=%(upperBound)s, " u"lowerBound=%(lowerBound)s, unit=%(unit)s)" % self.__dict__) _sites = {} _url_cache = {} # The code/fam pair for each URL def Site(code=None, fam=None, user=None, sysop=None, interface=None, url=None): """A factory method to obtain a Site object. Site objects are cached and reused by this method. By default rely on config settings. These defaults may all be overridden using the method parameters. @param code: language code (override config.mylang) @type code: string @param fam: family name or object (override config.family) @type fam: string or Family @param user: bot user name to use on this site (override config.usernames) @type user: unicode @param sysop: sysop user to use on this site (override config.sysopnames) @type sysop: unicode @param interface: site class or name of class in pywikibot.site (override config.site_interface) @type interface: subclass of L{pywikibot.site.BaseSite} or string @param url: Instead of code and fam, does try to get a Site based on the URL. Still requires that the family supporting that URL exists. @type url: string """ # Either code and fam or only url assert(not url or (not code and not fam)) _logger = "wiki" if url: if url in _url_cache: cached = _url_cache[url] if cached: code = cached[0] fam = cached[1] else: raise SiteDefinitionError("Unknown URL '{0}'.".format(url)) else: # Iterate through all families and look, which does apply to # the given URL for fam in config.family_files: try: family = pywikibot.family.Family.load(fam) code = family.from_url(url) if code: _url_cache[url] = (code, fam) break except Exception as e: pywikibot.warning('Error in Family(%s).from_url: %s' % (fam, e)) else: _url_cache[url] = None # TODO: As soon as AutoFamily is ready, try and use an # AutoFamily raise SiteDefinitionError("Unknown URL '{0}'.".format(url)) else: # Fallback to config defaults code = code or config.mylang fam = fam or config.family interface = interface or config.site_interface # config.usernames is initialised with a dict for each family name family_name = str(fam) if family_name in config.usernames: user = user or config.usernames[family_name].get(code) \ or config.usernames[family_name].get('*') sysop = sysop or config.sysopnames[family_name].get(code) \ or config.sysopnames[family_name].get('*') if not isinstance(interface, type): # If it isnt a class, assume it is a string try: tmp = __import__('pywikibot.site', fromlist=[interface]) interface = getattr(tmp, interface) except ImportError: raise ValueError("Invalid interface name '%(interface)s'" % locals()) if not issubclass(interface, pywikibot.site.BaseSite): warning('Site called with interface=%s' % interface.__name__) user = pywikibot.tools.normalize_username(user) key = '%s:%s:%s:%s' % (interface.__name__, fam, code, user) if key not in _sites or not isinstance(_sites[key], interface): _sites[key] = interface(code=code, fam=fam, user=user, sysop=sysop) debug(u"Instantiated %s object '%s'" % (interface.__name__, _sites[key]), _logger) if _sites[key].code != code: warn('Site %s instantiated using different code "%s"' % (_sites[key], code), UserWarning, 2) return _sites[key] # alias for backwards-compability getSite = pywikibot.tools.redirect_func(Site, old_name='getSite') from .page import ( Page, FilePage, Category, Link, User, ItemPage, PropertyPage, Claim, ) from .page import html2unicode, url2unicode, unicode2html link_regex = re.compile(r'\[\[(?P<title>[^\]|[<>{}]*)(\|.*?)?\]\]') @pywikibot.tools.deprecated("comment parameter for page saving method") def setAction(s): """Set a summary to use for changed page submissions.""" config.default_edit_summary = s def showDiff(oldtext, newtext, context=0): """ Output a string showing the differences between oldtext and newtext. The differences are highlighted (only on compatible systems) to show which changes were made. """ PatchManager(oldtext, newtext, context=context).print_hunks() # Throttle and thread handling stopped = False def stopme(): """Drop this process from the throttle log, after pending threads finish. Can be called manually if desired, but if not, will be called automatically at Python exit. """ global stopped _logger = "wiki" if not stopped: debug(u"stopme() called", _logger) def remaining(): remainingPages = page_put_queue.qsize() - 1 # -1 because we added a None element to stop the queue remainingSeconds = datetime.timedelta( seconds=(remainingPages * config.put_throttle)) return (remainingPages, remainingSeconds) page_put_queue.put((None, [], {})) stopped = True if page_put_queue.qsize() > 1: num, sec = remaining() format_values = dict(num=num, sec=sec) output(u'\03{lightblue}' u'Waiting for %(num)i pages to be put. ' u'Estimated time remaining: %(sec)s' u'\03{default}' % format_values) while(_putthread.isAlive()): try: _putthread.join(1) except KeyboardInterrupt: if input_yn('There are %i pages remaining in the queue. ' 'Estimated time remaining: %s\nReally exit?' % remaining(), default=False, automatic_quit=False): return # only need one drop() call because all throttles use the same global pid try: list(_sites.values())[0].throttle.drop() log(u"Dropped throttle(s).") except IndexError: pass import atexit atexit.register(stopme) # Create a separate thread for asynchronous page saves (and other requests) def async_manager(): """Daemon; take requests from the queue and execute them in background.""" while True: (request, args, kwargs) = page_put_queue.get() if request is None: break request(*args, **kwargs) page_put_queue.task_done() def async_request(request, *args, **kwargs): """Put a request on the queue, and start the daemon if necessary.""" if not _putthread.isAlive(): try: page_put_queue.mutex.acquire() try: _putthread.start() except (AssertionError, RuntimeError): pass finally: page_put_queue.mutex.release() page_put_queue.put((request, args, kwargs)) # queue to hold pending requests page_put_queue = Queue(config.max_queue_size) # set up the background thread _putthread = threading.Thread(target=async_manager) # identification for debugging purposes _putthread.setName('Put-Thread') _putthread.setDaemon(True) wrapper = pywikibot.tools.ModuleDeprecationWrapper(__name__) wrapper._add_deprecated_attr('ImagePage', FilePage) wrapper._add_deprecated_attr( 'PageNotFound', pywikibot.exceptions.DeprecatedPageNotFoundError, warning_message=('{0}.{1} is deprecated, and no longer ' 'used by pywikibot; use http.fetch() instead.')) wrapper._add_deprecated_attr( 'UserActionRefuse', pywikibot.exceptions._EmailUserError, warning_message='UserActionRefuse is deprecated; ' 'use UserRightsError and/or NotEmailableError')
hperala/kontuwikibot
pywikibot/__init__.py
Python
mit
26,829
export default function applyLocationOffset(rect, location, isOffsetBody) { var top = rect.top; var left = rect.left; if (isOffsetBody) { left = 0; top = 0; } return { top: top + location.top, left: left + location.left, height: rect.height, width: rect.width }; } //# sourceMappingURL=apply-location-offset.js.map
antpost/antpost-client
node_modules/@progress/kendo-popup-common/dist/es/apply-location-offset.js
JavaScript
mit
390
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* | ------------------------------------------------------------------- | DATABASE CONNECTIVITY SETTINGS | ------------------------------------------------------------------- | This file will contain the settings needed to access your database. | | For complete instructions please consult the 'Database Connection' | page of the User Guide. | | ------------------------------------------------------------------- | EXPLANATION OF VARIABLES | ------------------------------------------------------------------- | | ['dsn'] The full DSN string describe a connection to the database. | ['hostname'] The hostname of your database server. | ['username'] The username used to connect to the database | ['password'] The password used to connect to the database | ['database'] The name of the database you want to connect to | ['dbdriver'] The database driver. e.g.: mysqli. | Currently supported: | cubrid, ibase, mssql, mysql, mysqli, oci8, | odbc, pdo, postgre, sqlite, sqlite3, sqlsrv | ['dbprefix'] You can add an optional prefix, which will be added | to the table name when using the Query Builder class | ['pconnect'] TRUE/FALSE - Whether to use a persistent connection | ['db_debug'] TRUE/FALSE - Whether database errors should be displayed. | ['cache_on'] TRUE/FALSE - Enables/disables query caching | ['cachedir'] The path to the folder where cache files should be stored | ['char_set'] The character set used in communicating with the database | ['dbcollat'] The character collation used in communicating with the database | NOTE: For MySQL and MySQLi databases, this setting is only used | as a backup if your server is running PHP < 5.2.3 or MySQL < 5.0.7 | (and in table creation queries made with DB Forge). | There is an incompatibility in PHP with mysql_real_escape_string() which | can make your site vulnerable to SQL injection if you are using a | multi-byte character set and are running versions lower than these. | Sites using Latin-1 or UTF-8 database character set and collation are unaffected. | ['swap_pre'] A default table prefix that should be swapped with the dbprefix | ['encrypt'] Whether or not to use an encrypted connection. | | 'mysql' (deprecated), 'sqlsrv' and 'pdo/sqlsrv' drivers accept TRUE/FALSE | 'mysqli' and 'pdo/mysql' drivers accept an array with the following options: | | 'ssl_key' - Path to the private key file | 'ssl_cert' - Path to the public key certificate file | 'ssl_ca' - Path to the certificate authority file | 'ssl_capath' - Path to a directory containing trusted CA certificats in PEM format | 'ssl_cipher' - List of *allowed* ciphers to be used for the encryption, separated by colons (':') | 'ssl_verify' - TRUE/FALSE; Whether verify the server certificate or not ('mysqli' only) | | ['compress'] Whether or not to use client compression (MySQL only) | ['stricton'] TRUE/FALSE - forces 'Strict Mode' connections | - good for ensuring strict SQL while developing | ['ssl_options'] Used to set various SSL options that can be used when making SSL connections. | ['failover'] array - A array with 0 or more data for connections if the main should fail. | ['save_queries'] TRUE/FALSE - Whether to "save" all executed queries. | NOTE: Disabling this will also effectively disable both | $this->db->last_query() and profiling of DB queries. | When you run a query, with this setting set to TRUE (default), | CodeIgniter will store the SQL statement for debugging purposes. | However, this may cause high memory usage, especially if you run | a lot of SQL queries ... disable this to avoid that problem. | | The $active_group variable lets you choose which connection group to | make active. By default there is only one group (the 'default' group). | | The $query_builder variables lets you determine whether or not to load | the query builder class. */ $active_group = 'default'; $query_builder = TRUE; $db['default'] = array( 'dsn' => '', 'hostname' => 'YOUT_HOST', 'username' => 'YOUR_USERNAME', 'password' => 'YOUR_PASSWORD', 'database' => 'YOUR_DATABASE_NAME', 'dbdriver' => 'mysqli', 'dbprefix' => '', 'pconnect' => FALSE, 'db_debug' => (ENVIRONMENT !== 'production'), 'cache_on' => FALSE, 'cachedir' => '', 'char_set' => 'utf8', 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'encrypt' => FALSE, 'compress' => FALSE, 'stricton' => FALSE, 'failover' => array(), 'save_queries' => TRUE );
pablojotaguardiola/ParseQL-Swift-To-MySQL
PHP/parseql/application/config/database.php
PHP
mit
4,558
KB.component('task-move-position', function (containerElement, options) { function getSelectedValue(id) { var element = KB.dom(document).find('#' + id); if (element) { return parseInt(element.options[element.selectedIndex].value); } return null; } function getSwimlaneId() { var swimlaneId = getSelectedValue('form-swimlanes'); return swimlaneId === null ? options.board[0].id : swimlaneId; } function getColumnId() { var columnId = getSelectedValue('form-columns'); return columnId === null ? options.board[0].columns[0].id : columnId; } function getPosition() { var position = getSelectedValue('form-position'); return position === null ? 1 : position; } function getPositionChoice() { var element = KB.find('input[name=positionChoice]:checked'); if (element) { return element.value; } return 'before'; } function onSwimlaneChanged() { var columnSelect = KB.dom(document).find('#form-columns'); KB.dom(columnSelect).replace(buildColumnSelect()); var taskSection = KB.dom(document).find('#form-tasks'); KB.dom(taskSection).replace(buildTasks()); } function onColumnChanged() { var taskSection = KB.dom(document).find('#form-tasks'); KB.dom(taskSection).replace(buildTasks()); } function onError(message) { KB.trigger('modal.stop'); KB.find('#message-container') .replace(KB.dom('div') .attr('id', 'message-container') .attr('class', 'alert alert-error') .text(message) .build() ); } function onSubmit() { var position = getPosition(); var positionChoice = getPositionChoice(); if (positionChoice === 'after') { position++; } KB.find('#message-container').replace(KB.dom('div').attr('id', 'message-container').build()); KB.http.postJson(options.saveUrl, { "column_id": getColumnId(), "swimlane_id": getSwimlaneId(), "position": position }).success(function () { window.location.reload(true); }).error(function (response) { if (response) { onError(response.message); } }); } function buildSwimlaneSelect() { var swimlanes = []; options.board.forEach(function(swimlane) { swimlanes.push({'value': swimlane.id, 'text': swimlane.name}); }); return KB.dom('select') .attr('id', 'form-swimlanes') .change(onSwimlaneChanged) .for('option', swimlanes) .build(); } function buildColumnSelect() { var columns = []; var swimlaneId = getSwimlaneId(); options.board.forEach(function(swimlane) { if (swimlaneId === swimlane.id) { swimlane.columns.forEach(function(column) { columns.push({'value': column.id, 'text': column.title}); }); } }); return KB.dom('select') .attr('id', 'form-columns') .change(onColumnChanged) .for('option', columns) .build(); } function buildTasks() { var tasks = []; var swimlaneId = getSwimlaneId(); var columnId = getColumnId(); var container = KB.dom('div').attr('id', 'form-tasks'); options.board.forEach(function (swimlane) { if (swimlaneId === swimlane.id) { swimlane.columns.forEach(function (column) { if (columnId === column.id) { column.tasks.forEach(function (task) { tasks.push({'value': task.position, 'text': '#' + task.id + ' - ' + task.title}); }); } }); } }); if (tasks.length > 0) { container .add(KB.html.label(options.positionLabel, 'form-position')) .add(KB.dom('select').attr('id', 'form-position').for('option', tasks).build()) .add(KB.html.radio(options.beforeLabel, 'positionChoice', 'before')) .add(KB.html.radio(options.afterLabel, 'positionChoice', 'after')) ; } return container.build(); } this.render = function () { KB.on('modal.submit', onSubmit); var form = KB.dom('div') .on('submit', onSubmit) .add(KB.dom('div').attr('id', 'message-container').build()) .add(KB.html.label(options.swimlaneLabel, 'form-swimlanes')) .add(buildSwimlaneSelect()) .add(KB.html.label(options.columnLabel, 'form-columns')) .add(buildColumnSelect()) .add(buildTasks()) .build(); containerElement.appendChild(form); }; });
lianguan/kanboard
assets/js/components/task-move-position.js
JavaScript
mit
5,050
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Text; using EOLib.IO.Pub; using EOLib.IO.Services; using NUnit.Framework; namespace EOLib.IO.Test.Pub { [TestFixture, ExcludeFromCodeCoverage] public class EIFRecordTest { [Test] public void EIFRecord_GetGlobalPropertyID_GetsRecordID() { const int expected = 44; var rec = new EIFRecord {ID = expected}; var actual = rec.Get<int>(PubRecordProperty.GlobalID); Assert.AreEqual(expected, actual); } [Test] public void EIFRecord_GetGlobalPropertyName_GetsRecordName() { const string expected = "some name"; var rec = new EIFRecord { Name = expected }; var actual = rec.Get<string>(PubRecordProperty.GlobalName); Assert.AreEqual(expected, actual); } [Test] public void EIFRecord_GetItemPropertiesComprehensive_NoException() { var itemProperties = Enum.GetNames(typeof (PubRecordProperty)) .Where(x => x.StartsWith("Item")) .Select(x => (PubRecordProperty) Enum.Parse(typeof (PubRecordProperty), x)) .ToArray(); Assert.AreNotEqual(0, itemProperties.Length); var record = new EIFRecord(); foreach (var property in itemProperties) { var dummy = record.Get<object>(property); Assert.IsNotNull(dummy); } } [Test] public void EIFRecord_GetNPCProperty_ThrowsArgumentOutOfRangeException() { const PubRecordProperty invalidProperty = PubRecordProperty.NPCAccuracy; var record = new EIFRecord(); Assert.Throws<ArgumentOutOfRangeException>(() => record.Get<object>(invalidProperty)); } [Test] public void EIFRecord_GetSpellProperty_ThrowsArgumentOutOfRangeException() { const PubRecordProperty invalidProperty = PubRecordProperty.SpellAccuracy; var record = new EIFRecord(); Assert.Throws<ArgumentOutOfRangeException>(() => record.Get<object>(invalidProperty)); } [Test] public void EIFRecord_GetClassProperty_ThrowsArgumentOutOfRangeException() { const PubRecordProperty invalidProperty = PubRecordProperty.ClassAgi; var record = new EIFRecord(); Assert.Throws<ArgumentOutOfRangeException>(() => record.Get<object>(invalidProperty)); } [Test] public void EIFRecord_InvalidPropertyReturnType_ThrowsInvalidCastException() { var rec = new EIFRecord {Name = ""}; Assert.Throws<InvalidCastException>(() => rec.Get<int>(PubRecordProperty.GlobalName)); } [Test] public void EIFRecord_SerializeToByteArray_WritesExpectedFormat() { var numberEncoderService = new NumberEncoderService(); var record = CreateRecordWithSomeGoodTestData(); var actualBytes = record.SerializeToByteArray(numberEncoderService); var expectedBytes = GetExpectedBytes(record, numberEncoderService); CollectionAssert.AreEqual(expectedBytes, actualBytes); } [Test] public void EIFRecord_DeserializeFromByteArray_HasCorrectData() { var numberEncoderService = new NumberEncoderService(); var sourceRecord = CreateRecordWithSomeGoodTestData(); var sourceRecordBytes = GetExpectedBytesWithoutName(sourceRecord, numberEncoderService); var record = new EIFRecord { ID = sourceRecord.ID, Name = sourceRecord.Name }; record.DeserializeFromByteArray(sourceRecordBytes, numberEncoderService); var properties = record.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); Assert.IsTrue(properties.Length > 0); foreach (var property in properties) { var expectedValue = property.GetValue(sourceRecord); var actualValue = property.GetValue(record); Assert.AreEqual(expectedValue, actualValue, "Property: {0}", property.Name); } } [Test] public void EIFRecord_DeserializeFromByteArray_InvalidArrayLength_ThrowsException() { var record = new EIFRecord(); Assert.Throws<ArgumentOutOfRangeException>(() => record.DeserializeFromByteArray(new byte[] { 1, 2, 3 }, new NumberEncoderService())); } [Test] public void EIFRecord_GunOverride_ConvertsItemSubTypeToRanged() { var record = new EIFRecord {ID = 365, Name = "Gun", SubType = ItemSubType.Arrows}; record.DeserializeFromByteArray(Enumerable.Repeat((byte)128, EIFRecord.DATA_SIZE).ToArray(), new NumberEncoderService()); Assert.AreEqual(ItemSubType.Ranged, record.SubType); } [Test] public void EIFRecord_SharedValueSet1_HaveSameValue() { var properties = new[] { "ScrollMap", "DollGraphic", "ExpReward", "HairColor", "Effect", "Key" }; var record = new EIFRecord(); var value = new Random().Next(100); foreach (var prop in properties) { record.GetType().GetProperty(prop, BindingFlags.Instance | BindingFlags.Public) .SetValue(record, value); Assert.AreEqual(value, record.ScrollMap); Assert.AreEqual(value, record.DollGraphic); Assert.AreEqual(value, record.ExpReward); Assert.AreEqual(value, record.HairColor); Assert.AreEqual(value, record.Effect); Assert.AreEqual(value, record.Key); value++; } } [Test] public void EIFRecord_SharedValueSet2_HaveSameValue() { var properties = new[] { "Gender", "ScrollX" }; var record = new EIFRecord(); var value = new Random().Next(100); foreach (var prop in properties) { record.GetType().GetProperty(prop, BindingFlags.Instance | BindingFlags.Public) .SetValue(record, (byte)value); Assert.AreEqual(value, record.Gender); Assert.AreEqual(value, record.ScrollX); value++; } } [Test] public void EIFRecord_SharedValueSet3_HaveSameValue() { var properties = new[] { "ScrollY", "DualWieldDollGraphic" }; var record = new EIFRecord(); var value = new Random().Next(100); foreach (var prop in properties) { record.GetType().GetProperty(prop, BindingFlags.Instance | BindingFlags.Public) .SetValue(record, (byte)value); Assert.AreEqual(value, record.ScrollY); Assert.AreEqual(value, record.DualWieldDollGraphic); value++; } } private static EIFRecord CreateRecordWithSomeGoodTestData() { return new EIFRecord { ID = 1, Name = "TestName", Graphic = 123, Type = ItemType.Bracer, SubType = ItemSubType.Ranged, Special = ItemSpecial.Unique, HP = 456, TP = 654, MinDam = 33, MaxDam = 66, Accuracy = 100, Evade = 200, Armor = 300, Str = 40, Int = 50, Wis = 60, Agi = 70, Con = 80, Cha = 90, Light = 3, Dark = 6, Earth = 9, Air = 12, Water = 15, Fire = 18, ScrollMap = 33, Gender = 44, ScrollY = 55, LevelReq = 66, ClassReq = 77, StrReq = 88, IntReq = 99, WisReq = 30, AgiReq = 20, ConReq = 10, ChaReq = 5, Weight = 200, Size = ItemSize.Size2x3 }; } private static byte[] GetExpectedBytes(EIFRecord rec, INumberEncoderService nes) { var ret = new List<byte>(); ret.AddRange(nes.EncodeNumber(rec.Name.Length, 1)); ret.AddRange(Encoding.ASCII.GetBytes(rec.Name)); ret.AddRange(GetExpectedBytesWithoutName(rec, nes)); return ret.ToArray(); } private static byte[] GetExpectedBytesWithoutName(EIFRecord rec, INumberEncoderService nes) { var ret = new List<byte>(); ret.AddRange(nes.EncodeNumber(rec.Graphic, 2)); ret.AddRange(nes.EncodeNumber((byte)rec.Type, 1)); ret.AddRange(nes.EncodeNumber((byte)rec.SubType, 1)); ret.AddRange(nes.EncodeNumber((byte)rec.Special, 1)); ret.AddRange(nes.EncodeNumber(rec.HP, 2)); ret.AddRange(nes.EncodeNumber(rec.TP, 2)); ret.AddRange(nes.EncodeNumber(rec.MinDam, 2)); ret.AddRange(nes.EncodeNumber(rec.MaxDam, 2)); ret.AddRange(nes.EncodeNumber(rec.Accuracy, 2)); ret.AddRange(nes.EncodeNumber(rec.Evade, 2)); ret.AddRange(nes.EncodeNumber(rec.Armor, 2)); ret.AddRange(Enumerable.Repeat((byte)254, 1)); ret.AddRange(nes.EncodeNumber(rec.Str, 1)); ret.AddRange(nes.EncodeNumber(rec.Int, 1)); ret.AddRange(nes.EncodeNumber(rec.Wis, 1)); ret.AddRange(nes.EncodeNumber(rec.Agi, 1)); ret.AddRange(nes.EncodeNumber(rec.Con, 1)); ret.AddRange(nes.EncodeNumber(rec.Cha, 1)); ret.AddRange(nes.EncodeNumber(rec.Light, 1)); ret.AddRange(nes.EncodeNumber(rec.Dark, 1)); ret.AddRange(nes.EncodeNumber(rec.Earth, 1)); ret.AddRange(nes.EncodeNumber(rec.Air, 1)); ret.AddRange(nes.EncodeNumber(rec.Water, 1)); ret.AddRange(nes.EncodeNumber(rec.Fire, 1)); ret.AddRange(nes.EncodeNumber(rec.ScrollMap, 3)); ret.AddRange(nes.EncodeNumber(rec.ScrollX, 1)); ret.AddRange(nes.EncodeNumber(rec.ScrollY, 1)); ret.AddRange(nes.EncodeNumber(rec.LevelReq, 2)); ret.AddRange(nes.EncodeNumber(rec.ClassReq, 2)); ret.AddRange(nes.EncodeNumber(rec.StrReq, 2)); ret.AddRange(nes.EncodeNumber(rec.IntReq, 2)); ret.AddRange(nes.EncodeNumber(rec.WisReq, 2)); ret.AddRange(nes.EncodeNumber(rec.AgiReq, 2)); ret.AddRange(nes.EncodeNumber(rec.ConReq, 2)); ret.AddRange(nes.EncodeNumber(rec.ChaReq, 2)); ret.AddRange(Enumerable.Repeat((byte)254, 2)); ret.AddRange(nes.EncodeNumber(rec.Weight, 1)); ret.AddRange(Enumerable.Repeat((byte)254, 1)); ret.AddRange(nes.EncodeNumber((byte)rec.Size, 1)); return ret.ToArray(); } } }
ethanmoffat/EndlessClient
EOLib.IO.Test/Pub/EIFRecordTest.cs
C#
mit
11,477
# import libraries import urllib.request from feedgen.feed import FeedGenerator from post_parser import post_title, post_author, post_time, post_files_num from misc import is_number # info baseurl = 'http://phya.snu.ac.kr/xe/underbbs/' url ='http://phya.snu.ac.kr/xe/index.php?mid=underbbs&category=372' # notices + general f = open('srl_notices.txt','r') num_notices = f.read().split(',') f.close() g = open('srl_general.txt','r') num_general = g.read().split(',') g.close() g = open('srl_general.txt','a') response = urllib.request.urlopen(url) data = response.read() text = data.decode('utf-8') count_new = 0 srl_arr_general = [] text_splitted = text.split('document_srl=') for i in range(1,len(text_splitted)): srl = text_splitted[i].split('">')[0].split('#comment')[0] if(is_number(srl)): if(srl not in num_notices and srl not in srl_arr_general): # second statement : to prevent duplication srl_arr_general.append(srl) if(srl not in num_general): count_new += 1 g.write(',' + srl) print('New post found : ' + srl) g.close() if(count_new != 0): print('Started generating feed...') # make FeedGenerator fg = FeedGenerator() fg.id('asdf') fg.title('SNU Physics Board RSS feed - general') fg.author({'name':'Seungwon Park','email':'yyyyy at snu dot ac dot kr'}) fg.link(href='asdf') fg.subtitle('SNU Physics Board RSS - general') fg.language('ko') for srl in srl_arr_general: print('Parsing post #' + srl + '...') fe = fg.add_entry() fe.id(baseurl + srl) fe.title(post_title(srl)) fe.author({'name':post_author(srl),'email':'unknown'}) fe.link(href = baseurl + srl) atomfeed = fg.atom_str(pretty=True) fg.atom_file('general.xml') print('Added ' + str(count_new) + ' posts to feed.') else: print('Posts are up-to-date.')
seungwonpark/SNU_physics_board_rss
update_general.py
Python
mit
1,781
const AES = require('./aesjs'); function encrypt(text, key) { key = new TextEncoder().encode(key); const textBytes = AES.utils.utf8.toBytes(text); const aesCtr = new AES.ModeOfOperation.ctr(key); const encryptedBytes = aesCtr.encrypt(textBytes); return AES.utils.hex.fromBytes(encryptedBytes); } function decrypt(encryptedHex, key) { key = new TextEncoder().encode(key); const encryptedBytes = AES.utils.hex.toBytes(encryptedHex); const aesCtr = new AES.ModeOfOperation.ctr(key); const decryptedBytes = aesCtr.decrypt(encryptedBytes); return AES.utils.utf8.fromBytes(decryptedBytes); } module.exports = { encrypt, decrypt, };
cheminfo-js/visualizer-helper
util/aes.js
JavaScript
mit
653
#!/usr/bin/env python __version__= "$Version: $" __rcsid__="$Id: $" import matplotlib #matplotlib.use('WX') from wx import MilliSleep from wx import SplashScreen, SPLASH_CENTRE_ON_SCREEN, SPLASH_TIMEOUT import os import sys import warnings from . import zpickle from .utils import * from .dialogs.waxy import * from .dialogs import * from .run_sim import * import threading import pylab gray=pylab.cm.gray from matplotlib.backends.backend_wxagg import FigureCanvasWx as FigureCanvas from matplotlib.backends.backend_wx import FigureManager from matplotlib.figure import Figure from matplotlib.axes import Subplot class SimThread(threading.Thread): def __init__(self,params,parent): self.params=params self.parent=parent threading.Thread.__init__(self); def run(self): run_sim(self.params,self.parent) def subplot(*args): import pylab if len(args)==1: return pylab.subplot(args[0]) elif len(args)==3: return pylab.subplot(args[0],args[1],args[2]) elif len(args)==4: r=args[2] c=args[3] return pylab.subplot(args[0],args[1],c+(r-1)*args[1]); else: raise ValueError("invalid number of arguments") class MainFrame(Frame): def __init__(self,parent=None,title='',direction='H', size=(750,750),lfname=None,params=None): self.fig=None # turn off security warning on tmpnam. why is it here? warnings.filterwarnings('ignore') fname=os.tempnam() warnings.resetwarnings() self.base_dir=os.path.dirname(__file__) if not self.base_dir: self.base_dir='.' self.tmpfile=fname+"_plasticity.dat" self.modified=False self.running=False self.stopping=False self.quitting=False self.plot_first=False if not params: self.params=default_params() else: self.params=params for p in self.params['pattern_input']: if not os.path.exists(p['filename']): p['filename']=self.base_dir+"/"+p['filename'] if lfname: if not self.__load_sim__(lfname): self.plot_first=True Frame.__init__(self,parent,title,direction,size) def Body(self): self.CreateMenu() self.CenterOnScreen() self.ResetTitle() fname=self.base_dir+"/images/plasticity_small_icon.ico" self.SetIcon(fname) self.fig = Figure(figsize=(7,5),dpi=100) self.canvas = FigureCanvas(self, -1, self.fig) self.figmgr = FigureManager(self.canvas, 1, self) self.axes = [self.fig.add_subplot(221), self.fig.add_subplot(222), self.fig.add_subplot(223), self.fig.add_subplot(224)] if self.plot_first: sim=zpickle.load(self.tmpfile) sim['params']['display']=True self.Plot(sim) def Stopping(self): return self.stopping def Yield(self): wx.Yield() def ResetTitle(self): (root,sfname)=os.path.split(self.params['save_sim_file']) if self.modified: s=' (*)' else: s='' title='Plasticity: %s%s' % (sfname,s) self.SetTitle(title) def Plot(self,sim): if not sim['params']['display']: return if sim['params']['display_module']: try: module=__import__(sim['params']['display_module'],fromlist=['UserPlot']) except ImportError: sim['params']['display']=False dlg = MessageDialog(self, "Error","Error in Import: %s. Turning display off" % sim['params']['display_module'], icon='error') dlg.ShowModal() dlg.Destroy() return try: module.UserPlot(self,sim) return except ValueError: sim['params']['display']=False dlg = MessageDialog(self, "Error","Error in display. Turning display off", icon='error') dlg.ShowModal() dlg.Destroy() return try: im=weights2image(sim['params'],sim['weights']) self.axes[0].hold(False) self.axes[0].set_axis_bgcolor('k') self.axes[0].pcolor(im,cmap=gray,edgecolors='k') self.axes[0].set_aspect('equal') num_moments=sim['moments_mat'].shape[0] self.axes[1].hold(False) num_neurons=sim['moments_mat'].shape[1] for k in range(num_neurons): for i in range(num_moments): self.axes[1].plot(sim['moments_mat'][i,k,:],'-o') self.axes[1].hold(True) self.axes[2].hold(False) response_mat=sim['response_mat'] response_var_list=sim['response_var_list'] styles=['b-o','g-o'] for i,r in enumerate(response_var_list[-1]): x=r[1] y=r[2] self.axes[2].plot(x,y,styles[i]) self.axes[2].hold(True) self.axes[3].hold(False) styles=['b-o','g-o'] for i,r in enumerate(response_mat): self.axes[3].plot(r,styles[i]) self.axes[3].hold(True) self.canvas.draw() self.canvas.gui_repaint() except ValueError: sim['params']['display']=False dlg = MessageDialog(self, "Error","Error in display. Turning display off", icon='error') dlg.ShowModal() dlg.Destroy() def Run_Pause(self,event): if not self.running: # pylab.close() self.params['tmpfile']=self.tmpfile if os.path.exists(self.tmpfile): self.params['continue']=1 self.modified=True self.ResetTitle() self.running=True ## d={} ## d['params']=self.params ## zpickle.save(d,'plasticity_tmpparams.dat') ## cmd='./run_sim.py --paramfile plasticity_tmpparams.dat --from_gui 1' ## os.system(cmd) self.stopping=False run_sim(self.params,self) self.params['load_sim_file']=self.tmpfile self.running=False if self.quitting: self.Quit() else: self.stopping=True def __load_sim__(self,lfname): sim=zpickle.load(lfname) params=sim['params'] params['save_sim_file']=self.params['save_sim_file'] params['load_sim_file']='' params['continue']=False try: params['initial_weights']=sim['weights'] params['initial_moments']=sim['moments'] except KeyError: self.params=params return 1 params['load_sim_file']=self.tmpfile params['continue']=True sim['params']=params self.params=params zpickle.save(sim,self.tmpfile) return 0 def Reset_Simulation(self,event=None): if not os.path.exists(self.tmpfile): return self.canvas.Show(False) if self.modified: (root,sfname)=os.path.split(self.params['save_sim_file']) dlg=MessageDialog(self, text="Do you want to save the changes you made to %s?" % sfname, title="Reset", ok=0, yes_no=1,cancel=1) result=dlg.ShowModal() dlg.Destroy() if result == 'cancel': self.canvas.Show(True) return elif result == 'yes': filename=self.Save_Simulation() if not filename: # cancelled the save self.canvas.Show(True) return self.params['continue']=False self.params['load_sim_file']='' self.params['initial_weights']=[] self.params['initial_moments']=[] for a in self.axes: a.cla() self.canvas.draw() self.canvas.Show(True) def Restart(self,event=None): if not os.path.exists(self.tmpfile): return self.canvas.Show(False) if self.modified: (root,sfname)=os.path.split(self.params['save_sim_file']) dlg=MessageDialog(self, text="Do you want to save the changes you made to %s?" % sfname, title="Restart", ok=0, yes_no=1,cancel=1) result=dlg.ShowModal() dlg.Destroy() if result == 'cancel': self.canvas.Show(True) return elif result == 'yes': filename=self.Save_Simulation() if not filename: # cancelled the save self.canvas.Show(True) return self.__load_sim__(self.tmpfile) self.params['continue']=False self.canvas.Show(True) def Load_Simulation(self,event=None): self.canvas.Show(False) if self.modified: (root,sfname)=os.path.split(self.params['save_sim_file']) dlg=MessageDialog(self, text="Do you want to save the changes you made to %s?" % sfname, title="Load Simulation", ok=0, yes_no=1,cancel=1) result=dlg.ShowModal() dlg.Destroy() if result == 'cancel': pass elif result == 'yes': self.Save_Simulation() lfname='' dlg = FileDialog(self, "Load Simulation",default_dir=os.getcwd()+"/sims", wildcard='DAT Files|*.dat|All Files|*.*') result = dlg.ShowModal() if result == 'ok': lfname = dlg.GetPaths()[0] dlg.Destroy() if not lfname: self.canvas.Show(True) return self.__load_sim__(lfname) sim=zpickle.load(self.tmpfile) self.Plot(sim) self.canvas.Show(True) def Save_Simulation(self,event=None): if not self.modified: return sfname=self.params['save_sim_file'] def_sfname=default_params()['save_sim_file'] if sfname==def_sfname: filename=self.Save_Simulation_As() else: filename=sfname d=zpickle.load(self.tmpfile) d['params']=self.params zpickle.save(d,sfname) self.modified=False self.ResetTitle() return filename def Save_Simulation_As(self,event=None): self.canvas.Show(False) dlg = FileDialog(self, "Save Simulation As...",default_dir=os.getcwd()+"/sims/", wildcard='DAT Files|*.dat|All Files|*.*',save=1) result = dlg.ShowModal() if result == 'ok': filename = dlg.GetPaths()[0] else: filename=None dlg.Destroy() if filename: d=zpickle.load(self.tmpfile) self.params['save_sim_file']=filename d['params']=self.params zpickle.save(d,filename) self.modified=False self.ResetTitle() self.canvas.Show(True) return filename def Set_Simulation_Parameters(self,event): self.canvas.Show(False) set_simulation_parameters(self.params,self) self.canvas.Show(True) def Set_Input_Parameters(self,event): self.canvas.Show(False) set_input_parameters(self.params,self) self.canvas.Show(True) def Set_Output_Parameters(self,event): self.canvas.Show(False) set_output_parameters(self.params,self) self.canvas.Show(True) def Set_Weight_Parameters(self,event): self.canvas.Show(False) set_weight_parameters(self.params,self) self.canvas.Show(True) def Save_Parameters_As(self,event): save_parameters_as(self.params,self) def Set_Parameter_Structure(self,event): set_parameter_structure(self.params,self) def Load_Parameters(self,event): p=load_parameters(None,self) if p: self.params=p def CreateMenu(self): menubar = MenuBar() menu = Menu(self) menu.Append("L&oad State", self.Load_Simulation, "Load a Complete Simulation",hotkey="Ctrl+O") menu.Append("Load &Parameters", self.Load_Parameters, "Load Simulation Parameters") menu.AppendSeparator() menu.Append("Save Parameters As...", self.Save_Parameters_As, "Save Simulation Parameters") menu.Append("Save State As...", self.Save_Simulation_As, "Save a Complete Simulation") menu.Append("Save State", self.Save_Simulation, "Save a Complete Simulation",hotkey="Ctrl+S") menu.AppendSeparator() menu.Append("&Run/Pause", self.Run_Pause, "Run a Simulation",hotkey="Ctrl+P") menu.Append("Restart from Current State", self.Restart) menu.Append("Reset Simulation", self.Reset_Simulation,hotkey="Ctrl+R") menu.AppendSeparator() menu.Append("Export Figure...", self.Export, "Export the Screen") menu.Append("&Quit", self.Quit, "Quit",hotkey="Ctrl+Q") menubar.Append(menu, "&File") menu = Menu(self) menu.Append("&Simulation Parameters", self.Set_Simulation_Parameters) menu.Append("&Input Parameters", self.Set_Input_Parameters) menu.Append("&Output Neuron Parameters", self.Set_Output_Parameters) menu.Append("&Weight Parameters", self.Set_Weight_Parameters) menu.AppendSeparator() menu.Append("&Display", self.Display) menu.Append("Make &New Input Files", self.Nop) menu.Append("Parameter Structure", self.Set_Parameter_Structure) menubar.Append(menu, "&Edit") menu=Menu(self) menu.Append("&Help", self.Nop) menu.Append("&About", self.About) menubar.Append(menu, "&Help") self.SetMenuBar(menubar) self.CreateStatusBar() def Display(self,event=None): self.canvas.Show(False) dlg = FileDialog(self, "Choose Display Module",default_dir=os.getcwd()+"/", wildcard='Python Plot Files|plot*.py|All Files|*.*') result = dlg.ShowModal() dlg.Destroy() if result == 'ok': lfname = dlg.GetPaths()[0] modulename=os.path.splitext(os.path.split(lfname)[-1])[0] self.params['display_module']=modulename if os.path.exists(self.tmpfile): sim=zpickle.load(self.tmpfile) self.Plot(sim) self.canvas.Show(True) def About(self,event): win=AboutWindow() win.Show() def Nop(self,event): self.canvas.Show(False) dlg = MessageDialog(self, "Error","Function Not Implemented",icon='error') dlg.ShowModal() dlg.Destroy() self.canvas.Show(True) def Export(self,event=None): export_fig(self) def Quit(self,event=None): if self.running: self.quitting=True self.stopping=True return self.canvas.Show(False) if self.modified: (root,sfname)=os.path.split(self.params['save_sim_file']) dlg=MessageDialog(self, text="Do you want to save the changes you made to %s?" % sfname, title="Quit", ok=0, yes_no=1,cancel=1) result=dlg.ShowModal() dlg.Destroy() if result == 'cancel': self.canvas.Show(True) return elif result == 'yes': self.Save_Simulation() self.Close() if os.path.exists(self.tmpfile): os.remove(self.tmpfile) def run(lfname=None,params=None,use_splash=True): if use_splash: app1=Application(splash.SplashFrame) app1.Run() app = Application(MainFrame, title="Plasticity",lfname=lfname, params=params) app.Run() if __name__ == '__main__': from optparse import OptionParser parser = OptionParser() parser.add_option( "--nosplash", action="store_false", dest="splash", default=True, help="don't show the splash screen") (options, args) = parser.parse_args() if options.splash: app1=Application(splash.SplashFrame) app1.Run() if len(args)>=1: lfname=args[0] else: lfname=None run(lfname)
bblais/plasticity
plasticity/run.py
Python
mit
17,982
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _index = require('../../isSameWeek/index.js'); var _index2 = _interopRequireDefault(_index); var _index3 = require('../_lib/convertToFP/index.js'); var _index4 = _interopRequireDefault(_index3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // This file is generated automatically by `scripts/build/fp.js`. Please, don't change it. var isSameWeekWithOptions = (0, _index4.default)(_index2.default, 3); exports.default = isSameWeekWithOptions; module.exports = exports['default'];
lucionei/chamadotecnico
chamadosTecnicosFinal-app/node_modules/date-fns/fp/isSameWeekWithOptions/index.js
JavaScript
mit
621
package com.jeremiq.tictactoe.game.board; public class InvalidMoveException extends Exception { public InvalidMoveException(String message) { super(message); } }
jeremiq/tic-tac-toe
src/main/java/com/jeremiq/tictactoe/game/board/InvalidMoveException.java
Java
mit
179
angular.module('EggApp', ['ngRoute'], function($routeProvider) { $routeProvider .when('/', { templateUrl: '/app/view/search.html', controller: 'SearchController' }) .when('/show/:id', { templateUrl: '/app/view/show.html', controller: 'ShowController' }) .otherwise({ redirectTo: '/' }); });
kamilbiela/bowereggs-frontend
app/app.js
JavaScript
mit
402
using System; using System.Collections.Generic; using System.Linq; using System.Web.UI; using System.Data; using System.Globalization; using System.Web.UI.WebControls; public partial class Detail : Page { public const string KeyDropDownData = "KeyDropDownData"; public const string KeyData = "KeyData"; private bool _reload; private int? _id; private PageLoadInfo _dropDownData; private DetailData _data; private bool _saveClicked; protected override void OnInit(EventArgs e) { base.OnInit(e); var idString = Request.QueryString["id"]; int idValue; _id = null; if (!string.IsNullOrEmpty(idString) && int.TryParse(idString, out idValue)) { _id = idValue; } } protected override void LoadViewState(object savedState) { base.LoadViewState(savedState); _dropDownData = ViewState[KeyDropDownData] as PageLoadInfo ?? new PageLoadInfo(); _data = ViewState[KeyData] as DetailData ?? new DetailData(); } protected override object SaveViewState() { ViewState[KeyDropDownData] = _dropDownData; return base.SaveViewState(); } private void GenerateControls(List<Product> data) { lbProductsAvailable.Items.Clear(); foreach (var item in data.Where(x => !x.IsOrdered && (x.Available == null || x.NotOrdered > 0))) { var text = item.Name + ", €" + item.Price; if (item.Available != null) text += ", ostáva " + item.NotOrdered; lbProductsAvailable.Items.Add(new ListItem(text, item.Id.ToString())); } lbProductsAvailable.Rows = Math.Max(1, Math.Min(20, lbProductsAvailable.Items.Count)); lbProductsOrdered.Items.Clear(); foreach (var item in data.Where(x => x.IsOrdered)) { var text = item.Name + ", €" + item.Price; lbProductsOrdered.Items.Add(new ListItem(text, item.Id.ToString())); } lbProductsOrdered.Rows = Math.Max(1, lbProductsOrdered.Items.Count); } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { _dropDownData = Database.GetPageLoadInfo(); GenerateControls(_dropDownData.Products); Common.FillDropDown(ddlChurch, _dropDownData.Churches, new ListItem(Common.ChybaZbor, "0")); Common.FillJobs(ddlJob, _dropDownData.Jobs, true); LoadData(); } lblSuccess.Text = ""; } private void LoadData() { _reload = true; } protected void btnSave_Click(object sender, EventArgs e) { _saveClicked = true; } private void Transaction(int paymentToUs, int donationToUs) { float amount = 0; if (!string.IsNullOrWhiteSpace(txtAmount.Text)) { if (float.TryParse(txtAmount.Text, out amount)) { amount = Math.Abs(amount); if (amount >= 0.01) { try { if (paymentToUs != 0) { Database.AddPayment(_id.Value, paymentToUs * amount, (paymentToUs > 0 ? "Platba na mieste" : "Vratenie preplatku") + ", IP = " + Common.GetIpAddress()); LoadData(); } if (donationToUs != 0) { Database.AddDonation(_id.Value, donationToUs * amount); LoadData(); } } catch (Exception ex) { lblError.Text = ex.Message + ' ' + ex.InnerException; } } } } } protected void btnTheyDonatedToUs_Click(object sender, EventArgs e) { Transaction(0, 1); } protected void btnTheyPaidUs_Click(object sender, EventArgs e) { Transaction(1, 0); } protected void btnWePaidThem_Click(object sender, EventArgs e) { Transaction(-1, 0); } protected void btnWeDonatedToThem_Click(object sender, EventArgs e) { Transaction(0, -1); } protected void btnShowedUp_Click(object sender, EventArgs e) { Database.ShowedUp(_id.Value); LoadData(); } protected void btnAdd_Click(object sender, EventArgs e) { foreach (ListItem item in lbProductsAvailable.Items) { if (item.Selected) { var foundProduct = _dropDownData.Products.FirstOrDefault(x => x.Id.ToString() == item.Value); if (foundProduct != null) { foundProduct.IsOrdered = true; } } } GenerateControls(_dropDownData.Products); } protected void btnRemove_Click(object sender, EventArgs e) { foreach (ListItem item in lbProductsOrdered.Items) { if (item.Selected) { var foundProduct = _dropDownData.Products.FirstOrDefault(x => x.Id.ToString() == item.Value); if (foundProduct != null) { foundProduct.IsOrdered = false; } } } GenerateControls(_dropDownData.Products); } private List<int> GetOrderedProducts() { var result = new List<int>(); foreach (ListItem item in lbProductsOrdered.Items) { int idProduct; if (int.TryParse(item.Value, out idProduct)) { result.Add(idProduct); } } return result; } private DetailData GetDataFromPage() { var errors = new List<string>(); if (string.IsNullOrWhiteSpace(txtFirstName.Text)) errors.Add(Common.ChybaMeno); if (string.IsNullOrWhiteSpace(txtLastName.Text)) errors.Add(Common.ChybaPriezvisko); if (!string.IsNullOrWhiteSpace(txtEmail.Text) && !Common.ValidateEmail(txtEmail.Text.Trim())) errors.Add(Common.ChybaEmail); var idChurch = ddlChurch.SelectedValue.StringToInt(); if (idChurch == 0 || idChurch == -1) idChurch = null; var idJob = ddlJob.SelectedValue.StringToInt(); if (idJob == 0) idJob = null; lblError.Text = ""; if (errors.Count > 0) { lblError.Text = string.Join("<br/>", errors); return null; } float? extraFee = null; float tmp; if (!string.IsNullOrWhiteSpace(txtExtraFee.Text) && float.TryParse(txtExtraFee.Text, out tmp)) extraFee = tmp; float donation = 0; if (!string.IsNullOrWhiteSpace(txtDonation.Text)) { if (!float.TryParse(txtDonation.Text, out donation)) errors.Add(Common.ChybaSponzorskyDar); } var data = new DetailData() { Id = _id, FirstName = txtFirstName.Text, LastName = txtLastName.Text, Email = txtEmail.Text, PhoneNumber = txtPhoneNumber.Text, IdChurch = idChurch, OtherChurch = txtOtherChurch.Text, IdJob = idJob, Note = txtNote.Text, Donation = donation, ExtraFee = extraFee, OrderedProducts = GetOrderedProducts(), }; return data; } private void UpdatePageFromData(DetailData data) { lblId.Text = data.Id.ToString(); txtFirstName.Text = data.FirstName; txtLastName.Text = data.LastName; txtEmail.Text = data.Email; txtPhoneNumber.Text = data.PhoneNumber; ddlChurch.SelectedValue = (data.IdChurch ?? 0).ToString(); txtOtherChurch.Text = data.OtherChurch; ddlJob.SelectedValue = (data.IdJob ?? 0).ToString(); txtNote.Text = data.Note; lblRegistrationDate.Text = data.DtRegistered.HasValue ? data.DtRegistered.Value.ToString(new CultureInfo("sk-SK")) : ""; lblPaymentDate.Text = data.DtPlatba.HasValue ? data.DtPlatba.Value.Date.ToString("d.M.yyyy") : ""; lblArrivalDate.Text = data.DtShowedUp.HasValue ? data.DtShowedUp.Value.ToString(new CultureInfo("sk-SK")) : ""; lblPaid.Text = Currency(data.Paid); lblCosts.Text = Currency(data.Costs); lblDonation.Text = Currency(data.Donation); lblSurplus.Text = Currency(data.Surplus); var surplus = data.Surplus >= 0.01; var debt = data.Surplus <= -0.01; lblSurplus.CssClass = debt ? "negative" : "positive"; //btnDarovaliNam.Visible = surplus; //btnDarovaliSme.Visible = debt; btnTheyPaidUs.Visible = debt; btnWePaidThem.Visible = surplus; btnShowedUp.Visible = !data.DtShowedUp.HasValue; txtAmount.Text = Currency(Math.Abs(data.Surplus)); // lblRegistracnyPoplatok.Text = data.RegistraciaZadarmo ? "Zadarmo" : Currency(data.ExtraFee); // txtRegistrationOverride.Text = data.RegistrationOverride == null ? "" : string.Format("{0:0.00}", data.RegistrationOverride); if (data.Group.Count > 0) { lblGroup.Text = string.Join("<br/>", data.Group.Select(x => string.Format("<a href=\"/Detail.aspx?id={0}\" target=\"new\">{1}</a>", x.Id, x.Name))); } _dropDownData.Products = data.Products; GenerateControls(data.Products); } protected override void OnPreRender(EventArgs e) { if (_saveClicked) { var data = GetDataFromPage(); if (data != null) { try { if (!_id.HasValue) { _id = Database.RegisterNewUser(data); if (_id.HasValue) { // just created a user Response.Redirect(string.Format("/Detail.aspx?id={0}", _id.Value)); } else { lblError.Text = "Niečo sa pokazilo. Kontaktujte administrátora."; } } else { Database.UpdateUser(data); // updated a user _reload = true; lblSuccess.Text = "Zmeny boli úspešne uložené"; } } catch (Exception ex) { lblError.Text = ex.Message + "<br/>" + ex.InnerException; } } } if (_reload && _id.HasValue) { _data = Database.GetDetail(_id.Value); if (_data.Id.HasValue) { UpdatePageFromData(_data); } else { Response.Redirect("/Detail.aspx"); } } if (!_id.HasValue) { int idJob; if (int.TryParse(ddlJob.SelectedValue, out idJob)) { var foundJob = _dropDownData.Jobs.FirstOrDefault(x => x.Id == idJob); // foundJob. } lblTotalCost.Text = Currency( GetOrderedProducts() .Select(x => _dropDownData.Products.FirstOrDefault(y => y.Id == x)) .Aggregate(0f, (sum, product) => sum + (product != null ? product.Price : 0)) ); } trId.Visible = _id.HasValue; trGroup.Visible = _id.HasValue && _data.Group.Count > 0; trRegistrationDate.Visible = _id.HasValue; trPaymentDate.Visible = _id.HasValue; trArrivalDate.Visible = _id.HasValue; trPaid.Visible = _id.HasValue; trCosts.Visible = _id.HasValue; trDonation.Visible = _id.HasValue; trSurplus.Visible = _id.HasValue; txtAmount.Visible = _id.HasValue; btnTheyPaidUs.Visible = _id.HasValue; btnWePaidThem.Visible = _id.HasValue; btnTheyDonatedToUs.Visible = _id.HasValue; btnWeDonatedToThem.Visible = _id.HasValue; btnShowedUp.Visible = _id.HasValue; trTotalCost.Visible = !_id.HasValue; lblTitle.Text = _id.HasValue ? _data.FirstName + " " + _data.LastName : "Nový účastník / účastníčka"; btnSave.Text = _id.HasValue ? "Uložiť zmeny" : "Registrovať nového účastníka"; base.OnPreRender(e); } private string Currency(float f) { return string.Format("{0:0.00}", f); } }
BJB-SK/MK
Website_internal/Detail.aspx.cs
C#
mit
12,768
Rails.application.routes.draw do root :to => redirect("/docs"), only_path: false mount Wordset::API => "/api" mount GrapeSwaggerRails::Engine, at: "/docs" end
turboMaCk/wordset-api
config/routes.rb
Ruby
mit
165
namespace Esthar.Data { public enum JsmCommand { NOP, CAL, JMP, JPF, GJMP, LBL, RET, PSHN_L, PSHI_L, POPI_L, PSHM_B, POPM_B, PSHM_W, POPM_W, PSHM_L, POPM_L, PSHSM_B, PSHSM_W, PSHSM_L, PSHAC, REQ, REQSW, REQEW, PREQ, PREQSW, PREQEW, UNUSE, DEBUG, HALT, SET, SET3, IDLOCK, IDUNLOCK, EFFECTPLAY2, FOOTSTEP, JUMP, JUMP3, LADDERUP, LADDERDOWN, LADDERUP2, LADDERDOWN2, MAPJUMP, MAPJUMP3, SETMODEL, BASEANIME, ANIME, ANIMEKEEP, CANIME, CANIMEKEEP, RANIME, RANIMEKEEP, RCANIME, RCANIMEKEEP, RANIMELOOP, RCANIMELOOP, LADDERANIME, DISCJUMP, SETLINE, LINEON, LINEOFF, WAIT, MSPEED, MOVE, MOVEA, PMOVEA, CMOVE, FMOVE, PJUMPA, ANIMESYNC, ANIMESTOP, MESW, MES, MESSYNC, MESVAR, ASK, WINSIZE, WINCLOSE, UCON, UCOFF, MOVIE, MOVIESYNC, SETPC, DIR, DIRP, DIRA, PDIRA, SPUREADY, TALKON, TALKOFF, PUSHON, PUSHOFF, ISTOUCH, MAPJUMPO, MAPJUMPON, MAPJUMPOFF, SETMESSPEED, SHOW, HIDE, TALKRADIUS, PUSHRADIUS, AMESW, AMES, GETINFO, THROUGHON, THROUGHOFF, BATTLE, BATTLERESULT, BATTLEON, BATTLEOFF, KEYSCAN, KEYON, AASK, PGETINFO, DSCROLL, LSCROLL, CSCROLL, DSCROLLA, LSCROLLA, CSCROLLA, SCROLLSYNC, RMOVE, RMOVEA, RPMOVEA, RCMOVE, RFMOVE, MOVESYNC, CLEAR, DSCROLLP, LSCROLLP, CSCROLLP, LTURNR, LTURNL, CTURNR, CTURNL, ADDPARTY, SUBPARTY, CHANGEPARTY, REFRESHPARTY, SETPARTY, ISPARTY, ADDMEMBER, SUBMEMBER, ISMEMBER, LTURN, CTURN, PLTURN, PCTURN, JOIN, MESFORCUS, BGANIME, RBGANIME, RBGANIMELOOP, BGANIMESYNC, BGDRAW, BGOFF, BGANIMESPEED, SETTIMER, DISPTIMER, SHADETIMER, SETGETA, SETROOTTRANS, SETVIBRATE, STOPVIBRATE, MOVIEREADY, GETTIMER, FADEIN, FADEOUT, FADESYNC, SHAKE, SHAKEOFF, FADEBLACK, FOLLOWOFF, FOLLOWON, GAMEOVER, ENDING, SHADELEVEL, SHADEFORM, FMOVEA, FMOVEP, SHADESET, MUSICCHANGE, MUSICLOAD, FADENONE, POLYCOLOR, POLYCOLORALL, KILLTIMER, CROSSMUSIC, DUALMUSIC, EFFECTPLAY, EFFECTLOAD, LOADSYNC, MUSICSTOP, MUSICVOL, MUSICVOLTRANS, MUSICVOLFADE, ALLSEVOL, ALLSEVOLTRANS, ALLSEPOS, ALLSEPOSTRANS, SEVOL, SEVOLTRANS, SEPOS, SEPOSTRANS, SETBATTLEMUSIC, BATTLEMODE, SESTOP, BGANIMEFLAG, INITSOUND, BGSHADE, BGSHADESTOP, RBGSHADELOOP, DSCROLL2, LSCROLL2, CSCROLL2, DSCROLLA2, LSCROLLA2, CSCROLLA2, DSCROLLP2, LSCROLLP2, CSCROLLP2, SCROLLSYNC2, SCROLLMODE2, MENUENABLE, MENUDISABLE, FOOTSTEPON, FOOTSTEPOFF, FOOTSTEPOFFALL, FOOTSTEPCUT, PREMAPJUMP, USE, SPLIT, ANIMESPEED, RND, DCOLADD, DCOLSUB, TCOLADD, TCOLSUB, FCOLADD, FCOLSUB, COLSYNC, DOFFSET, LOFFSETS, COFFSETS, LOFFSET, COFFSET, OFFSETSYNC, RUNENABLE, RUNDISABLE, MAPFADEOFF, MAPFADEON, INITTRACE, SETDRESS, GETDRESS, FACEDIR, FACEDIRA, FACEDIRP, FACEDIRLIMIT, FACEDIROFF, SARALYOFF, SARALYON, SARALYDISPOFF, SARALYDISPON, MESMODE, FACEDIRINIT, FACEDIRI, JUNCTION, SETCAMERA, BATTLECUT, FOOTSTEPCOPY, WORLDMAPJUMP, RFACEDIRI, RFACEDIR, RFACEDIRA, RFACEDIRP, RFACEDIROFF, FACEDIRSYNC, COPYINFO, PCOPYINFO, RAMESW, BGSHADEOFF, AXIS, AXISSYNC, MENUNORMAL, MENUPHS, BGCLEAR, GETPARTY, MENUSHOP, DISC, DSCROLL3, LSCROLL3, CSCROLL3, MACCEL, MLIMIT, ADDITEM, SETWITCH, SETODIN, RESETGF, MENUNAME, REST, MOVECANCEL, PMOVECANCEL, ACTORMODE, MENUSAVE, SAVEENABLE, PHSENABLE, HOLD, MOVIECUT, SETPLACE, SETDCAMERA, CHOICEMUSIC, GETCARD, DRAWPOINT, PHSPOWER, KEY, CARDGAME, SETBAR, DISPBAR, KILLBAR, SCROLLRATIO2, WHOAMI, MUSICSTATUS, MUSICREPLAY, DOORLINEOFF, DOORLINEON, MUSICSKIP, DYING, SETHP, GETHP, MOVEFLUSH, MUSICVOLSYNC, PUSHANIME, POPANIME, KEYSCAN2, KEYON2, PARTICLEON, PARTICLEOFF, KEYSIGHNCHANGE, ADDGIL, ADDPASTGIL, ADDSEEDLEVEL, PARTICLESET, SETDRAWPOINT, MENUTIPS, LASTIN, LASTOUT, SEALEDOFF, MENUTUTO, OPENEYES, CLOSEEYES, BLINKEYES, SETCARD, HOWMANYCARD, WHERECARD, ADDMAGIC, SWAP, SETPARTY2, SPUSYNC, BROKEN, Unknown1, Unknown2, Unknown3, Unknown4, Unknown5, Unknown6, Unknown7, Unknown8, Unknown9, Unknown10, Unknown11, Unknown12, Unknown13, Unknown14, Unknown15, Unknown16, Unknown17, Unknown18 } }
Albeoris/Esthar
Esthar.Data/JSM, SYM/JsmOperationCode.cs
C#
mit
6,772
var Phaser = require('phaser-unofficial'); /** * Wall class. * @param {object} game * @param {number} x * @param {number} y */ Wall = function (game, x, y) { Phaser.Sprite.call(this, game, x, y, 'paddle'); this.game.physics.arcade.enable(this); this.width = 200; this.height = this.game.world.bounds.height; this.blendMode = Phaser.blendModes.ADD; this.body.bounce.setTo(1, 1); this.body.immovable = true; this.alpha = 0; }; Wall.prototype = Object.create(Phaser.Sprite.prototype); Wall.prototype.constructor = Wall; module.exports = Wall;
cognizo/bogey-pong
lib/wall.js
JavaScript
mit
581
exports.definition = { /** * Add custom methods to your Model`s Records * just define a function: * ```js * this.function_name = function(){ * //this == Record * }; * ``` * This will automatically add the new method to your Record * * @class Definition * @name Custom Record Methods * */ mixinCallback: function() { var objKeys = [] var self = this this.use(function() { // get all current property names objKeys = Object.keys(this) }, 90) this.on('finished', function() { // an now search for new ones ==> instance methods for our new model class Object.keys(self).forEach(function(name) { if (objKeys.indexOf(name) === -1) { self.instanceMethods[name] = self[name] delete self[name] } }) }) } }
PhilWaldmann/openrecord
lib/base/methods.js
JavaScript
mit
843
/* ---------------------------------- * PUSH v2.0.0 * Licensed under The MIT License * inspired by chris's jquery.pjax.js * http://opensource.org/licenses/MIT * ---------------------------------- */ !function () { var noop = function () {}; // Pushstate cacheing // ================== var isScrolling; var maxCacheLength = 20; var cacheMapping = sessionStorage; var domCache = {}; var transitionMap = { 'slide-in' : 'slide-out', 'slide-out' : 'slide-in', 'fade' : 'fade' }; var bars = { bartab : '.bar-tab', barnav : '.bar-nav', barfooter : '.bar-footer', barheadersecondary : '.bar-header-secondary' }; var cacheReplace = function (data, updates) { PUSH.id = data.id; if (updates) data = getCached(data.id); cacheMapping[data.id] = JSON.stringify(data); window.history.replaceState(data.id, data.title, data.url); domCache[data.id] = document.body.cloneNode(true); }; var cachePush = function () { var id = PUSH.id; var cacheForwardStack = JSON.parse(cacheMapping.cacheForwardStack || '[]'); var cacheBackStack = JSON.parse(cacheMapping.cacheBackStack || '[]'); cacheBackStack.push(id); while (cacheForwardStack.length) delete cacheMapping[cacheForwardStack.shift()]; while (cacheBackStack.length > maxCacheLength) delete cacheMapping[cacheBackStack.shift()]; window.history.pushState(null, '', cacheMapping[PUSH.id].url); cacheMapping.cacheForwardStack = JSON.stringify(cacheForwardStack); cacheMapping.cacheBackStack = JSON.stringify(cacheBackStack); }; var cachePop = function (id, direction) { var forward = direction == 'forward'; var cacheForwardStack = JSON.parse(cacheMapping.cacheForwardStack || '[]'); var cacheBackStack = JSON.parse(cacheMapping.cacheBackStack || '[]'); var pushStack = forward ? cacheBackStack : cacheForwardStack; var popStack = forward ? cacheForwardStack : cacheBackStack; if (PUSH.id) pushStack.push(PUSH.id); popStack.pop(); cacheMapping.cacheForwardStack = JSON.stringify(cacheForwardStack); cacheMapping.cacheBackStack = JSON.stringify(cacheBackStack); }; var getCached = function (id) { return JSON.parse(cacheMapping[id] || null) || {}; }; var getTarget = function (e) { var target = findTarget(e.target); if ( ! target || e.which > 1 || e.metaKey || e.ctrlKey || isScrolling || location.protocol !== target.protocol || location.host !== target.host || !target.hash && /#/.test(target.href) || target.hash && target.href.replace(target.hash, '') === location.href.replace(location.hash, '') || target.getAttribute('data-ignore') == 'push' ) return; return target; }; // Main event handlers (touchend, popstate) // ========================================== var touchend = function (e) { var target = getTarget(e); if (!target) return; e.preventDefault(); PUSH({ url : target.href, hash : target.hash, timeout : target.getAttribute('data-timeout'), transition : target.getAttribute('data-transition') }); }; var popstate = function (e) { var key; var barElement; var activeObj; var activeDom; var direction; var transition; var transitionFrom; var transitionFromObj; var id = e.state; if (!id || !cacheMapping[id]) return; direction = PUSH.id < id ? 'forward' : 'back'; cachePop(id, direction); activeObj = getCached(id); activeDom = domCache[id]; if (activeObj.title) document.title = activeObj.title; if (direction == 'back') { transitionFrom = JSON.parse(direction == 'back' ? cacheMapping.cacheForwardStack : cacheMapping.cacheBackStack); transitionFromObj = getCached(transitionFrom[transitionFrom.length - 1]); } else { transitionFromObj = activeObj; } if (direction == 'back' && !transitionFromObj.id) return PUSH.id = id; transition = direction == 'back' ? transitionMap[transitionFromObj.transition] : transitionFromObj.transition; if (!activeDom) { return PUSH({ id : activeObj.id, url : activeObj.url, title : activeObj.title, timeout : activeObj.timeout, transition : transition, ignorePush : true }); } if (transitionFromObj.transition) { activeObj = extendWithDom(activeObj, '.content', activeDom.cloneNode(true)); for (key in bars) { barElement = document.querySelector(bars[key]) if (activeObj[key]) swapContent(activeObj[key], barElement); else if (barElement) barElement.parentNode.removeChild(barElement); } } swapContent( (activeObj.contents || activeDom).cloneNode(true), document.querySelector('.content'), transition ); PUSH.id = id; document.body.offsetHeight; // force reflow to prevent scroll }; // Core PUSH functionality // ======================= var PUSH = function (options) { var key; var data = {}; var xhr = PUSH.xhr; options.container = options.container || options.transition ? document.querySelector('.content') : document.body; for (key in bars) { options[key] = options[key] || document.querySelector(bars[key]); } if (xhr && xhr.readyState < 4) { xhr.onreadystatechange = noop; xhr.abort() } xhr = new XMLHttpRequest(); xhr.open('GET', options.url, true); xhr.setRequestHeader('X-PUSH', 'true'); xhr.onreadystatechange = function () { if (options._timeout) clearTimeout(options._timeout); if (xhr.readyState == 4) xhr.status == 200 ? success(xhr, options) : failure(options.url); }; if (!PUSH.id) { cacheReplace({ id : +new Date, url : window.location.href, title : document.title, timeout : options.timeout, transition : null }); } if (options.timeout) { options._timeout = setTimeout(function () { xhr.abort('timeout'); }, options.timeout); } xhr.send(); if (xhr.readyState && !options.ignorePush) cachePush(); }; // Main XHR handlers // ================= var success = function (xhr, options) { var key; var barElement; var data = parseXHR(xhr, options); if (!data.contents) return locationReplace(options.url); if (data.title) document.title = data.title; if (options.transition) { for (key in bars) { barElement = document.querySelector(bars[key]) if (data[key]) swapContent(data[key], barElement); else if (barElement) barElement.parentNode.removeChild(barElement); } } swapContent(data.contents, options.container, options.transition, function () { cacheReplace({ id : options.id || +new Date, url : data.url, title : data.title, timeout : options.timeout, transition : options.transition }, options.id); triggerStateChange(); }); if (!options.ignorePush && window._gaq) _gaq.push(['_trackPageview']) // google analytics if (!options.hash) return; }; var failure = function (url) { throw new Error('Could not get: ' + url) }; // PUSH helpers // ============ var swapContent = function (swap, container, transition, complete) { var enter; var containerDirection; var swapDirection; if (!transition) { if (container) container.innerHTML = swap.innerHTML; else if (swap.classList.contains('content')) document.body.appendChild(swap); else document.body.insertBefore(swap, document.querySelector('.content')); } else { enter = /in$/.test(transition); if (transition == 'fade') { container.classList.add('in'); container.classList.add('fade'); swap.classList.add('fade'); } if (/slide/.test(transition)) { swap.classList.add('sliding-in', enter ? 'right' : 'left'); swap.classList.add('sliding'); container.classList.add('sliding'); } container.parentNode.insertBefore(swap, container); } if (!transition) complete && complete(); if (transition == 'fade') { container.offsetWidth; // force reflow container.classList.remove('in'); container.addEventListener('webkitTransitionEnd', fadeContainerEnd); function fadeContainerEnd() { container.removeEventListener('webkitTransitionEnd', fadeContainerEnd); swap.classList.add('in'); swap.addEventListener('webkitTransitionEnd', fadeSwapEnd); } function fadeSwapEnd () { swap.removeEventListener('webkitTransitionEnd', fadeSwapEnd); container.parentNode.removeChild(container); swap.classList.remove('fade'); swap.classList.remove('in'); complete && complete(); } } if (/slide/.test(transition)) { container.offsetWidth; // force reflow swapDirection = enter ? 'right' : 'left' containerDirection = enter ? 'left' : 'right' container.classList.add(containerDirection); swap.classList.remove(swapDirection); swap.addEventListener('webkitTransitionEnd', slideEnd); function slideEnd() { swap.removeEventListener('webkitTransitionEnd', slideEnd); swap.classList.remove('sliding', 'sliding-in'); swap.classList.remove(swapDirection); container.parentNode.removeChild(container); complete && complete(); } } }; var triggerStateChange = function () { var e = new CustomEvent('push', { detail: { state: getCached(PUSH.id) }, bubbles: true, cancelable: true }); window.dispatchEvent(e); }; var findTarget = function (target) { var i, toggles = document.querySelectorAll('a'); for (; target && target !== document; target = target.parentNode) { for (i = toggles.length; i--;) { if (toggles[i] === target) return target; } } }; var locationReplace = function (url) { window.history.replaceState(null, '', '#'); window.location.replace(url); }; var parseURL = function (url) { var a = document.createElement('a'); a.href = url; return a; }; var extendWithDom = function (obj, fragment, dom) { var i; var result = {}; for (i in obj) result[i] = obj[i]; Object.keys(bars).forEach(function (key) { var el = dom.querySelector(bars[key]); if (el) el.parentNode.removeChild(el); result[key] = el; }); result.contents = dom.querySelector(fragment); return result; }; var parseXHR = function (xhr, options) { var head; var body; var data = {}; var responseText = xhr.responseText; data.url = options.url; if (!responseText) return data; if (/<html/i.test(responseText)) { head = document.createElement('div'); body = document.createElement('div'); head.innerHTML = responseText.match(/<head[^>]*>([\s\S.]*)<\/head>/i)[0] body.innerHTML = responseText.match(/<body[^>]*>([\s\S.]*)<\/body>/i)[0] } else { head = body = document.createElement('div'); head.innerHTML = responseText; } data.title = head.querySelector('title'); data.title = data.title && data.title.innerText.trim(); if (options.transition) data = extendWithDom(data, '.content', body); else data.contents = body; return data; }; // Attach PUSH event handlers // ========================== window.addEventListener('touchstart', function () { isScrolling = false; }); window.addEventListener('touchmove', function () { isScrolling = true; }) window.addEventListener('touchend', touchend); window.addEventListener('click', function (e) { if (getTarget(e)) e.preventDefault(); }); window.addEventListener('popstate', popstate); window.PUSH = PUSH; }();
vladikoff/ratchet
js/push.js
JavaScript
mit
12,122
<?php namespace Kaishiyoku\LaravelMenu\Exceptions; class MenuExistsException extends \Exception { public function __construct(string $name, $code = 0, \Throwable $previous = null) { $message = "Menu '{$name}' already exists."; parent::__construct($message, $code, $previous); } }
Kaishiyoku/laravel-menu
src/Exceptions/MenuExistsException.php
PHP
mit
311
<?php /** * PHP version 5.6 * * This source file is subject to the license that is bundled with this package in the file LICENSE. */ namespace specs\Codeup\Bootcamps; use Codeup\Bootcamps\BootcampId; use Codeup\Bootcamps\Schedule; use Codeup\Bootcamps\Duration; use DateTimeImmutable; use PhpSpec\ObjectBehavior; class BootcampSpec extends ObjectBehavior { /** @var DateTimeImmutable */ private $now; function let() { $this->now = new DateTimeImmutable('now'); $currentMinute = (int) $this->now->format('i'); $currentHour = (int) $this->now->format('G'); if ($currentHour >= 16) { $currentHour -= 7; $this->now = $this->now->setTime($currentHour, $currentMinute); } $this->beConstructedThrough('start', [ BootcampId::fromLiteral(1), Duration::between( $this->now->modify('1 day ago'), $this->now->modify('4 months') ), 'Hampton', Schedule::withClassTimeBetween( $this->now, $this->now->setTime($currentHour + 7, $currentMinute) ) ]); } function it_knows_if_it_is_in_progress() { $this->isInProgress($this->now)->shouldBe(true); } function it_knows_if_has_not_yet_started() { $this->isInProgress($this->now->modify('2 days ago'))->shouldBe(false); } function it_knows_if_has_finished() { $this->isInProgress($this->now->modify('5 months'))->shouldBe(false); } }
MontealegreLuis/attendance
packages/attendance/tests/specs/Bootcamps/BootcampSpec.php
PHP
mit
1,568
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2007 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ ///-----includes_start----- #include "btBulletDynamicsCommon.h" #include <stdio.h> /// This is a Hello World program for running a basic Bullet physics simulation int main(int argc, char** argv) { ///-----includes_end----- int i; ///-----initialization_start----- ///collision configuration contains default setup for memory, collision setup. Advanced users can create their own configuration. btDefaultCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration(); ///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded) btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration); ///btDbvtBroadphase is a good general purpose broadphase. You can also try out btAxis3Sweep. btBroadphaseInterface* overlappingPairCache = new btDbvtBroadphase(); ///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded) btSequentialImpulseConstraintSolver* solver = new btSequentialImpulseConstraintSolver; btDiscreteDynamicsWorld* dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher,overlappingPairCache,solver,collisionConfiguration); dynamicsWorld->setGravity(btVector3(0,-10,0)); ///-----initialization_end----- ///create a few basic rigid bodies btCollisionShape* groundShape = new btBoxShape(btVector3(btScalar(50.),btScalar(50.),btScalar(50.))); //keep track of the shapes, we release memory at exit. //make sure to re-use collision shapes among rigid bodies whenever possible! btAlignedObjectArray<btCollisionShape*> collisionShapes; collisionShapes.push_back(groundShape); btTransform groundTransform; groundTransform.setIdentity(); groundTransform.setOrigin(btVector3(0,-56,0)); { btScalar mass(0.); //rigidbody is dynamic if and only if mass is non zero, otherwise static bool isDynamic = (mass != 0.f); btVector3 localInertia(0,0,0); if (isDynamic) groundShape->calculateLocalInertia(mass,localInertia); //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects btDefaultMotionState* myMotionState = new btDefaultMotionState(groundTransform); btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,groundShape,localInertia); btRigidBody* body = new btRigidBody(rbInfo); //add the body to the dynamics world dynamicsWorld->addRigidBody(body); } { //create a dynamic rigidbody //btCollisionShape* colShape = new btBoxShape(btVector3(1,1,1)); btCollisionShape* colShape = new btSphereShape(btScalar(1.)); collisionShapes.push_back(colShape); /// Create Dynamic Objects btTransform startTransform; startTransform.setIdentity(); btScalar mass(1.f); //rigidbody is dynamic if and only if mass is non zero, otherwise static bool isDynamic = (mass != 0.f); btVector3 localInertia(0,0,0); if (isDynamic) colShape->calculateLocalInertia(mass,localInertia); startTransform.setOrigin(btVector3(2,10,0)); //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform); btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,colShape,localInertia); btRigidBody* body = new btRigidBody(rbInfo); dynamicsWorld->addRigidBody(body); } /// Do some simulation ///-----stepsimulation_start----- for (i=0;i<100;i++) { dynamicsWorld->stepSimulation(1.f/60.f,10); //print positions of all objects for (int j=dynamicsWorld->getNumCollisionObjects()-1; j>=0 ;j--) { btCollisionObject* obj = dynamicsWorld->getCollisionObjectArray()[j]; btRigidBody* body = btRigidBody::upcast(obj); if (body && body->getMotionState()) { btTransform trans; body->getMotionState()->getWorldTransform(trans); printf("world pos = %f,%f,%f\n",float(trans.getOrigin().getX()),float(trans.getOrigin().getY()),float(trans.getOrigin().getZ())); } } } ///-----stepsimulation_end----- //cleanup in the reverse order of creation/initialization ///-----cleanup_start----- //remove the rigidbodies from the dynamics world and delete them for (i=dynamicsWorld->getNumCollisionObjects()-1; i>=0 ;i--) { btCollisionObject* obj = dynamicsWorld->getCollisionObjectArray()[i]; btRigidBody* body = btRigidBody::upcast(obj); if (body && body->getMotionState()) { delete body->getMotionState(); } dynamicsWorld->removeCollisionObject( obj ); delete obj; } //delete collision shapes for (int j=0;j<collisionShapes.size();j++) { btCollisionShape* shape = collisionShapes[j]; collisionShapes[j] = 0; delete shape; } //delete dynamics world delete dynamicsWorld; //delete solver delete solver; //delete broadphase delete overlappingPairCache; //delete dispatcher delete dispatcher; delete collisionConfiguration; //next line is optional: it will be cleared by the destructor when the array goes out of scope collisionShapes.clear(); ///-----cleanup_end----- }
sabov/jedi
extern/bullet/Demos/HelloWorld/HelloWorld.cpp
C++
mit
6,257
using Agrobook.Common; using Agrobook.Domain.Usuarios; using System.Threading.Tasks; using System.Web.Http; namespace Agrobook.Server.Login { [RoutePrefix("login")] public class LoginController : ApiController { private readonly IDateTimeProvider dateTime = ServiceLocator.ResolveSingleton<IDateTimeProvider>(); private readonly UsuariosService usuariosService = ServiceLocator.ResolveSingleton<UsuariosService>(); [HttpPost] [Route("try-login")] public async Task<IHttpActionResult> TryLogin([FromBody]dynamic value) { // Source: http://stackoverflow.com/questions/13120971/how-to-get-json-post-values-with-asp-net-webapi string username = value.username.Value; string password = value.password.Value; var result = await this.usuariosService.HandleAsync(new IniciarSesion(username, password, this.dateTime.Now)); return this.Ok(result); } } }
Narvalex/Agrobook
src/Agrobook.Server/Login/LoginController.cs
C#
mit
983
/* ----------------------------------------------------------------------------------------------------------- Software License for The Fraunhofer FDK AAC Codec Library for Android © Copyright 1995 - 2013 Fraunhofer-Gesellschaft zur Förderung der angewandten Forschung e.V. All rights reserved. 1. INTRODUCTION The Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software that implements the MPEG Advanced Audio Coding ("AAC") encoding and decoding scheme for digital audio. This FDK AAC Codec software is intended to be used on a wide variety of Android devices. AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient general perceptual audio codecs. AAC-ELD is considered the best-performing full-bandwidth communications codec by independent studies and is widely deployed. AAC has been standardized by ISO and IEC as part of the MPEG specifications. Patent licenses for necessary patent claims for the FDK AAC Codec (including those of Fraunhofer) may be obtained through Via Licensing (www.vialicensing.com) or through the respective patent owners individually for the purpose of encoding or decoding bit streams in products that are compliant with the ISO/IEC MPEG audio standards. Please note that most manufacturers of Android devices already license these patent claims through Via Licensing or directly from the patent owners, and therefore FDK AAC Codec software may already be covered under those patent licenses when it is used for those licensed purposes only. Commercially-licensed AAC software libraries, including floating-point versions with enhanced sound quality, are also available from Fraunhofer. Users are encouraged to check the Fraunhofer website for additional applications information and documentation. 2. COPYRIGHT LICENSE Redistribution and use in source and binary forms, with or without modification, are permitted without payment of copyright license fees provided that you satisfy the following conditions: You must retain the complete text of this software license in redistributions of the FDK AAC Codec or your modifications thereto in source code form. You must retain the complete text of this software license in the documentation and/or other materials provided with redistributions of the FDK AAC Codec or your modifications thereto in binary form. You must make available free of charge copies of the complete source code of the FDK AAC Codec and your modifications thereto to recipients of copies in binary form. The name of Fraunhofer may not be used to endorse or promote products derived from this library without prior written permission. You may not charge copyright license fees for anyone to use, copy or distribute the FDK AAC Codec software or your modifications thereto. Your modified versions of the FDK AAC Codec must carry prominent notices stating that you changed the software and the date of any change. For modified versions of the FDK AAC Codec, the term "Fraunhofer FDK AAC Codec Library for Android" must be replaced by the term "Third-Party Modified Version of the Fraunhofer FDK AAC Codec Library for Android." 3. NO PATENT LICENSE NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without limitation the patents of Fraunhofer, ARE GRANTED BY THIS SOFTWARE LICENSE. Fraunhofer provides no warranty of patent non-infringement with respect to this software. You may use this FDK AAC Codec software or modifications thereto only for purposes that are authorized by appropriate patent licenses. 4. DISCLAIMER This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright holders and contributors "AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, including but not limited to the implied warranties of merchantability and fitness for a particular purpose. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE for any direct, indirect, incidental, special, exemplary, or consequential damages, including but not limited to procurement of substitute goods or services; loss of use, data, or profits, or business interruption, however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence), arising in any way out of the use of this software, even if advised of the possibility of such damage. 5. CONTACT INFORMATION Fraunhofer Institute for Integrated Circuits IIS Attention: Audio and Multimedia Departments - FDK AAC LL Am Wolfsmantel 33 91058 Erlangen, Germany www.iis.fraunhofer.de/amm amm-info@iis.fraunhofer.de ----------------------------------------------------------------------------------------------------------- */ /*! \file \brief frequency scale \author Tobias Chalupka */ #include "sbrenc_freq_sca.h" #include "sbr_misc.h" #include BLIK_FDKAAC_U_genericStds_h //original-code:"genericStds.h" /* StartFreq */ static INT getStartFreq(INT fsCore, const INT start_freq); /* StopFreq */ static INT getStopFreq(INT fsCore, const INT stop_freq); static INT numberOfBands(INT b_p_o, INT start, INT stop, FIXP_DBL warp_factor); static void CalcBands(INT * diff, INT start , INT stop , INT num_bands); static INT modifyBands(INT max_band, INT * diff, INT length); static void cumSum(INT start_value, INT* diff, INT length, UCHAR *start_adress); /******************************************************************************* Functionname: FDKsbrEnc_getSbrStartFreqRAW ******************************************************************************* Description: Arguments: Return: *******************************************************************************/ INT FDKsbrEnc_getSbrStartFreqRAW (INT startFreq, INT fsCore) { INT result; if ( startFreq < 0 || startFreq > 15) { return -1; } /* Update startFreq struct */ result = getStartFreq(fsCore, startFreq); result = (result*(fsCore>>5)+1)>>1; /* (result*fsSBR/QMFbands+1)>>1; */ return (result); } /* End FDKsbrEnc_getSbrStartFreqRAW */ /******************************************************************************* Functionname: getSbrStopFreq ******************************************************************************* Description: Arguments: Return: *******************************************************************************/ INT FDKsbrEnc_getSbrStopFreqRAW (INT stopFreq, INT fsCore) { INT result; if ( stopFreq < 0 || stopFreq > 13) return -1; /* Uppdate stopFreq struct */ result = getStopFreq(fsCore, stopFreq); result = (result*(fsCore>>5)+1)>>1; /* (result*fsSBR/QMFbands+1)>>1; */ return (result); } /* End getSbrStopFreq */ /******************************************************************************* Functionname: getStartFreq ******************************************************************************* Description: Arguments: fsCore - core sampling rate Return: *******************************************************************************/ static INT getStartFreq(INT fsCore, const INT start_freq) { INT k0_min; switch(fsCore){ case 8000: k0_min = 24; /* (3000 * nQmfChannels / fsSBR ) + 0.5 */ break; case 11025: k0_min = 17; /* (3000 * nQmfChannels / fsSBR ) + 0.5 */ break; case 12000: k0_min = 16; /* (3000 * nQmfChannels / fsSBR ) + 0.5 */ break; case 16000: k0_min = 16; /* (4000 * nQmfChannels / fsSBR ) + 0.5 */ break; case 22050: k0_min = 12; /* (4000 * nQmfChannels / fsSBR ) + 0.5 */ break; case 24000: k0_min = 11; /* (4000 * nQmfChannels / fsSBR ) + 0.5 */ break; case 32000: k0_min = 10; /* (5000 * nQmfChannels / fsSBR ) + 0.5 */ break; case 44100: k0_min = 7; /* (5000 * nQmfChannels / fsSBR ) + 0.5 */ break; case 48000: k0_min = 7; /* (5000 * nQmfChannels / fsSBR ) + 0.5 */ break; case 96000: k0_min = 3; /* (5000 * nQmfChannels / fsSBR ) + 0.5 */ break; default: k0_min=11; /* illegal fs */ } switch (fsCore) { case 8000: { INT v_offset[]= {-8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7}; return (k0_min + v_offset[start_freq]); } case 11025: { INT v_offset[]= {-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13}; return (k0_min + v_offset[start_freq]); } case 12000: { INT v_offset[]= {-5, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16}; return (k0_min + v_offset[start_freq]); } case 16000: { INT v_offset[]= {-6, -4, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16}; return (k0_min + v_offset[start_freq]); } case 22050: case 24000: case 32000: { INT v_offset[]= {-4, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16, 20}; return (k0_min + v_offset[start_freq]); } case 44100: case 48000: case 96000: { INT v_offset[]= {-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16, 20, 24}; return (k0_min + v_offset[start_freq]); } default: { INT v_offset[]= {0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 16, 20, 24, 28, 33}; return (k0_min + v_offset[start_freq]); } } } /* End getStartFreq */ /******************************************************************************* Functionname: getStopFreq ******************************************************************************* Description: Arguments: Return: *******************************************************************************/ static INT getStopFreq(INT fsCore, const INT stop_freq) { INT result,i; INT k1_min; INT v_dstop[13]; INT *v_stop_freq = NULL; INT v_stop_freq_16[14] = {48,49,50,51,52,54,55,56,57,59,60,61,63,64}; INT v_stop_freq_22[14] = {35,37,38,40,42,44,46,48,51,53,56,58,61,64}; INT v_stop_freq_24[14] = {32,34,36,38,40,42,44,46,49,52,55,58,61,64}; INT v_stop_freq_32[14] = {32,34,36,38,40,42,44,46,49,52,55,58,61,64}; INT v_stop_freq_44[14] = {23,25,27,29,32,34,37,40,43,47,51,55,59,64}; INT v_stop_freq_48[14] = {21,23,25,27,30,32,35,38,42,45,49,54,59,64}; INT v_stop_freq_64[14] = {20,22,24,26,29,31,34,37,41,45,49,54,59,64}; INT v_stop_freq_88[14] = {15,17,19,21,23,26,29,33,37,41,46,51,57,64}; INT v_stop_freq_96[14] = {13,15,17,19,21,24,27,31,35,39,44,50,57,64}; INT v_stop_freq_192[14] = {7, 8,10,12,14,16,19,23,27,32,38,46,54,64}; switch(fsCore){ case 8000: k1_min = 48; v_stop_freq =v_stop_freq_16; break; case 11025: k1_min = 35; v_stop_freq =v_stop_freq_22; break; case 12000: k1_min = 32; v_stop_freq =v_stop_freq_24; break; case 16000: k1_min = 32; v_stop_freq =v_stop_freq_32; break; case 22050: k1_min = 23; v_stop_freq =v_stop_freq_44; break; case 24000: k1_min = 21; v_stop_freq =v_stop_freq_48; break; case 32000: k1_min = 20; v_stop_freq =v_stop_freq_64; break; case 44100: k1_min = 15; v_stop_freq =v_stop_freq_88; break; case 48000: k1_min = 13; v_stop_freq =v_stop_freq_96; break; case 96000: k1_min = 7; v_stop_freq =v_stop_freq_192; break; default: k1_min = 21; /* illegal fs */ } /* if no valid core samplingrate is used this loop produces a segfault, because v_stop_freq is not initialized */ /* Ensure increasing bandwidth */ for(i = 0; i <= 12; i++) { v_dstop[i] = v_stop_freq[i+1] - v_stop_freq[i]; } FDKsbrEnc_Shellsort_int(v_dstop, 13); /* Sort bandwidth changes */ result = k1_min; for(i = 0; i < stop_freq; i++) { result = result + v_dstop[i]; } return(result); }/* End getStopFreq */ /******************************************************************************* Functionname: FDKsbrEnc_FindStartAndStopBand ******************************************************************************* Description: Arguments: srSbr SBR sampling freqency srCore AAC core sampling freqency noChannels Number of QMF channels startFreq SBR start frequency in QMF bands stopFreq SBR start frequency in QMF bands *k0 Output parameter *k2 Output parameter Return: Error code (0 is OK) *******************************************************************************/ INT FDKsbrEnc_FindStartAndStopBand( const INT srSbr, const INT srCore, const INT noChannels, const INT startFreq, const INT stopFreq, INT *k0, INT *k2 ) { /* Update startFreq struct */ *k0 = getStartFreq(srCore, startFreq); /* Test if start freq is outside corecoder range */ if( srSbr*noChannels < *k0 * srCore ) { return (1); /* raise the cross-over frequency and/or lower the number of target bands per octave (or lower the sampling frequency) */ } /*Update stopFreq struct */ if ( stopFreq < 14 ) { *k2 = getStopFreq(srCore, stopFreq); } else if( stopFreq == 14 ) { *k2 = 2 * *k0; } else { *k2 = 3 * *k0; } /* limit to Nyqvist */ if (*k2 > noChannels) { *k2 = noChannels; } /* Test for invalid k0 k2 combinations */ if ( (srCore == 22050) && ( (*k2 - *k0) > MAX_FREQ_COEFFS_FS44100 ) ) return (1); /* Number of bands exceeds valid range of MAX_FREQ_COEFFS for fs=44.1kHz */ if ( (srCore >= 24000) && ( (*k2 - *k0) > MAX_FREQ_COEFFS_FS48000 ) ) return (1); /* Number of bands exceeds valid range of MAX_FREQ_COEFFS for fs>=48kHz */ if ((*k2 - *k0) > MAX_FREQ_COEFFS) return (1);/*Number of bands exceeds valid range of MAX_FREQ_COEFFS */ if ((*k2 - *k0) < 0) return (1);/* Number of bands is negative */ return(0); } /******************************************************************************* Functionname: FDKsbrEnc_UpdateFreqScale ******************************************************************************* Description: Arguments: Return: *******************************************************************************/ INT FDKsbrEnc_UpdateFreqScale( UCHAR *v_k_master, INT *h_num_bands, const INT k0, const INT k2, const INT freqScale, const INT alterScale ) { INT b_p_o = 0; /* bands_per_octave */ FIXP_DBL warp = FL2FXCONST_DBL(0.0f); INT dk = 0; /* Internal variables */ INT k1 = 0, i; INT num_bands0; INT num_bands1; INT diff_tot[MAX_OCTAVE + MAX_SECOND_REGION]; INT *diff0 = diff_tot; INT *diff1 = diff_tot+MAX_OCTAVE; INT k2_achived; INT k2_diff; INT incr = 0; /* Init */ if (freqScale==1) b_p_o = 12; if (freqScale==2) b_p_o = 10; if (freqScale==3) b_p_o = 8; if(freqScale > 0) /*Bark*/ { if(alterScale==0) warp = FL2FXCONST_DBL(0.5f); /* 1.0/(1.0*2.0) */ else warp = FL2FXCONST_DBL(1.0f/2.6f); /* 1.0/(1.3*2.0); */ if(4*k2 >= 9*k0) /*two or more regions (how many times the basis band is copied)*/ { k1=2*k0; num_bands0=numberOfBands(b_p_o, k0, k1, FL2FXCONST_DBL(0.5f)); num_bands1=numberOfBands(b_p_o, k1, k2, warp); CalcBands(diff0, k0, k1, num_bands0);/*CalcBands1 => diff0 */ FDKsbrEnc_Shellsort_int( diff0, num_bands0);/*SortBands sort diff0 */ if (diff0[0] == 0) /* too wide FB bands for target tuning */ { return (1);/* raise the cross-over frequency and/or lower the number of target bands per octave (or lower the sampling frequency */ } cumSum(k0, diff0, num_bands0, v_k_master); /* cumsum */ CalcBands(diff1, k1, k2, num_bands1); /* CalcBands2 => diff1 */ FDKsbrEnc_Shellsort_int( diff1, num_bands1); /* SortBands sort diff1 */ if(diff0[num_bands0-1] > diff1[0]) /* max(1) > min(2) */ { if(modifyBands(diff0[num_bands0-1],diff1, num_bands1)) return(1); } /* Add 2'nd region */ cumSum(k1, diff1, num_bands1, &v_k_master[num_bands0]); *h_num_bands=num_bands0+num_bands1; /* Output nr of bands */ } else /* one region */ { k1=k2; num_bands0=numberOfBands(b_p_o, k0, k1, FL2FXCONST_DBL(0.5f)); CalcBands(diff0, k0, k1, num_bands0);/* CalcBands1 => diff0 */ FDKsbrEnc_Shellsort_int( diff0, num_bands0); /* SortBands sort diff0 */ if (diff0[0] == 0) /* too wide FB bands for target tuning */ { return (1); /* raise the cross-over frequency and/or lower the number of target bands per octave (or lower the sampling frequency */ } cumSum(k0, diff0, num_bands0, v_k_master);/* cumsum */ *h_num_bands=num_bands0; /* Output nr of bands */ } } else /* Linear mode */ { if (alterScale==0) { dk = 1; num_bands0 = 2 * ((k2 - k0)/2); /* FLOOR to get to few number of bands*/ } else { dk = 2; num_bands0 = 2 * (((k2 - k0)/dk +1)/2); /* ROUND to get closest fit */ } k2_achived = k0 + num_bands0*dk; k2_diff = k2 - k2_achived; for(i=0;i<num_bands0;i++) diff_tot[i] = dk; /* If linear scale wasn't achived */ /* and we got wide SBR are */ if (k2_diff < 0) { incr = 1; i = 0; } /* If linear scale wasn't achived */ /* and we got small SBR are */ if (k2_diff > 0) { incr = -1; i = num_bands0-1; } /* Adjust diff vector to get sepc. SBR range */ while (k2_diff != 0) { diff_tot[i] = diff_tot[i] - incr; i = i + incr; k2_diff = k2_diff + incr; } cumSum(k0, diff_tot, num_bands0, v_k_master);/* cumsum */ *h_num_bands=num_bands0; /* Output nr of bands */ } if (*h_num_bands < 1) return(1); /*To small sbr area */ return (0); }/* End FDKsbrEnc_UpdateFreqScale */ static INT numberOfBands(INT b_p_o, INT start, INT stop, FIXP_DBL warp_factor) { INT result=0; /* result = 2* (INT) ( (double)b_p_o * (double)(FDKlog((double)stop/(double)start)/FDKlog((double)2)) * (double)FX_DBL2FL(warp_factor) + 0.5); */ result = ( ( b_p_o * fMult( (CalcLdInt(stop) - CalcLdInt(start)), warp_factor) + (FL2FX_DBL(0.5f)>>LD_DATA_SHIFT) ) >> ((DFRACT_BITS-1)-LD_DATA_SHIFT) ) << 1; /* do not optimize anymore (rounding!!) */ return(result); } static void CalcBands(INT * diff, INT start , INT stop , INT num_bands) { INT i, qb, qe, qtmp; INT previous; INT current; FIXP_DBL base, exp, tmp; previous=start; for(i=1; i<= num_bands; i++) { base = fDivNorm((FIXP_DBL)stop, (FIXP_DBL)start, &qb); exp = fDivNorm((FIXP_DBL)i, (FIXP_DBL)num_bands, &qe); tmp = fPow(base, qb, exp, qe, &qtmp); tmp = fMult(tmp, (FIXP_DBL)(start<<24)); current = (INT)scaleValue(tmp, qtmp-23); current = (current+1) >> 1; /* rounding*/ diff[i-1] = current-previous; previous = current; } }/* End CalcBands */ static void cumSum(INT start_value, INT* diff, INT length, UCHAR *start_adress) { INT i; start_adress[0]=start_value; for(i=1;i<=length;i++) start_adress[i]=start_adress[i-1]+diff[i-1]; } /* End cumSum */ static INT modifyBands(INT max_band_previous, INT * diff, INT length) { INT change=max_band_previous-diff[0]; /* Limit the change so that the last band cannot get narrower than the first one */ if ( change > (diff[length-1] - diff[0]) / 2 ) change = (diff[length-1] - diff[0]) / 2; diff[0] += change; diff[length-1] -= change; FDKsbrEnc_Shellsort_int(diff, length); return(0); }/* End modifyBands */ /******************************************************************************* Functionname: FDKsbrEnc_UpdateHiRes ******************************************************************************* Description: Arguments: Return: *******************************************************************************/ INT FDKsbrEnc_UpdateHiRes( UCHAR *h_hires, INT *num_hires, UCHAR *v_k_master, INT num_master, INT *xover_band ) { INT i; INT max1,max2; if( (v_k_master[*xover_band] > 32 ) || /* v_k_master[*xover_band] > noQMFChannels(dualRate)/divider */ ( *xover_band > num_master ) ) { /* xover_band error, too big for this startFreq. Will be clipped */ /* Calculate maximum value for xover_band */ max1=0; max2=num_master; while( (v_k_master[max1+1] < 32 ) && /* noQMFChannels(dualRate)/divider */ ( (max1+1) < max2) ) { max1++; } *xover_band=max1; } *num_hires = num_master - *xover_band; for(i = *xover_band; i <= num_master; i++) { h_hires[i - *xover_band] = v_k_master[i]; } return (0); }/* End FDKsbrEnc_UpdateHiRes */ /******************************************************************************* Functionname: FDKsbrEnc_UpdateLoRes ******************************************************************************* Description: Arguments: Return: *******************************************************************************/ void FDKsbrEnc_UpdateLoRes(UCHAR * h_lores, INT *num_lores, UCHAR * h_hires, INT num_hires) { INT i; if(num_hires%2 == 0) /* if even number of hires bands */ { *num_lores=num_hires/2; /* Use every second lores=hires[0,2,4...] */ for(i=0;i<=*num_lores;i++) h_lores[i]=h_hires[i*2]; } else /* odd number of hires which means xover is odd */ { *num_lores=(num_hires+1)/2; /* Use lores=hires[0,1,3,5 ...] */ h_lores[0]=h_hires[0]; for(i=1;i<=*num_lores;i++) { h_lores[i]=h_hires[i*2-1]; } } }/* End FDKsbrEnc_UpdateLoRes */
BonexGu/Blik2D-SDK
Blik2D/addon/fdk-aac-0.1.4_for_blik/libSBRenc/src/sbrenc_freq_sca.cpp
C++
mit
22,046
#include "catch.hpp" #include "JumpGame.hpp" TEST_CASE("Jump Game") { JumpGame s; SECTION("Sample tests") { vector<int> nums_1{2, 3, 1, 1, 4}; REQUIRE(s.canJump(nums_1)); vector<int> nums_2{3, 2, 1, 0, 4}; REQUIRE_FALSE(s.canJump(nums_2)); } }
yanzhe-chen/leetcode
tests/JumpGameTest.cpp
C++
mit
290
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. using System; using TerraFX.ApplicationModel; using TerraFX.Graphics; using TerraFX.Numerics; using static TerraFX.Utilities.UnsafeUtilities; namespace TerraFX.Samples.Graphics; public sealed class HelloTransform : HelloWindow { private GraphicsBuffer _constantBuffer = null!; private GraphicsPrimitive _trianglePrimitive = null!; private GraphicsBuffer _uploadBuffer = null!; private GraphicsBuffer _vertexBuffer = null!; private float _trianglePrimitiveTranslationX; public HelloTransform(string name, ApplicationServiceProvider serviceProvider) : base(name, serviceProvider) { } public override void Cleanup() { _trianglePrimitive?.Dispose(); _constantBuffer?.Dispose(); _uploadBuffer?.Dispose(); _vertexBuffer?.Dispose(); base.Cleanup(); } /// <summary>Initializes the GUI for this sample.</summary> /// <param name="application">The hosting <see cref="Application" />.</param> /// <param name="timeout">The <see cref="TimeSpan" /> after which this sample should stop running.</param> /// <param name="windowLocation">The <see cref="Vector2" /> that defines the initial window location.</param> /// <param name="windowSize">The <see cref="Vector2" /> that defines the initial window client rectangle size.</param> public override void Initialize(Application application, TimeSpan timeout, Vector2? windowLocation, Vector2? windowSize) { base.Initialize(application, timeout, windowLocation, windowSize); var graphicsDevice = GraphicsDevice; _constantBuffer = graphicsDevice.CreateConstantBuffer(64 * 1024, GraphicsResourceCpuAccess.Write); _uploadBuffer = graphicsDevice.CreateUploadBuffer(64 * 1024); _vertexBuffer = graphicsDevice.CreateVertexBuffer(64 * 1024); var graphicsCopyContext = graphicsDevice.RentCopyContext(); { graphicsCopyContext.Reset(); _trianglePrimitive = CreateTrianglePrimitive(graphicsCopyContext); graphicsCopyContext.Flush(); graphicsDevice.WaitForIdle(); } graphicsDevice.ReturnContext(graphicsCopyContext); _uploadBuffer.DisposeAllViews(); } protected override void Draw(GraphicsRenderContext graphicsRenderContext) { _trianglePrimitive.Draw(graphicsRenderContext); base.Draw(graphicsRenderContext); } protected override unsafe void Update(TimeSpan delta) { const float TranslationSpeed = 1.0f; const float OffsetBounds = 1.25f; var trianglePrimitiveTranslationX = _trianglePrimitiveTranslationX; { trianglePrimitiveTranslationX += (float)(TranslationSpeed * delta.TotalSeconds); if (trianglePrimitiveTranslationX > OffsetBounds) { trianglePrimitiveTranslationX = -OffsetBounds; } } _trianglePrimitiveTranslationX = trianglePrimitiveTranslationX; var constantBufferView = _trianglePrimitive.PipelineResourceViews![1].As<GraphicsBufferView>(); var constantBufferSpan = constantBufferView.Map<Matrix4x4>(); { // Shaders take transposed matrices, so we want to set X.W constantBufferSpan[0] = Matrix4x4.Identity; constantBufferSpan[0].X = Vector4.Create(1.0f, 0.0f, 0.0f, trianglePrimitiveTranslationX); } constantBufferView.UnmapAndWrite(); } private unsafe GraphicsPrimitive CreateTrianglePrimitive(GraphicsCopyContext graphicsCopyContext) { var graphicsRenderPass = GraphicsRenderPass; var graphicsSurface = graphicsRenderPass.Surface; var graphicsPipeline = CreateGraphicsPipeline(graphicsRenderPass, "Transform", "main", "main"); var constantBuffer = _constantBuffer; var uploadBuffer = _uploadBuffer; return new GraphicsPrimitive( graphicsPipeline, CreateVertexBufferView(graphicsCopyContext, _vertexBuffer, uploadBuffer, aspectRatio: graphicsSurface.Width / graphicsSurface.Height), resourceViews: new GraphicsResourceView[2] { CreateConstantBufferView(graphicsCopyContext, constantBuffer), CreateConstantBufferView(graphicsCopyContext, constantBuffer), } ); static GraphicsBufferView CreateConstantBufferView(GraphicsCopyContext graphicsCopyContext, GraphicsBuffer constantBuffer) { var constantBufferView = constantBuffer.CreateView<Matrix4x4>(1); var constantBufferSpan = constantBufferView.Map<Matrix4x4>(); { constantBufferSpan[0] = Matrix4x4.Identity; } constantBufferView.UnmapAndWrite(); return constantBufferView; } static GraphicsBufferView CreateVertexBufferView(GraphicsCopyContext graphicsCopyContext, GraphicsBuffer vertexBuffer, GraphicsBuffer uploadBuffer, float aspectRatio) { var uploadBufferView = uploadBuffer.CreateView<IdentityVertex>(3); var vertexBufferSpan = uploadBufferView.Map<IdentityVertex>(); { vertexBufferSpan[0] = new IdentityVertex { Color = Colors.Red, Position = Vector3.Create(0.0f, 0.25f * aspectRatio, 0.0f), }; vertexBufferSpan[1] = new IdentityVertex { Color = Colors.Lime, Position = Vector3.Create(0.25f, -0.25f * aspectRatio, 0.0f), }; vertexBufferSpan[2] = new IdentityVertex { Color = Colors.Blue, Position = Vector3.Create(-0.25f, -0.25f * aspectRatio, 0.0f), }; } uploadBufferView.UnmapAndWrite(); var vertexBufferView = vertexBuffer.CreateView<IdentityVertex>(3); graphicsCopyContext.Copy(vertexBufferView, uploadBufferView); return vertexBufferView; } GraphicsPipeline CreateGraphicsPipeline(GraphicsRenderPass graphicsRenderPass, string shaderName, string vertexShaderEntryPoint, string pixelShaderEntryPoint) { var graphicsDevice = graphicsRenderPass.Device; var signature = CreateGraphicsPipelineSignature(graphicsDevice); var vertexShader = CompileShader(graphicsDevice, GraphicsShaderKind.Vertex, shaderName, vertexShaderEntryPoint); var pixelShader = CompileShader(graphicsDevice, GraphicsShaderKind.Pixel, shaderName, pixelShaderEntryPoint); return graphicsRenderPass.CreatePipeline(signature, vertexShader, pixelShader); } static GraphicsPipelineSignature CreateGraphicsPipelineSignature(GraphicsDevice graphicsDevice) { var inputs = new GraphicsPipelineInput[1] { new GraphicsPipelineInput( new GraphicsPipelineInputElement[2] { new GraphicsPipelineInputElement(GraphicsPipelineInputElementKind.Color, GraphicsFormat.R32G32B32A32_SFLOAT, size: 16, alignment: 16), new GraphicsPipelineInputElement(GraphicsPipelineInputElementKind.Position, GraphicsFormat.R32G32B32_SFLOAT, size: 12, alignment: 4), } ), }; var resources = new GraphicsPipelineResourceInfo[2] { new GraphicsPipelineResourceInfo(GraphicsPipelineResourceKind.ConstantBuffer, GraphicsShaderVisibility.Vertex), new GraphicsPipelineResourceInfo(GraphicsPipelineResourceKind.ConstantBuffer, GraphicsShaderVisibility.Vertex), }; return graphicsDevice.CreatePipelineSignature(inputs, resources); } } }
terrafx/terrafx
samples/TerraFX/Graphics/HelloTransform.cs
C#
mit
7,930
using UnityEngine; using HoloToolkit.Unity.InputModule; public class ObjectTapHandler : MonoBehaviour, IInputClickHandler { /// <summary> /// Handles the users taps on objects. /// </summary> /// private AudioClip clickFeedback; private AudioSource audioSource; void Start() { var audioContainer = GameObject.Find("AudioContainer"); audioSource = audioContainer.GetComponents<AudioSource>()[1]; clickFeedback = Resources.Load<AudioClip>("Audio/highclick"); } public void OnInputClicked(InputClickedEventData eventData) { audioSource.PlayOneShot(clickFeedback, 0.1f); ObjectInteraction.Instance.Tap(gameObject); } }
TNOCS/WorldExplorer
Assets/Scripts/Interaction/InputHandlers/ObjectTapHandler.cs
C#
mit
710
import { exec, getById } from "../database/database"; import Gender from "../entities/gender"; export default class GenderController { constructor() {} static getById(id, as_object = true) { let gender = null; let results = getById(id, ` SELECT t1.id, t1.identifier as name FROM genders as t1 `); if(results) { gender = (as_object) ? new Gender(results) : results; } console.log(results); return gender; } }
milk-shake/electron-pokemon
app/js/controllers/genderController.js
JavaScript
mit
485
require 'mcll4r' require 'test/unit' class Mcll4rTest < Test::Unit::TestCase def setup @mcll4r = Mcll4r.new end def test_assert_we_get_back_correct_district_data expected = { "response" => { "state_upper" => { "district" => "029", "display_name" => "TX 29th", "state" => "TX" }, "federal" => { "district" => "16", "display_name" => "TX 16th", "state" => "TX" }, "state_lower" => { "district" => "077", "display_name" => "TX 77th", "state" => "TX" }, "lng" => "-106.490969", "lat" => "31.76321" } } assert_equal expected, @mcll4r.district_lookup(31.76321, -106.490969) end def test_assert_raise_on_error assert_raise DistrictNotFound do @mcll4r.district_lookup(nil,nil) end end def test_assert_raise_on_district_not_found assert_raise DistrictNotFound do @mcll4r.district_lookup( 1.0, 1.0 ) end end end
mcommons/mcll4r
mcll4r_test.rb
Ruby
mit
1,216