repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
viraj-qspl/teamQ
www/js/devjs/services.js
563
angular.module('starter.services', ['ngResource']) /** * A simple example service that returns some data. */ .factory('ListService',['$resource', function($resource) { return $resource('http://115.113.151.200:8081/user/maphook/mobile/list_trends\\/', {}, { query: {method:'GET', params:{}, isArray:false, cache:true} }) }]) .factory('DetailService',['$resource', function($resource) { return $resource('http://115.113.151.200:8081/view_trend/:hookId/:hookType/', {}, { query: {method:'GET', params:{}, isArray:false, cache:true} }); }]);
mit
Gaubee/Simple-OMS
src/app/md-dev-com/core/ripple/ripple-renderer.ts
6787
import { ElementRef, } from '@angular/core'; /** TODO: internal */ export enum ForegroundRippleState { NEW, EXPANDING, FADING_OUT, } /** * Wrapper for a foreground ripple DOM element and its animation state. * TODO: internal */ export class ForegroundRipple { state = ForegroundRippleState.NEW; constructor(public rippleElement: Element) {} } const RIPPLE_SPEED_PX_PER_SECOND = 1000; const MIN_RIPPLE_FILL_TIME_SECONDS = 0.1; const MAX_RIPPLE_FILL_TIME_SECONDS = 0.3; /** * Returns the distance from the point (x, y) to the furthest corner of a rectangle. */ const distanceToFurthestCorner = (x: number, y: number, rect: ClientRect) => { const distX = Math.max(Math.abs(x - rect.left), Math.abs(x - rect.right)); const distY = Math.max(Math.abs(y - rect.top), Math.abs(y - rect.bottom)); return Math.sqrt(distX * distX + distY * distY); }; /** * Helper service that performs DOM manipulations. Not intended to be used outside this module. * The constructor takes a reference to the ripple directive's host element and a map of DOM * event handlers to be installed on the element that triggers ripple animations. * This will eventually become a custom renderer once Angular support exists. * TODO: internal */ export class RippleRenderer { private _backgroundDiv: HTMLElement; private _rippleElement: HTMLElement; private _triggerElement: HTMLElement; _opacity: string; constructor(_elementRef: ElementRef, private _eventHandlers: Map<string, (e: Event) => void>) { this._rippleElement = _elementRef.nativeElement; // The background div is created in createBackgroundIfNeeded when the ripple becomes enabled. // This avoids creating unneeded divs when the ripple is always disabled. this._backgroundDiv = null; } /** Creates the div for the ripple background, if it doesn't already exist. */ createBackgroundIfNeeded() { if (!this._backgroundDiv) { this._backgroundDiv = document.createElement('div'); this._backgroundDiv.classList.add('md-ripple-background'); this._rippleElement.appendChild(this._backgroundDiv); } } /** * Installs event handlers on the given trigger element, and removes event handlers from the * previous trigger if needed. */ setTriggerElement(newTrigger: HTMLElement) { if (this._triggerElement !== newTrigger) { if (this._triggerElement) { this._eventHandlers.forEach((eventHandler, eventName) => { this._triggerElement.removeEventListener(eventName, eventHandler); }); } this._triggerElement = newTrigger; if (this._triggerElement) { this._eventHandlers.forEach((eventHandler, eventName) => { this._triggerElement.addEventListener(eventName, eventHandler); }); } } } /** Installs event handlers on the host element of the md-ripple directive. */ setTriggerElementToHost() { this.setTriggerElement(this._rippleElement); } /** Removes event handlers from the current trigger element if needed. */ clearTriggerElement() { this.setTriggerElement(null); } /** * Creates a foreground ripple and sets its animation to expand and fade in from the position * given by rippleOriginLeft and rippleOriginTop (or from the center of the <md-ripple> * bounding rect if centered is true). */ createForegroundRipple( rippleOriginLeft: number, rippleOriginTop: number, color: string, centered: boolean, radius: number, speedFactor: number, transitionEndCallback: (r: ForegroundRipple, e: TransitionEvent) => void) { const parentRect = this._rippleElement.getBoundingClientRect(); // Create a foreground ripple div with the size and position of the fully expanded ripple. // When the div is created, it's given a transform style that causes the ripple to be displayed // small and centered on the event location (or the center of the bounding rect if the centered // argument is true). Removing that transform causes the ripple to animate to its natural size. const startX = centered ? (parentRect.left + parentRect.width / 2) : rippleOriginLeft; const startY = centered ? (parentRect.top + parentRect.height / 2) : rippleOriginTop; const offsetX = startX - parentRect.left; const offsetY = startY - parentRect.top; const maxRadius = radius > 0 ? radius : distanceToFurthestCorner(startX, startY, parentRect); const rippleDiv = document.createElement('div'); this._rippleElement.appendChild(rippleDiv); rippleDiv.classList.add('md-ripple-foreground'); rippleDiv.style.left = `${offsetX - maxRadius}px`; rippleDiv.style.top = `${offsetY - maxRadius}px`; rippleDiv.style.width = `${2 * maxRadius}px`; rippleDiv.style.height = rippleDiv.style.width; // If color input is not set, this will default to the background color defined in CSS. rippleDiv.style.backgroundColor = color; // Start the ripple tiny. rippleDiv.style.transform = `scale(0.001)`; const fadeInSeconds = (1 / (speedFactor || 1)) * Math.max( MIN_RIPPLE_FILL_TIME_SECONDS, Math.min(MAX_RIPPLE_FILL_TIME_SECONDS, maxRadius / RIPPLE_SPEED_PX_PER_SECOND)); rippleDiv.style.transitionDuration = `${fadeInSeconds}s`; // https://timtaubert.de/blog/2012/09/css-transitions-for-dynamically-created-dom-elements/ // Store the opacity to prevent this line as being seen as a no-op by optimizers. this._opacity = window.getComputedStyle(rippleDiv).opacity; rippleDiv.classList.add('md-ripple-fade-in'); // Clearing the transform property causes the ripple to animate to its full size. rippleDiv.style.transform = ''; const ripple = new ForegroundRipple(rippleDiv); ripple.state = ForegroundRippleState.EXPANDING; rippleDiv.addEventListener('transitionend', (event: TransitionEvent) => transitionEndCallback(ripple, event)); } /** Fades out a foreground ripple after it has fully expanded and faded in. */ fadeOutForegroundRipple(ripple: Element) { ripple.classList.remove('md-ripple-fade-in'); ripple.classList.add('md-ripple-fade-out'); } /** Removes a foreground ripple from the DOM after it has faded out. */ removeRippleFromDom(ripple: Element) { ripple.parentElement.removeChild(ripple); } /** Fades in the ripple background. */ fadeInRippleBackground(color: string) { this._backgroundDiv.classList.add('md-ripple-active'); // If color is not set, this will default to the background color defined in CSS. this._backgroundDiv.style.backgroundColor = color; } /** Fades out the ripple background. */ fadeOutRippleBackground() { if (this._backgroundDiv) { this._backgroundDiv.classList.remove('md-ripple-active'); } } }
mit
orbingol/NURBS-Python
geomdl/linalg.py
25437
""" .. module:: linalg :platform: Unix, Windows :synopsis: Provides linear algebra utility functions .. moduleauthor:: Onur Rauf Bingol <[email protected]> """ import os import math from copy import deepcopy from functools import reduce from .exceptions import GeomdlException from . import _linalg try: from functools import lru_cache except ImportError: from .functools_lru_cache import lru_cache def vector_cross(vector1, vector2): """ Computes the cross-product of the input vectors. :param vector1: input vector 1 :type vector1: list, tuple :param vector2: input vector 2 :type vector2: list, tuple :return: result of the cross product :rtype: tuple """ try: if vector1 is None or len(vector1) == 0 or vector2 is None or len(vector2) == 0: raise ValueError("Input vectors cannot be empty") except TypeError as e: print("An error occurred: {}".format(e.args[-1])) raise TypeError("Input must be a list or tuple") except Exception: raise if not 1 < len(vector1) <= 3 or not 1 < len(vector2) <= 3: raise ValueError("The input vectors should contain 2 or 3 elements") # Convert 2-D to 3-D, if necessary if len(vector1) == 2: v1 = [float(v) for v in vector1] + [0.0] else: v1 = vector1 if len(vector2) == 2: v2 = [float(v) for v in vector2] + [0.0] else: v2 = vector2 # Compute cross product vector_out = [(v1[1] * v2[2]) - (v1[2] * v2[1]), (v1[2] * v2[0]) - (v1[0] * v2[2]), (v1[0] * v2[1]) - (v1[1] * v2[0])] # Return the cross product of the input vectors return vector_out def vector_dot(vector1, vector2): """ Computes the dot-product of the input vectors. :param vector1: input vector 1 :type vector1: list, tuple :param vector2: input vector 2 :type vector2: list, tuple :return: result of the dot product :rtype: float """ try: if vector1 is None or len(vector1) == 0 or vector2 is None or len(vector2) == 0: raise ValueError("Input vectors cannot be empty") except TypeError as e: print("An error occurred: {}".format(e.args[-1])) raise TypeError("Input must be a list or tuple") except Exception: raise # Compute dot product prod = 0.0 for v1, v2 in zip(vector1, vector2): prod += v1 * v2 # Return the dot product of the input vectors return prod def vector_multiply(vector_in, scalar): """ Multiplies the vector with a scalar value. This operation is also called *vector scaling*. :param vector_in: vector :type vector_in: list, tuple :param scalar: scalar value :type scalar: int, float :return: updated vector :rtype: tuple """ scaled_vector = [v * scalar for v in vector_in] return scaled_vector def vector_sum(vector1, vector2, coeff=1.0): """ Sums the vectors. This function computes the result of the vector operation :math:`\\overline{v}_{1} + c * \\overline{v}_{2}`, where :math:`\\overline{v}_{1}` is ``vector1``, :math:`\\overline{v}_{2}` is ``vector2`` and :math:`c` is ``coeff``. :param vector1: vector 1 :type vector1: list, tuple :param vector2: vector 2 :type vector2: list, tuple :param coeff: multiplier for vector 2 :type coeff: float :return: updated vector :rtype: list """ summed_vector = [v1 + (coeff * v2) for v1, v2 in zip(vector1, vector2)] return summed_vector def vector_normalize(vector_in, decimals=18): """ Generates a unit vector from the input. :param vector_in: vector to be normalized :type vector_in: list, tuple :param decimals: number of significands :type decimals: int :return: the normalized vector (i.e. the unit vector) :rtype: list """ try: if vector_in is None or len(vector_in) == 0: raise ValueError("Input vector cannot be empty") except TypeError as e: print("An error occurred: {}".format(e.args[-1])) raise TypeError("Input must be a list or tuple") except Exception: raise # Calculate magnitude of the vector magnitude = vector_magnitude(vector_in) # Normalize the vector if magnitude > 0: vector_out = [] for vin in vector_in: vector_out.append(vin / magnitude) # Return the normalized vector and consider the number of significands return [float(("{:." + str(decimals) + "f}").format(vout)) for vout in vector_out] else: raise ValueError("The magnitude of the vector is zero") def vector_generate(start_pt, end_pt, normalize=False): """ Generates a vector from 2 input points. :param start_pt: start point of the vector :type start_pt: list, tuple :param end_pt: end point of the vector :type end_pt: list, tuple :param normalize: if True, the generated vector is normalized :type normalize: bool :return: a vector from start_pt to end_pt :rtype: list """ try: if start_pt is None or len(start_pt) == 0 or end_pt is None or len(end_pt) == 0: raise ValueError("Input points cannot be empty") except TypeError as e: print("An error occurred: {}".format(e.args[-1])) raise TypeError("Input must be a list or tuple") except Exception: raise ret_vec = [] for sp, ep in zip(start_pt, end_pt): ret_vec.append(ep - sp) if normalize: ret_vec = vector_normalize(ret_vec) return ret_vec def vector_mean(*args): """ Computes the mean (average) of a list of vectors. The function computes the arithmetic mean of a list of vectors, which are also organized as a list of integers or floating point numbers. .. code-block:: python :linenos: # Import geomdl.utilities module from geomdl import utilities # Create a list of vectors as an example vector_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Compute mean vector mean_vector = utilities.vector_mean(*vector_list) # Alternative usage example (same as above): mean_vector = utilities.vector_mean([1, 2, 3], [4, 5, 6], [7, 8, 9]) :param args: list of vectors :type args: list, tuple :return: mean vector :rtype: list """ sz = len(args) mean_vector = [0.0 for _ in range(len(args[0]))] for input_vector in args: mean_vector = [a+b for a, b in zip(mean_vector, input_vector)] mean_vector = [a / sz for a in mean_vector] return mean_vector def vector_magnitude(vector_in): """ Computes the magnitude of the input vector. :param vector_in: input vector :type vector_in: list, tuple :return: magnitude of the vector :rtype: float """ sq_sum = 0.0 for vin in vector_in: sq_sum += vin**2 return math.sqrt(sq_sum) def vector_angle_between(vector1, vector2, **kwargs): """ Computes the angle between the two input vectors. If the keyword argument ``degrees`` is set to *True*, then the angle will be in degrees. Otherwise, it will be in radians. By default, ``degrees`` is set to *True*. :param vector1: vector :type vector1: list, tuple :param vector2: vector :type vector2: list, tuple :return: angle between the vectors :rtype: float """ degrees = kwargs.get('degrees', True) magn1 = vector_magnitude(vector1) magn2 = vector_magnitude(vector2) acos_val = vector_dot(vector1, vector2) / (magn1 * magn2) angle_radians = math.acos(acos_val) if degrees: return math.degrees(angle_radians) else: return angle_radians def vector_is_zero(vector_in, tol=10e-8): """ Checks if the input vector is a zero vector. :param vector_in: input vector :type vector_in: list, tuple :param tol: tolerance value :type tol: float :return: True if the input vector is zero, False otherwise :rtype: bool """ if not isinstance(vector_in, (list, tuple)): raise TypeError("Input vector must be a list or a tuple") res = [False for _ in range(len(vector_in))] for idx in range(len(vector_in)): if abs(vector_in[idx]) < tol: res[idx] = True return all(res) def point_translate(point_in, vector_in): """ Translates the input points using the input vector. :param point_in: input point :type point_in: list, tuple :param vector_in: input vector :type vector_in: list, tuple :return: translated point :rtype: list """ try: if point_in is None or len(point_in) == 0 or vector_in is None or len(vector_in) == 0: raise ValueError("Input arguments cannot be empty") except TypeError as e: print("An error occurred: {}".format(e.args[-1])) raise TypeError("Input must be a list or tuple") except Exception: raise # Translate the point using the input vector point_out = [coord + comp for coord, comp in zip(point_in, vector_in)] return point_out def point_distance(pt1, pt2): """ Computes distance between two points. :param pt1: point 1 :type pt1: list, tuple :param pt2: point 2 :type pt2: list, tuple :return: distance between input points :rtype: float """ if len(pt1) != len(pt2): raise ValueError("The input points should have the same dimension") dist_vector = vector_generate(pt1, pt2, normalize=False) distance = vector_magnitude(dist_vector) return distance def point_mid(pt1, pt2): """ Computes the midpoint of the input points. :param pt1: point 1 :type pt1: list, tuple :param pt2: point 2 :type pt2: list, tuple :return: midpoint :rtype: list """ if len(pt1) != len(pt2): raise ValueError("The input points should have the same dimension") dist_vector = vector_generate(pt1, pt2, normalize=False) half_dist_vector = vector_multiply(dist_vector, 0.5) return point_translate(pt1, half_dist_vector) @lru_cache(maxsize=os.environ['GEOMDL_CACHE_SIZE'] if "GEOMDL_CACHE_SIZE" in os.environ else 16) def matrix_identity(n): """ Generates a :math:`N \\times N` identity matrix. :param n: size of the matrix :type n: int :return: identity matrix :rtype: list """ imat = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)] return imat def matrix_pivot(m, sign=False): """ Computes the pivot matrix for M, a square matrix. This function computes * the permutation matrix, :math:`P` * the product of M and P, :math:`M \\times P` * determinant of P, :math:`det(P)` if ``sign = True`` :param m: input matrix :type m: list, tuple :param sign: flag to return the determinant of the permutation matrix, P :type sign: bool :return: a tuple containing the matrix product of M x P, P and det(P) :rtype: tuple """ mp = deepcopy(m) n = len(mp) p = matrix_identity(n) # permutation matrix num_rowswap = 0 for j in range(0, n): row = j a_max = 0.0 for i in range(j, n): a_abs = abs(mp[i][j]) if a_abs > a_max: a_max = a_abs row = i if j != row: num_rowswap += 1 for q in range(0, n): # Swap rows p[j][q], p[row][q] = p[row][q], p[j][q] mp[j][q], mp[row][q] = mp[row][q], mp[j][q] if sign: return mp, p, math.pow(-1, num_rowswap) return mp, p def matrix_inverse(m): """ Computes the inverse of the matrix via LUP decomposition. :param m: input matrix :type m: list, tuple :return: inverse of the matrix :rtype: list """ mp, p = matrix_pivot(m) m_inv = lu_solve(mp, p) return m_inv def matrix_determinant(m): """ Computes the determinant of the square matrix :math:`M` via LUP decomposition. :param m: input matrix :type m: list, tuple :return: determinant of the matrix :rtype: float """ mp, p, sign = matrix_pivot(m, sign=True) m_l, m_u = lu_decomposition(mp) det = 1.0 for i in range(len(m)): det *= m_l[i][i] * m_u[i][i] det *= sign return det def matrix_transpose(m): """ Transposes the input matrix. The input matrix :math:`m` is a 2-dimensional array. :param m: input matrix with dimensions :math:`(n \\times m)` :type m: list, tuple :return: transpose matrix with dimensions :math:`(m \\times n)` :rtype: list """ num_cols = len(m) num_rows = len(m[0]) m_t = [] for i in range(num_rows): temp = [] for j in range(num_cols): temp.append(m[j][i]) m_t.append(temp) return m_t def matrix_multiply(mat1, mat2): """ Matrix multiplication (iterative algorithm). The running time of the iterative matrix multiplication algorithm is :math:`O(n^{3})`. :param mat1: 1st matrix with dimensions :math:`(n \\times p)` :type mat1: list, tuple :param mat2: 2nd matrix with dimensions :math:`(p \\times m)` :type mat2: list, tuple :return: resultant matrix with dimensions :math:`(n \\times m)` :rtype: list """ n = len(mat1) p1 = len(mat1[0]) p2 = len(mat2) if p1 != p2: raise GeomdlException("Column - row size mismatch") try: # Matrix - matrix multiplication m = len(mat2[0]) mat3 = [[0.0 for _ in range(m)] for _ in range(n)] for i in range(n): for j in range(m): for k in range(p2): mat3[i][j] += float(mat1[i][k] * mat2[k][j]) except TypeError: # Matrix - vector multiplication mat3 = [0.0 for _ in range(n)] for i in range(n): for k in range(p2): mat3[i] += float(mat1[i][k] * mat2[k]) return mat3 def matrix_scalar(m, sc): """ Matrix multiplication by a scalar value (iterative algorithm). The running time of the iterative matrix multiplication algorithm is :math:`O(n^{2})`. :param m: input matrix :type m: list, tuple :param sc: scalar value :type sc: int, float :return: resultant matrix :rtype: list """ mm = [[0.0 for _ in range(len(m[0]))] for _ in range(len(m))] for i in range(len(m)): for j in range(len(m[0])): mm[i][j] = float(m[i][j] * sc) return mm def triangle_normal(tri): """ Computes the (approximate) normal vector of the input triangle. :param tri: triangle object :type tri: elements.Triangle :return: normal vector of the triangle :rtype: tuple """ vec1 = vector_generate(tri.vertices[0].data, tri.vertices[1].data) vec2 = vector_generate(tri.vertices[1].data, tri.vertices[2].data) return vector_cross(vec1, vec2) def triangle_center(tri, uv=False): """ Computes the center of mass of the input triangle. :param tri: triangle object :type tri: elements.Triangle :param uv: if True, then finds parametric position of the center of mass :type uv: bool :return: center of mass of the triangle :rtype: tuple """ if uv: data = [t.uv for t in tri] mid = [0.0, 0.0] else: data = tri.vertices mid = [0.0, 0.0, 0.0] for vert in data: mid = [m + v for m, v in zip(mid, vert)] mid = [float(m) / 3.0 for m in mid] return tuple(mid) @lru_cache(maxsize=os.environ['GEOMDL_CACHE_SIZE'] if "GEOMDL_CACHE_SIZE" in os.environ else 128) def binomial_coefficient(k, i): """ Computes the binomial coefficient (denoted by *k choose i*). Please see the following website for details: http://mathworld.wolfram.com/BinomialCoefficient.html :param k: size of the set of distinct elements :type k: int :param i: size of the subsets :type i: int :return: combination of *k* and *i* :rtype: float """ # Special case if i > k: return float(0) # Compute binomial coefficient k_fact = math.factorial(k) i_fact = math.factorial(i) k_i_fact = math.factorial(k - i) return float(k_fact / (k_i_fact * i_fact)) def lu_decomposition(matrix_a): """ LU-Factorization method using Doolittle's Method for solution of linear systems. Decomposes the matrix :math:`A` such that :math:`A = LU`. The input matrix is represented by a list or a tuple. The input matrix is **2-dimensional**, i.e. list of lists of integers and/or floats. :param matrix_a: Input matrix (must be a square matrix) :type matrix_a: list, tuple :return: a tuple containing matrices L and U :rtype: tuple """ # Check if the 2-dimensional input matrix is a square matrix q = len(matrix_a) for idx, m_a in enumerate(matrix_a): if len(m_a) != q: raise ValueError("The input must be a square matrix. " + "Row " + str(idx + 1) + " has a size of " + str(len(m_a)) + ".") # Return L and U matrices return _linalg.doolittle(matrix_a) def forward_substitution(matrix_l, matrix_b): """ Forward substitution method for the solution of linear systems. Solves the equation :math:`Ly = b` using forward substitution method where :math:`L` is a lower triangular matrix and :math:`b` is a column matrix. :param matrix_l: L, lower triangular matrix :type matrix_l: list, tuple :param matrix_b: b, column matrix :type matrix_b: list, tuple :return: y, column matrix :rtype: list """ q = len(matrix_b) matrix_y = [0.0 for _ in range(q)] matrix_y[0] = float(matrix_b[0]) / float(matrix_l[0][0]) for i in range(1, q): matrix_y[i] = float(matrix_b[i]) - sum([matrix_l[i][j] * matrix_y[j] for j in range(0, i)]) matrix_y[i] /= float(matrix_l[i][i]) return matrix_y def backward_substitution(matrix_u, matrix_y): """ Backward substitution method for the solution of linear systems. Solves the equation :math:`Ux = y` using backward substitution method where :math:`U` is a upper triangular matrix and :math:`y` is a column matrix. :param matrix_u: U, upper triangular matrix :type matrix_u: list, tuple :param matrix_y: y, column matrix :type matrix_y: list, tuple :return: x, column matrix :rtype: list """ q = len(matrix_y) matrix_x = [0.0 for _ in range(q)] matrix_x[q - 1] = float(matrix_y[q - 1]) / float(matrix_u[q - 1][q - 1]) for i in range(q - 2, -1, -1): matrix_x[i] = float(matrix_y[i]) - sum([matrix_u[i][j] * matrix_x[j] for j in range(i, q)]) matrix_x[i] /= float(matrix_u[i][i]) return matrix_x def lu_solve(matrix_a, b): """ Computes the solution to a system of linear equations. This function solves :math:`Ax = b` using LU decomposition. :math:`A` is a :math:`N \\times N` matrix, :math:`b` is :math:`N \\times M` matrix of :math:`M` column vectors. Each column of :math:`x` is a solution for corresponding column of :math:`b`. :param matrix_a: matrix A :type m_l: list :param b: matrix of M column vectors :type b: list :return: x, the solution matrix :rtype: list """ # Variable initialization dim = len(b[0]) num_x = len(b) x = [[0.0 for _ in range(dim)] for _ in range(num_x)] # LU decomposition m_l, m_u = lu_decomposition(matrix_a) # Solve the system of linear equations for i in range(dim): bt = [b1[i] for b1 in b] y = forward_substitution(m_l, bt) xt = backward_substitution(m_u, y) for j in range(num_x): x[j][i] = xt[j] # Return the solution return x def lu_factor(matrix_a, b): """ Computes the solution to a system of linear equations with partial pivoting. This function solves :math:`Ax = b` using LUP decomposition. :math:`A` is a :math:`N \\times N` matrix, :math:`b` is :math:`N \\times M` matrix of :math:`M` column vectors. Each column of :math:`x` is a solution for corresponding column of :math:`b`. :param matrix_a: matrix A :type m_l: list :param b: matrix of M column vectors :type b: list :return: x, the solution matrix :rtype: list """ # Variable initialization dim = len(b[0]) num_x = len(b) x = [[0.0 for _ in range(dim)] for _ in range(num_x)] # LUP decomposition mp, p = matrix_pivot(matrix_a) m_l, m_u = lu_decomposition(mp) # Solve the system of linear equations for i in range(dim): bt = [b1[i] for b1 in b] y = forward_substitution(m_l, bt) xt = backward_substitution(m_u, y) for j in range(num_x): x[j][i] = xt[j] # Return the solution return x def linspace(start, stop, num, decimals=18): """ Returns a list of evenly spaced numbers over a specified interval. Inspired from Numpy's linspace function: https://github.com/numpy/numpy/blob/master/numpy/core/function_base.py :param start: starting value :type start: float :param stop: end value :type stop: float :param num: number of samples to generate :type num: int :param decimals: number of significands :type decimals: int :return: a list of equally spaced numbers :rtype: list """ start = float(start) stop = float(stop) if abs(start - stop) <= 10e-8: return [start] num = int(num) if num > 1: div = num - 1 delta = stop - start return [float(("{:." + str(decimals) + "f}").format((start + (float(x) * float(delta) / float(div))))) for x in range(num)] return [float(("{:." + str(decimals) + "f}").format(start))] def frange(start, stop, step=1.0): """ Implementation of Python's ``range()`` function which works with floats. Reference to this implementation: https://stackoverflow.com/a/36091634 :param start: start value :type start: float :param stop: end value :type stop: float :param step: increment :type step: float :return: float :rtype: generator """ i = 0.0 x = float(start) # Prevent yielding integers. x0 = x epsilon = step / 2.0 yield x # always yield first value while x + epsilon < stop: i += 1.0 x = x0 + i * step yield x if stop > x: yield stop # for yielding last value of the knot vector if the step is a large value, like 0.1 def convex_hull(points): """ Returns points on convex hull in counterclockwise order according to Graham's scan algorithm. Reference: https://gist.github.com/arthur-e/5cf52962341310f438e96c1f3c3398b8 .. note:: This implementation only works in 2-dimensional space. :param points: list of 2-dimensional points :type points: list, tuple :return: convex hull of the input points :rtype: list """ turn_left, turn_right, turn_none = (1, -1, 0) def cmp(a, b): return (a > b) - (a < b) def turn(p, q, r): return cmp((q[0] - p[0])*(r[1] - p[1]) - (r[0] - p[0])*(q[1] - p[1]), 0) def keep_left(hull, r): while len(hull) > 1 and turn(hull[-2], hull[-1], r) != turn_left: hull.pop() if not len(hull) or hull[-1] != r: hull.append(r) return hull points = sorted(points) l = reduce(keep_left, points, []) u = reduce(keep_left, reversed(points), []) return l.extend(u[i] for i in range(1, len(u) - 1)) or l def is_left(point0, point1, point2): """ Tests if a point is Left|On|Right of an infinite line. Ported from the C++ version: on http://geomalgorithms.com/a03-_inclusion.html .. note:: This implementation only works in 2-dimensional space. :param point0: Point P0 :param point1: Point P1 :param point2: Point P2 :return: >0 for P2 left of the line through P0 and P1 =0 for P2 on the line <0 for P2 right of the line """ return ((point1[0] - point0[0]) * (point2[1] - point0[1])) - ((point2[0] - point0[0]) * (point1[1] - point0[1])) def wn_poly(point, vertices): """ Winding number test for a point in a polygon. Ported from the C++ version: http://geomalgorithms.com/a03-_inclusion.html .. note:: This implementation only works in 2-dimensional space. :param point: point to be tested :type point: list, tuple :param vertices: vertex points of a polygon vertices[n+1] with vertices[n] = vertices[0] :type vertices: list, tuple :return: True if the point is inside the input polygon, False otherwise :rtype: bool """ wn = 0 # the winding number counter v_size = len(vertices) - 1 # loop through all edges of the polygon for i in range(v_size): # edge from V[i] to V[i+1] if vertices[i][1] <= point[1]: # start y <= P.y if vertices[i + 1][1] > point[1]: # an upward crossing if is_left(vertices[i], vertices[i + 1], point) > 0: # P left of edge wn += 1 # have a valid up intersect else: # start y > P.y (no test needed) if vertices[i + 1][1] <= point[1]: # a downward crossing if is_left(vertices[i], vertices[i + 1], point) < 0: # P right of edge wn -= 1 # have a valid down intersect # return wn return bool(wn)
mit
kicumkicum/vknplayer
app/api/index.js
304
/** * @type {{ * Api: Api, * vk: vk, * Gmusik: GMusic, * yandexMusic: yandexMusic * }} */ var api = {}; module.exports = api; api.Api = require('./lib/api'); api.vk = require('./lib/vk'); api.Gmusik = require('./lib/gmusic'); api.yandexMusic = require('./lib/yandex-music');
mit
ekzoplasm/yoxima
app/cache/prod/annotations/81f8000a42e2165862ce52927a39470968d73f82$comments.cache.php
257
<?php return unserialize('a:1:{i:0;O:30:"Doctrine\\ORM\\Mapping\\OneToMany":6:{s:8:"mappedBy";s:7:"article";s:12:"targetEntity";s:33:"yoxima\\BlogBundle\\Entity\\Comments";s:7:"cascade";N;s:5:"fetch";s:4:"LAZY";s:13:"orphanRemoval";b:0;s:7:"indexBy";N;}}');
mit
bign8/purchasing-system
src/app/security/login/toolbar.js
723
angular.module('security.login.toolbar', []) // The loginToolbar directive is a reusable widget that can show login or logout buttons // and information the current authenticated user .directive('loginToolbar', ['security', function(security) { var directive = { templateUrl: 'app/security/login/toolbar.tpl.html', restrict: 'E', replace: true, scope: true, link: function($scope, $element, $attrs, $controller) { $scope.isAuthenticated = security.isAuthenticated; $scope.login = security.showLogin; $scope.logout = security.logout; $scope.$watch(function() { return security.currentUser; }, function(currentUser) { $scope.currentUser = currentUser; }); } }; return directive; }]);
mit
projetCartoSavoie/carto
src/Carto/AccueilBundle/CartoAccueilBundle.php
524
<?php /** * Bundle frontal * * * @author Rémy Cluze <[email protected]> * @author Anthony Di Lisio <[email protected]> * @author Juliana Leclaire <[email protected]> * @author Rémi Mollard <[email protected]> * @author Céline de Roland <[email protected]> * * @version 1.0 */ namespace Carto\AccueilBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; /** * Bundle frontal * */ class CartoAccueilBundle extends Bundle { }
mit
erikringsmuth/suri
app-built/bower_components/ace/lib/ace/mode/vbscript.js
2069
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2012, Ajax.org B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Ajax.org B.V. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. 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 OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * Contributor(s): * * * * ***** END LICENSE BLOCK ***** */ define(["require","exports","module","../lib/oop","./text","./vbscript_highlight_rules"],function(e,t,n){var r=e("../lib/oop"),i=e("./text").Mode,s=e("./vbscript_highlight_rules").VBScriptHighlightRules,o=function(){this.HighlightRules=s};r.inherits(o,i),function(){this.lineCommentStart=["'","REM"],this.$id="ace/mode/vbscript"}.call(o.prototype),t.Mode=o});
mit
Haufe-Lexware/haufe.no-frills-transformation
src/NoFrillsTransformation/NoFrillsTransformation.Plugins.Salesforce.DotNet/SfdcDotNetReaderFactory.cs
2000
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using System.Linq; using System.Text; using System.Xml.Serialization; using NoFrillsTransformation.Interfaces; using NoFrillsTransformation.Plugins.Salesforce.Config; namespace NoFrillsTransformation.Plugins.Salesforce.DotNet { [Export(typeof(NoFrillsTransformation.Interfaces.ISourceReaderFactory))] public class SfdcDotNetReaderFactory : SfdcBaseFactory, ISourceReaderFactory { public bool CanReadSource(string source) { if (string.IsNullOrWhiteSpace(source)) return false; string temp = source.ToLowerInvariant(); if (!temp.StartsWith("soql.net://")) return false; return true; } public ISourceReader CreateReader(IContext context, string source, string config) { string soql = source.Substring(11); var soqlQuery = ParseQuery(soql); var sfdcConfig = ParseConfig(context, config); SfdcDotNetReader sfdcReader = null; try { context.Logger.Info("SfdcDotNetReaderFactory: Attempting to create an SfdcReader."); sfdcReader = new SfdcDotNetReader(context, soqlQuery, sfdcConfig); sfdcReader.Initialize(); } catch (Exception ex) { if (null != sfdcReader) { sfdcReader.Dispose(); sfdcReader = null; } throw new InvalidOperationException("An error occurred while creating the SfdcReader: " + ex.Message); } context.Logger.Info("SfdcReaderFactory: Successfully created a SfdcReader."); return sfdcReader; } // public bool SupportsQuery { get { return false; } } } }
mit
gemmaan/moviesenal
Hasil/locdetection.py
1600
import json from mpl_toolkits.basemap import Basemap tweet_files = ['hasilstreaming.json'] tweets = [] for file in tweet_files: with open(file, 'r') as f: for line in f.readlines(): tweets.append(json.loads(line)) def populate_tweet_df(tweets): df = pd.DataFrame() df['text'] = list(map(lambda tweet: tweet['text'], tweets)) df['location'] = list(map(lambda tweet: tweet['user']['location'], tweets)) df['country_code'] = list(map(lambda tweet: tweet['place']['country_code'] if tweet['place'] != None else '', tweets)) df['long'] = list(map(lambda tweet: tweet['coordinates']['coordinates'][0] if tweet['coordinates'] != None else 'NaN', tweets)) df['latt'] = list(map(lambda tweet: tweet['coordinates']['coordinates'][1] if tweet['coordinates'] != None else 'NaN', tweets)) return df # plot the blank world map my_map = Basemap(projection='merc', lat_0=50, lon_0=-100, resolution = 'l', area_thresh = 5000.0, llcrnrlon=-140, llcrnrlat=-55, urcrnrlon=160, urcrnrlat=70) # set resolution='h' for high quality # draw elements onto the world map my_map.drawcountries() #my_map.drawstates() my_map.drawcoastlines(antialiased=False, linewidth=0.005) # add coordinates as red dots longs = list(df.loc[(df.long != 'NaN')].long) latts = list(df.loc[df.latt != 'NaN'].latt) x, y = my_map(longs, latts) my_map.plot(x, y, 'ro', markersize=6, alpha=0.5) plt.show()
mit
SlonCorp/laravel-acl
src/migrations/acl/2017_04_25_092657_create_permission_role_table.php
830
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePermissionRoleTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('permission_role', function (Blueprint $table) { $table->increments('id'); $table->integer('permission_id')->unsigned()->index()->foreign()->references('id')->on('permissions')->onDelete('cascade'); $table->integer('role_id')->unsigned()->index()->foreign()->references('id')->on('roles')->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('permission_role'); } }
mit
uber-common/luma.gl
modules/gltools/src/index.js
653
// Installs polyfills to support a subset of WebGL2 APIs on WebGL1 contexts export {default as polyfillContext} from './polyfill/polyfill-context'; // unified parameter APIs export { getParameters, setParameters, resetParameters, withParameters } from './state-tracker/unified-parameter-api'; // state tracking export { default as trackContextState, pushContextState, popContextState } from './state-tracker/track-context-state'; export { createGLContext, resizeGLContext, instrumentGLContext, getContextDebugInfo } from './context/context'; export {log, cssToDeviceRatio, cssToDevicePixels, isWebGL, isWebGL2} from './utils';
mit
spryker/demoshop
tests/PyzTest/Zed/CmsGui/_support/CmsGuiPresentationTester.php
3606
<?php /** * This file is part of the Spryker Demoshop. * For full license information, please view the LICENSE file that was distributed with this source code. */ namespace PyzTest\Zed\CmsGui; use Codeception\Actor; use Codeception\Scenario; /** * Inherited Methods * @method void wantToTest($text) * @method void wantTo($text) * @method void execute($callable) * @method void expectTo($prediction) * @method void expect($prediction) * @method void amGoingTo($argumentation) * @method void am($role) * @method void lookForwardTo($achieveValue) * @method void comment($description) * @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL) * * @SuppressWarnings(PHPMD) */ class CmsGuiPresentationTester extends Actor { use _generated\CmsGuiPresentationTesterActions; /** * @param \Codeception\Scenario $scenario */ public function __construct(Scenario $scenario) { parent::__construct($scenario); $this->amZed(); $this->amLoggedInUser(); } /** * @param string $date * * @return $this */ public function setValidFrom($date) { $this->fillField("//*[@id=\"cms_page_validFrom\"]", $date); return $this; } /** * @return $this */ public function setIsSearchable() { $this->checkOption('//*[@id="cms_page_isSearchable"]'); return $this; } /** * @param string $date * * @return $this */ public function setValidTo($date) { $this->fillField("//*[@id=\"cms_page_validTo\"]", $date); return $this; } /** * @param int $formIndex * @param string $name * @param string $url * * @return $this */ public function fillLocalizedUrlForm($formIndex, $name, $url) { $this->fillField('//*[@id="cms_page_pageAttributes_' . $formIndex . '_name"]', $name); $this->fillField('//*[@id="cms_page_pageAttributes_' . $formIndex . '_url"]', $url); return $this; } /** * @param int $placeHolderIndex * @param int $localeIndex * @param string $contents * * @return void */ public function fillPlaceholderContents($placeHolderIndex, $localeIndex, $contents) { $translationElementId = 'cms_glossary_glossaryAttributes_' . $placeHolderIndex . '_translations_' . $localeIndex . '_translation'; $this->executeJS("$('#$translationElementId').text('$contents');"); } /** * @return $this */ public function expandLocalizedUrlPane() { $this->click('//*[@id="tab-content-general"]/div/div[6]/div[1]/a'); return $this; } /** * @return $this */ public function clickSubmit() { $this->click('//*[@id="submit-cms"]'); return $this; } /** * @return $this */ public function clickPublishButton() { $this->click('//*[@id="page-wrapper"]/div[2]/div[2]/div/a[1]'); return $this; } /** * @return $this */ public function includeJquery() { $this->executeJS( ' var jq = document.createElement("script"); jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"; document.getElementsByTagName("head")[0].appendChild(jq); ' ); $this->wait(1); return $this; } /** * @return int */ public function grabCmsPageId() { return $this->grabFromCurrentUrl('/id-cms-page=(\d+)/'); } }
mit
atlascoinorg/atlas
share/qt/clean_mac_info_plist.py
891
#!/usr/bin/env python # Jonas Schnelli, 2013 # make sure the Atlas-Qt.app contains the right plist (including the right version) # fix made because of serval bugs in Qt mac deployment (https://bugreports.qt-project.org/browse/QTBUG-21267) from string import Template from datetime import date bitcoinDir = "./"; inFile = bitcoinDir+"/share/qt/Info.plist" outFile = "Atlas-Qt.app/Contents/Info.plist" version = "unknown"; fileForGrabbingVersion = bitcoinDir+"bitcoin-qt.pro" for line in open(fileForGrabbingVersion): lineArr = line.replace(" ", "").split("="); if lineArr[0].startswith("VERSION"): version = lineArr[1].replace("\n", ""); fIn = open(inFile, "r") fileContent = fIn.read() s = Template(fileContent) newFileContent = s.substitute(VERSION=version,YEAR=date.today().year) fOut = open(outFile, "w"); fOut.write(newFileContent); print "Info.plist fresh created"
mit
RoboAvatar65/ChessRobot
PlayerVsAi.py
5518
############################################################ ###PlayerVsAI.py Player vs computer file ### ###Written by Nicholas Maselli ### ### ### ###Purpose: Allows a player to play against a computer AI### ### ### ###Version: 1.0 ### ###Date: 6-30-17 ### ############################################################ from chess import Chess from algorithm import Algorithm import time import serial ###################################################### #####Code for playing the game against a computer##### ###################################################### def PlayerVsAI(startState, robot=False): chess = Chess() #Open Serial Port if (robot == True): port = open_port() while(True): player = input("Input Human Player's Color ('white' or 'black'): ") if (player == 'white'): computer = 'black' break elif (player == 'black'): computer = 'white' break else: print("Error incorrect color/n") print(); #Send player color information to Arduino when it is ready to recieve if (robot == True): ready = '' while(ready != 'R'): ready = arduino_ready(port) send_input(port, player) #Allows play from a specific state if (startState != None): chess.input_state() chess.print_board() #Max Recommended Difficulty: 5 layers. Averages around 15 seconds per move. layers = 5 algorithm = Algorithm(chess, computer, layers) #Play Chess! while(True): if (chess.state.turn == player): if (robot == True): serial_input = None move = recieve_input(port) move = chess.coordinate_to_notation(move) move = chess.convert_move(move) else: move = input('Input move: ') move = chess.convert_move(move) else: #Comments for move timing #start_time = time.time() move = algorithm.best_move() #end_time = time.time() #print("Move time: {}".format(end_time - start_time)) #If ChessBot is connected, send move via serial port if (robot == True): serial_input = chess.convert_serial_move(move) print_move = chess.convert_move(move) game = chess.move(move) if (robot == True and serial_input != None): send_input(port, serial_input) #Ensure game has not ended before if (game == None): print(print_move) chess.print_board() return(chess) elif (game == False): continue else: print(print_move) chess.print_board() return(chess) ######################################## ###### Robot Serial Port Functions ##### ######################################## def open_port(): #Open a serial port and test by writing a character ser = serial.Serial("COM3", 9600) return(ser) def send_input(port, move): #For python 3, need to convert from unicode string to bytes port_input = bytes(move, encoding="ascii") print(port_input) port.write(port_input) def arduino_ready(port): value = port.read(size=1) value = value.decode("ascii") return(value) def recieve_input(port): #Open a serial port and test by writing a character print("Starting Read") moves = 0 moveDetection = False while(True): value = port.read(size=1) value = value.decode("ascii") if (value == "x"): moveLimit = 2 value = port.read(size=1) value = int.from_bytes(value, byteorder='big') #Convert byte to int moveSquare = int(value) #print("Moving Square: ", end='') #print(value) value = port.read(size=1) value = int.from_bytes(value, byteorder='big') #Convert byte to int landingSquare = int(value) #print("Landing Square: ", end='') #print(value) move = convert_move(moveSquare, landingSquare) return(move) if (value == 'y'): moveLimit = 2 value = port.read(size=1) value = int.from_bytes(value, byteorder='big') #Convert byte to int moveSquare = int(value) print("Moving Square: ", end='') print(value) value = port.read(size=1) value = int.from_bytes(value, byteorder='big') #Convert byte to int landingSquare = int(value) print("Landing Square: ", end='') print(value) move = convert_move(moveSquare, landingSquare) return(move) if (value == 'z'): moveLimit = 2 value = port.read(size=1) value = int.from_bytes(value, byteorder='big') #Convert byte to int moveSquare = int(value) #print("Moving Square: ", end='') #print(value) value = port.read(size=1) value = int.from_bytes(value, byteorder='big') #Convert byte to int landingSquare = int(value) #print("Landing Square: ", end='') #print(value) move = convert_move(moveSquare, landingSquare) return(move) print(value, end='') def convert_move(moveSquare, landingSquare): yCurrent = int(moveSquare/8) xCurrent = int(moveSquare - 8*yCurrent) yCurrent = 7-yCurrent current = (yCurrent, xCurrent) yNew = int(landingSquare/8) xNew = int(landingSquare - 8*yNew) yNew = 7-yNew new = (yNew, xNew) move = (current, new) print(move) return(move) def main(): #Set robot to True if playing against a physical chess robot PlayerVsAI(startState = None, robot = True) main()
mit
msmith491/project-euler-rust
problem_26/src/main.rs
680
use std::collections::HashSet; fn main() { fn calc_sequence(numerator: usize, denominator: usize) -> usize { let mut seq: HashSet<usize> = HashSet::new(); let mut new_num = numerator; let mut length = 0; loop { if length >= denominator { break; } let mut remainder = new_num % denominator; new_num = remainder * 10; if seq.contains(&remainder) { break; } seq.insert(remainder); length += 1; } seq.len() + 1 } println!("{}", (0..1000).rev().map(|x| calc_sequence(1, x)).max().unwrap()); }
mit
googlestadia/pal
src/core/layers/dbgOverlay/dbgOverlayImage.cpp
2117
/* *********************************************************************************************************************** * * Copyright (c) 2015-2021 Advanced Micro Devices, Inc. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * **********************************************************************************************************************/ #include "core/layers/dbgOverlay/dbgOverlayDevice.h" #include "core/layers/dbgOverlay/dbgOverlayImage.h" namespace Pal { namespace DbgOverlay { // ===================================================================================================================== Image::Image( IImage* pNextImage, Device* pDevice, const ImageCreateInfo& createInfo) : ImageDecorator(pNextImage, pDevice), m_createInfo(createInfo), m_pBoundMemObj(nullptr), m_boundMemOffset(0) { } // ===================================================================================================================== Image::~Image() { } } // DbgOverlay } // Pal
mit
ignaciocases/hermeneumatics
node_modules/scala-node/main/target/streams/compile/externalDependencyClasspath/$global/package-js/extracted-jars/scalajs-library_2.10-0.4.0.jar--29fb2f8b/scala/io/BytePickle$Ref$.js
3107
/** @constructor */ ScalaJS.c.scala_io_BytePickle$Ref$ = (function() { ScalaJS.c.scala_runtime_AbstractFunction0.call(this) }); ScalaJS.c.scala_io_BytePickle$Ref$.prototype = new ScalaJS.inheritable.scala_runtime_AbstractFunction0(); ScalaJS.c.scala_io_BytePickle$Ref$.prototype.constructor = ScalaJS.c.scala_io_BytePickle$Ref$; ScalaJS.c.scala_io_BytePickle$Ref$.prototype.toString__T = (function() { return "Ref" }); ScalaJS.c.scala_io_BytePickle$Ref$.prototype.apply__Lscala_io_BytePickle$Ref = (function() { return new ScalaJS.c.scala_io_BytePickle$Ref().init___() }); ScalaJS.c.scala_io_BytePickle$Ref$.prototype.unapply__Lscala_io_BytePickle$Ref__Z = (function(x$0) { if (ScalaJS.anyRefEqEq(x$0, null)) { return false } else { return true } }); ScalaJS.c.scala_io_BytePickle$Ref$.prototype.readResolve__p2__O = (function() { return ScalaJS.modules.scala_io_BytePickle$Ref() }); ScalaJS.c.scala_io_BytePickle$Ref$.prototype.apply__O = (function() { return this.apply__Lscala_io_BytePickle$Ref() }); ScalaJS.c.scala_io_BytePickle$Ref$.prototype.unapply__Lscala_io_BytePickle$Ref__ = (function(x$0) { return ScalaJS.bZ(this.unapply__Lscala_io_BytePickle$Ref__Z(x$0)) }); /** @constructor */ ScalaJS.inheritable.scala_io_BytePickle$Ref$ = (function() { /*<skip>*/ }); ScalaJS.inheritable.scala_io_BytePickle$Ref$.prototype = ScalaJS.c.scala_io_BytePickle$Ref$.prototype; ScalaJS.is.scala_io_BytePickle$Ref$ = (function(obj) { return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_io_BytePickle$Ref$))) }); ScalaJS.as.scala_io_BytePickle$Ref$ = (function(obj) { if ((ScalaJS.is.scala_io_BytePickle$Ref$(obj) || (obj === null))) { return obj } else { ScalaJS.throwClassCastException(obj, "scala.io.BytePickle$Ref") } }); ScalaJS.isArrayOf.scala_io_BytePickle$Ref$ = (function(obj, depth) { return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_io_BytePickle$Ref$))) }); ScalaJS.asArrayOf.scala_io_BytePickle$Ref$ = (function(obj, depth) { if ((ScalaJS.isArrayOf.scala_io_BytePickle$Ref$(obj, depth) || (obj === null))) { return obj } else { ScalaJS.throwArrayCastException(obj, "Lscala.io.BytePickle$Ref;", depth) } }); ScalaJS.data.scala_io_BytePickle$Ref$ = new ScalaJS.ClassTypeData({ scala_io_BytePickle$Ref$: 0 }, false, "scala.io.BytePickle$Ref$", ScalaJS.data.scala_runtime_AbstractFunction0, { scala_io_BytePickle$Ref$: 1, scala_Serializable: 1, java_io_Serializable: 1, scala_runtime_AbstractFunction0: 1, scala_Function0: 1, java_lang_Object: 1 }); ScalaJS.c.scala_io_BytePickle$Ref$.prototype.$classData = ScalaJS.data.scala_io_BytePickle$Ref$; ScalaJS.moduleInstances.scala_io_BytePickle$Ref = undefined; ScalaJS.modules.scala_io_BytePickle$Ref = (function() { if ((!ScalaJS.moduleInstances.scala_io_BytePickle$Ref)) { ScalaJS.moduleInstances.scala_io_BytePickle$Ref = new ScalaJS.c.scala_io_BytePickle$Ref$().init___() }; return ScalaJS.moduleInstances.scala_io_BytePickle$Ref }); //@ sourceMappingURL=BytePickle$Ref$.js.map
mit
Cendey/schema
scheme/src/main/java/edu/mit/lab/meta/Keys.java
7225
package edu.mit.lab.meta; import edu.mit.lab.constant.Scheme; import edu.mit.lab.infts.IRelevance; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.reflections.ReflectionUtils; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Set; /** * <p>Title: Kewill Lab Center</p> * <p>Description: edu.mit.lab.meta.Keys</p> * <p>Copyright: Copyright (c) 2016</p> * <p>Company: Kewill Co., Ltd.</p> * * @author <[email protected]> * @version 1.0 * @since 11/14/2016 */ public class Keys implements IRelevance<String, List<String>>, Comparator { private String pkTableName; private List<String> pkColumnName; private String fkTableName; private List<String> fkColumnName; private Short keySequence; public String getPkTableName() { return pkTableName; } public void setPkTableName(String pkTableName) { this.pkTableName = pkTableName; } @SuppressWarnings(value = {"WeakerAccess"}) public List<String> getPkColumnName() { return pkColumnName; } public void setPkColumnName(List<String> pkColumnName) { this.pkColumnName = pkColumnName; } public void setFkColumnName(List<String> fkColumnName) { this.fkColumnName = fkColumnName; } public void addPkColumnName(String pkColumnName) { if (this.pkColumnName == null) { this.pkColumnName = new ArrayList<>(); } this.pkColumnName.add(pkColumnName); } public String getFkTableName() { return fkTableName; } public void setFkTableName(String fkTableName) { this.fkTableName = fkTableName; } @SuppressWarnings(value = {"WeakerAccess"}) public List<String> getFkColumnName() { return fkColumnName; } public void addFkColumnName(String fkColumnName) { if (this.fkColumnName == null) { this.fkColumnName = new ArrayList<>(); } this.fkColumnName.add(fkColumnName); } public Short getKeySequence() { return keySequence; } public void setKeySequence(Short keySequence) { this.keySequence = keySequence; } @Override public String toString() { StringBuilder item = new StringBuilder("Keys{"); if (StringUtils.isNotEmpty(pkTableName)) { item.append(Scheme.PK_TABLE_NAME + "='").append(pkTableName).append('\''); } if (CollectionUtils.isNotEmpty(pkColumnName)) { formatColumnName(item, pkColumnName, Scheme.PK_COLUMN_NAME); } if (StringUtils.isNotEmpty(fkTableName)) { item.append(", ").append(Scheme.FK_TABLE_NAME).append("='").append(fkTableName).append('\''); } if (CollectionUtils.isNotEmpty(fkColumnName)) { formatColumnName(item, fkColumnName, Scheme.FK_COLUMN_NAME); } if (keySequence != null) { item.append(", ").append(Scheme.KEY_SEQUENCE).append("='").append(keySequence).append('\''); } item.append('}'); int position = item.indexOf("{") + 1; if (StringUtils.startsWith(item.substring(position), ",")) { item.replace(position, position + 2, ""); } return item.toString(); } private void formatColumnName(StringBuilder item, List<String> lstColumnNames, String columnName) { item.append(", ").append(columnName).append("="); if (lstColumnNames.size() == 1) { item.append("'").append(lstColumnNames.get(0)).append("'"); } else { item.append("{'").append(lstColumnNames.get(0)); for (int index = 1; index < lstColumnNames.size(); index++) { item.append("', '").append(lstColumnNames.get(index)); } item.append("'}"); } } @Override public int compare(Object o1, Object o2) { if (o1 instanceof Keys && o2 instanceof Keys) { if (o1.equals(o2)) return 0; else { Keys one = Keys.class.cast(o1); Keys another = Keys.class.cast(o2); int result = one.getPkTableName().compareTo(another.getPkTableName()); if (result != 0) return result; else { int temp = one.getFkTableName().compareTo(another.getFkTableName()); if (temp != 0) return temp; else { return String.valueOf(one.getFkColumnName()) .compareTo(String.valueOf(another.getFkColumnName())); } } } } throw new IncompatibleClassChangeError( o1.getClass().toGenericString() + " vs " + o2.getClass().toGenericString()); } @Override public int hashCode() { return getPkTableName().hashCode() * 3 + getPkColumnName().hashCode() * 7 + getFkTableName().hashCode() * 11 + getFkColumnName().hashCode() * 13 + getKeySequence() * 17; } public boolean equals(Object obj) { if (obj instanceof Keys) { Keys meta = this.getClass().cast(obj); return getPkTableName().equals(meta.getPkTableName()) && getPkColumnName().equals(meta.getPkColumnName()) && getFkTableName().equals(meta.getFkTableName()) && getFkColumnName().equals(meta.getFkColumnName()) && getKeySequence().shortValue() == meta.getKeySequence().shortValue(); } else { return false; } } @Override public String from() { return fkTableName; } @Override public String to() { return pkTableName; } /** * Get field value from this * * @param name get name * @return this instance value of get name * @link https://github.com/ronmamo/reflections */ @Override @SuppressWarnings(value = {"unchecked"}) public List<String> get(String name) { List<String> attribute = new ArrayList<>(); Set<Method> getter = ReflectionUtils .getAllMethods(getClass(), ReflectionUtils.withModifier(Modifier.PUBLIC), ReflectionUtils.withPrefix("get"), ReflectionUtils.withParametersCount(0)); getter.stream().filter(method -> { method.setAccessible(true); return method.getName().toUpperCase().contains(StringUtils.upperCase(name)); }).findAny().ifPresent(method -> { try { Object value = method.invoke(this); if (List.class.isAssignableFrom(value.getClass())) { attribute.addAll(List.class.cast(value)); } else { attribute.add(String.valueOf(value)); } } catch (IllegalAccessException | InvocationTargetException e) { System.err.println(e.getMessage()); } }); return attribute; } @Override public void set(String item) { addFkColumnName(item); } }
mit
lyuboasenov/scheduler
packages/AForge.NET Framework-2.2.5/Unit Tests/AForge.Math.Tests/Geometry/SimpleShapeCheckerTest.cs
14837
using System; using System.Collections.Generic; using AForge; using AForge.Math.Geometry; using MbUnit.Framework; namespace AForge.Math.Geometry.Tests { [TestFixture] public class SimpleShapeCheckerTest { private SimpleShapeChecker shapeChecker = new SimpleShapeChecker( ); private List<IntPoint> idealCicle = new List<IntPoint>( ); private List<IntPoint> distorredCircle = new List<IntPoint>( ); private List<IntPoint> square1 = new List<IntPoint>( ); private List<IntPoint> square1Test = new List<IntPoint>( ); private List<IntPoint> square2 = new List<IntPoint>( ); private List<IntPoint> square2Test = new List<IntPoint>( ); private List<IntPoint> square3 = new List<IntPoint>( ); private List<IntPoint> rectangle = new List<IntPoint>( ); private List<IntPoint> triangle1 = new List<IntPoint>( ); private List<IntPoint> isoscelesTriangle = new List<IntPoint>( ); private List<IntPoint> equilateralTriangle = new List<IntPoint>( ); private List<IntPoint> rectangledTriangle = new List<IntPoint>( ); public SimpleShapeCheckerTest( ) { System.Random rand = new System.Random( ); // generate sample circles double radius = 100; for ( int i = 0; i < 360; i += 10 ) { double angle = (double) i / 180 * System.Math.PI; // add point to ideal circle idealCicle.Add( new IntPoint( (int) ( radius * System.Math.Cos( angle ) ), (int) ( radius * System.Math.Sin( angle ) ) ) ); // add a bit distortion for distorred cirlce double distorredRadius = radius + rand.Next( 7 ) - 3; distorredCircle.Add( new IntPoint( (int) ( distorredRadius * System.Math.Cos( angle ) ), (int) ( distorredRadius * System.Math.Sin( angle ) ) ) ); } // generate sample squares square1.Add( new IntPoint( 0, 0 ) ); square1.Add( new IntPoint( 50, 0 ) ); square1.Add( new IntPoint( 100, 0 ) ); square1.Add( new IntPoint( 100, 50 ) ); square1.Add( new IntPoint( 100, 100 ) ); square1.Add( new IntPoint( 50, 100 ) ); square1.Add( new IntPoint( 0, 100 ) ); square1.Add( new IntPoint( 0, 50 ) ); square2.Add( new IntPoint( 50, 0 ) ); square2.Add( new IntPoint( 75, 25 ) ); square2.Add( new IntPoint( 100, 50 ) ); square2.Add( new IntPoint( 75, 75 ) ); square2.Add( new IntPoint( 50, 100 ) ); square2.Add( new IntPoint( 25, 75 ) ); square2.Add( new IntPoint( 0, 50 ) ); square2.Add( new IntPoint( 25, 25 ) ); // these should be obtained as corners square1Test.Add( new IntPoint( 0, 0 ) ); square1Test.Add( new IntPoint( 100, 0 ) ); square1Test.Add( new IntPoint( 100, 100 ) ); square1Test.Add( new IntPoint( 0, 100 ) ); square2Test.Add( new IntPoint( 50, 0 ) ); square2Test.Add( new IntPoint( 100, 50 ) ); square2Test.Add( new IntPoint( 50, 100 ) ); square2Test.Add( new IntPoint( 0, 50 ) ); // special square, which may look like circle, but should be recognized as circle square3.Add( new IntPoint( 50, 0 ) ); square3.Add( new IntPoint( 100, 50 ) ); square3.Add( new IntPoint( 50, 100 ) ); square3.Add( new IntPoint( 0, 50 ) ); // generate sample rectangle rectangle.Add( new IntPoint( 0, 0 ) ); rectangle.Add( new IntPoint( 50, 0 ) ); rectangle.Add( new IntPoint( 100, 0 ) ); rectangle.Add( new IntPoint( 100, 20 ) ); rectangle.Add( new IntPoint( 100, 40 ) ); rectangle.Add( new IntPoint( 50, 40 ) ); rectangle.Add( new IntPoint( 0, 40 ) ); rectangle.Add( new IntPoint( 0, 20 ) ); // generate some triangles triangle1.Add( new IntPoint( 0, 0 ) ); triangle1.Add( new IntPoint( 50, 10 ) ); triangle1.Add( new IntPoint( 100, 20 ) ); triangle1.Add( new IntPoint( 90, 50 ) ); triangle1.Add( new IntPoint( 80, 80 ) ); triangle1.Add( new IntPoint( 40, 40 ) ); isoscelesTriangle.Add( new IntPoint( 0, 0 ) ); isoscelesTriangle.Add( new IntPoint( 50, 0 ) ); isoscelesTriangle.Add( new IntPoint( 100, 0 ) ); isoscelesTriangle.Add( new IntPoint( 75, 20 ) ); isoscelesTriangle.Add( new IntPoint( 50, 40 ) ); isoscelesTriangle.Add( new IntPoint( 25, 20 ) ); equilateralTriangle.Add( new IntPoint( 0, 0 ) ); equilateralTriangle.Add( new IntPoint( 50, 0 ) ); equilateralTriangle.Add( new IntPoint( 100, 0 ) ); equilateralTriangle.Add( new IntPoint( 75, 43 ) ); equilateralTriangle.Add( new IntPoint( 50, 86 ) ); equilateralTriangle.Add( new IntPoint( 25, 43 ) ); rectangledTriangle.Add( new IntPoint( 0, 0 ) ); rectangledTriangle.Add( new IntPoint( 20, 0 ) ); rectangledTriangle.Add( new IntPoint( 40, 0 ) ); rectangledTriangle.Add( new IntPoint( 20, 50 ) ); rectangledTriangle.Add( new IntPoint( 0, 100 ) ); rectangledTriangle.Add( new IntPoint( 0, 50 ) ); } [Test] public void IsCircleTest( ) { Assert.AreEqual( true, shapeChecker.IsCircle( idealCicle ) ); Assert.AreEqual( true, shapeChecker.IsCircle( distorredCircle ) ); Assert.AreEqual( false, shapeChecker.IsCircle( square1 ) ); Assert.AreEqual( false, shapeChecker.IsCircle( square2 ) ); Assert.AreEqual( false, shapeChecker.IsCircle( square3 ) ); Assert.AreEqual( false, shapeChecker.IsCircle( rectangle ) ); Assert.AreEqual( false, shapeChecker.IsCircle( triangle1 ) ); Assert.AreEqual( false, shapeChecker.IsCircle( equilateralTriangle ) ); Assert.AreEqual( false, shapeChecker.IsCircle( isoscelesTriangle ) ); Assert.AreEqual( false, shapeChecker.IsCircle( rectangledTriangle ) ); } [Test] public void IsQuadrilateralTest( ) { Assert.AreEqual( true, shapeChecker.IsQuadrilateral( square1 ) ); Assert.AreEqual( true, shapeChecker.IsQuadrilateral( square2 ) ); Assert.AreEqual( true, shapeChecker.IsQuadrilateral( square3 ) ); Assert.AreEqual( true, shapeChecker.IsQuadrilateral( rectangle ) ); Assert.AreEqual( false, shapeChecker.IsQuadrilateral( idealCicle ) ); Assert.AreEqual( false, shapeChecker.IsQuadrilateral( distorredCircle ) ); Assert.AreEqual( false, shapeChecker.IsQuadrilateral( triangle1 ) ); Assert.AreEqual( false, shapeChecker.IsQuadrilateral( equilateralTriangle ) ); Assert.AreEqual( false, shapeChecker.IsQuadrilateral( isoscelesTriangle ) ); Assert.AreEqual( false, shapeChecker.IsQuadrilateral( rectangledTriangle ) ); } [Test] public void CheckQuadrilateralCornersTest( ) { List<IntPoint> corners; Assert.AreEqual( true, shapeChecker.IsQuadrilateral( square1, out corners ) ); Assert.AreEqual( 4, corners.Count ); Assert.AreEqual( true, CompareShape( corners, square1Test ) ); Assert.AreEqual( true, shapeChecker.IsQuadrilateral( square2, out corners ) ); Assert.AreEqual( 4, corners.Count ); Assert.AreEqual( true, CompareShape( corners, square2Test ) ); } [Test] public void IsTriangleTest( ) { Assert.AreEqual( true, shapeChecker.IsTriangle( triangle1 ) ); Assert.AreEqual( true, shapeChecker.IsTriangle( equilateralTriangle ) ); Assert.AreEqual( true, shapeChecker.IsTriangle( isoscelesTriangle ) ); Assert.AreEqual( true, shapeChecker.IsTriangle( rectangledTriangle ) ); Assert.AreEqual( false, shapeChecker.IsTriangle( idealCicle ) ); Assert.AreEqual( false, shapeChecker.IsTriangle( distorredCircle ) ); Assert.AreEqual( false, shapeChecker.IsTriangle( square1 ) ); Assert.AreEqual( false, shapeChecker.IsTriangle( square2 ) ); Assert.AreEqual( false, shapeChecker.IsTriangle( square3 ) ); Assert.AreEqual( false, shapeChecker.IsTriangle( rectangle ) ); } [Test] public void IsConvexPolygon( ) { List<IntPoint> corners; Assert.AreEqual( true, shapeChecker.IsConvexPolygon( triangle1, out corners ) ); Assert.AreEqual( 3, corners.Count ); Assert.AreEqual( true, shapeChecker.IsConvexPolygon( equilateralTriangle, out corners ) ); Assert.AreEqual( 3, corners.Count ); Assert.AreEqual( true, shapeChecker.IsConvexPolygon( isoscelesTriangle, out corners ) ); Assert.AreEqual( 3, corners.Count ); Assert.AreEqual( true, shapeChecker.IsConvexPolygon( rectangledTriangle, out corners ) ); Assert.AreEqual( 3, corners.Count ); Assert.AreEqual( true, shapeChecker.IsConvexPolygon( square1, out corners ) ); Assert.AreEqual( 4, corners.Count ); Assert.AreEqual( true, shapeChecker.IsConvexPolygon( square2, out corners ) ); Assert.AreEqual( 4, corners.Count ); Assert.AreEqual( true, shapeChecker.IsConvexPolygon( square3, out corners ) ); Assert.AreEqual( 4, corners.Count ); Assert.AreEqual( true, shapeChecker.IsConvexPolygon( rectangle, out corners ) ); Assert.AreEqual( 4, corners.Count ); Assert.AreEqual( false, shapeChecker.IsConvexPolygon( idealCicle, out corners ) ); Assert.AreEqual( false, shapeChecker.IsConvexPolygon( distorredCircle, out corners ) ); } [Test] public void CheckShapeTypeTest( ) { Assert.AreEqual( ShapeType.Circle, shapeChecker.CheckShapeType( idealCicle ) ); Assert.AreEqual( ShapeType.Circle, shapeChecker.CheckShapeType( distorredCircle ) ); Assert.AreEqual( ShapeType.Quadrilateral, shapeChecker.CheckShapeType( square1 ) ); Assert.AreEqual( ShapeType.Quadrilateral, shapeChecker.CheckShapeType( square2 ) ); Assert.AreEqual( ShapeType.Quadrilateral, shapeChecker.CheckShapeType( square3 ) ); Assert.AreEqual( ShapeType.Quadrilateral, shapeChecker.CheckShapeType( rectangle ) ); Assert.AreEqual( ShapeType.Triangle, shapeChecker.CheckShapeType( triangle1 ) ); Assert.AreEqual( ShapeType.Triangle, shapeChecker.CheckShapeType( equilateralTriangle ) ); Assert.AreEqual( ShapeType.Triangle, shapeChecker.CheckShapeType( isoscelesTriangle ) ); Assert.AreEqual( ShapeType.Triangle, shapeChecker.CheckShapeType( rectangledTriangle ) ); } private bool CompareShape( List<IntPoint> shape1, List<IntPoint> shape2 ) { if ( shape1.Count != shape2.Count ) return false; if ( shape1.Count == 0 ) return true; int index = shape1.IndexOf( shape2[0] ); if ( index == -1 ) return false; index++; for ( int i = 1; i < shape2.Count; i++, index++ ) { if ( index >= shape1.Count ) index = 0; if ( !shape1[index].Equals( shape2[i] ) ) return false; } return true; } [Test] [Row( PolygonSubType.Unknown, new int[] { 0, 0, 100, 0, 90, 10 } )] // just a triangle [Row( PolygonSubType.IsoscelesTriangle, new int[] { 0, 0, 100, 0, 50, 10 } )] [Row( PolygonSubType.IsoscelesTriangle, new int[] { 0, 0, 100, 0, 50, 200 } )] [Row( PolygonSubType.EquilateralTriangle, new int[] { 0, 0, 100, 0, 50, 86 } )] [Row( PolygonSubType.RectangledIsoscelesTriangle, new int[] { 0, 0, 100, 0, 50, 50 } )] [Row( PolygonSubType.RectangledIsoscelesTriangle, new int[] { 0, 0, 100, 0, 0, 100 } )] [Row( PolygonSubType.RectangledTriangle, new int[] { 0, 0, 100, 0, 0, 50 } )] [Row( PolygonSubType.Unknown, new int[] { 0, 0, 100, 0, 90, 50, 10, 70 } )] // just a quadrilateral [Row( PolygonSubType.Trapezoid, new int[] { 0, 0, 100, 0, 90, 50, 10, 50 } )] [Row( PolygonSubType.Trapezoid, new int[] { 0, 0, 100, 0, 90, 50, 0, 50 } )] [Row( PolygonSubType.Trapezoid, new int[] { 0, 0, 100, 0, 90, 50, 0, 53 } )] // a bit disformed [Row( PolygonSubType.Parallelogram, new int[] { 0, 0, 100, 0, 120, 50, 20, 50 } )] [Row( PolygonSubType.Parallelogram, new int[] { 0, 0, 100, 0, 70, 50, -30, 50 } )] [Row( PolygonSubType.Rectangle, new int[] { 0, 0, 100, 0, 100, 50, 0, 50 } )] [Row( PolygonSubType.Rectangle, new int[] { 0, 0, 100, 0, 100, 52, -3, 50 } )] // a bit disformed [Row( PolygonSubType.Square, new int[] { 0, 0, 100, 0, 100, 100, 0, 100 } )] [Row( PolygonSubType.Square, new int[] { 50, 0, 100, 50, 50, 100, 0, 50 } )] [Row( PolygonSubType.Square, new int[] { 51, 0, 100, 49, 50, 101, 1, 50 } )] // a bit disformed [Row( PolygonSubType.Rhombus, new int[] { 30, 0, 60, 50, 30, 100, 0, 50 } )] [Row( PolygonSubType.Rhombus, new int[] { 0, 0, 100, 0, 130, 95, 30, 95 } )] [Row( PolygonSubType.Unknown, new int[] { 0, 0, 100, 0, 90, 50, 40, 70, 10, 40 } )] // unknown if 5 corners or more public void CheckPolygonSubTypeTest( PolygonSubType expectedSubType, int[] corners ) { Assert.AreEqual( expectedSubType, shapeChecker.CheckPolygonSubType( GetListOfPointFromArray( corners ) ) ); } private List<IntPoint> GetListOfPointFromArray( int[] points ) { List<IntPoint> list = new List<IntPoint>( ); for ( int i = 0, n = points.Length; i < n; i += 2 ) { list.Add( new IntPoint( points[i], points[i + 1] ) ); } return list; } } }
mit
synaq/SynaqZasaBundle
DependencyInjection/Configuration.php
1484
<?php namespace Synaq\ZasaBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('synaq_zasa'); $rootNode ->children() ->scalarNode('server') ->cannotBeEmpty() ->end() ->scalarNode('admin_user') ->cannotBeEmpty() ->end() ->scalarNode('admin_pass') ->cannotBeEmpty() ->end() ->scalarNode('use_fopen') ->defaultTrue() ->end() ->scalarNode('auth_token_path') ->defaultNull() ->end() ->scalarNode('rest_base_url') ->defaultNull() ->end() ->scalarNode('auth_propagation_time') ->defaultValue(0) ->end() ->scalarNode('ignore_delegated_auth') ->defaultFalse() ->end() ->end(); return $treeBuilder; } }
mit
VizArtJS/vizart-basic
src/axis/is-tick-div.js
95
const isTickDiv = (data, units) => (data.length - 1) % units === 0; export default isTickDiv;
mit
ajlopez/SimpleMongo
test/findOne.js
1873
var collections = require('../lib/collections'); exports['null in empty collection'] = function (test) { var collection = collections.createCollection('people'); var doc = collection.findOne(); test.equal(doc, null); } exports['find one document'] = function (test) { var collection = collections.createCollection('people'); var adam = { name: 'Adam' }; collection.insert(adam); var doc = collection.findOne(); test.ok(doc); test.equal(doc._id, adam._id); test.equal(doc.name, adam.name); } exports['find one documents with empty query'] = function (test) { var collection = collections.createCollection('people'); var adam = { name: 'Adam', age: 800 }; collection.insert(adam); var eve = { name: 'Eve', age: 700 }; collection.insert(eve); var doc = collection.findOne({ }); test.ok(doc); test.equal(doc._id, adam._id); test.equal(doc.name, adam.name); test.equal(doc.age, adam.age); } exports['find one document with projection'] = function (test) { var collection = collections.createCollection('people'); var adam = { name: 'Adam', age: 800 }; collection.insert(adam); var eve = { name: 'Eve', age: 700 }; collection.insert(eve); var doc = collection.findOne({ }, { name: true }); test.ok(doc); test.equal(doc._id, adam._id); test.equal(doc.name, adam.name); test.ok(doc.age === undefined); } exports['find one with query by example'] = function (test) { var collection = collections.createCollection('people'); var adam = { name: 'Adam' }; collection.insert(adam); var eve = { name: 'Eve' }; collection.insert(eve); var doc = collection.findOne({ name: 'Eve' }); test.ok(doc); test.equal(doc._id, eve._id); test.equal(doc.name, "Eve"); }
mit
gabrieldodan/php-dancer
system/libraries/SwiftMailer/lib/classes/Swift/Transport/SimpleMailInvoker.php
1553
<?php /* Invokes the mail() function in Swift Mailer. This program 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. This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ /** * This is the implementation class for {@link Swift_Transport_MailInvoker}. * * @package Swift * @subpackage Transport * @author Chris Corbyn */ class Swift_Transport_SimpleMailInvoker implements Swift_Transport_MailInvoker { /** * Send mail via the mail() function. * * This method takes the same arguments as PHP mail(). * * @param string $to * @param string $subject * @param string $body * @param string $headers * @param string $extraParams * * @return boolean */ public function mail($to, $subject, $body, $headers = null, $extraParams = null) { if (!ini_get('safe_mode')) { return mail($to, $subject, $body, $headers, $extraParams); } else { return mail($to, $subject, $body, $headers); } } }
mit
SPDEVGUY/Multi-device-network-controller
NetworkController.Server.Logic/Broadcaster.cs
6428
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using NetworkController.Logic.Controller; using NetworkController.Logic.Plugin.Interfaces; using NetworkController.Server.Logic.Communicators; namespace NetworkController.Server.Logic { public class Broadcaster : IDisposable { private IPacketBroadcaster _communicator; private BroadcasterTypeEnum _communicationType; private int _broadcastPort = 9050; private List<Exception> _exceptions = new List<Exception>(); private InputDeltaObserver _observer; private int _updateTick = 100; private bool _isRunning = false; private Thread _updateThread; public event EventHandler DriversReady; public bool IsBroadcasting { get { return _communicator != null && _communicator.IsBroadcasting; } } public long PacketsSent { get { return _communicator == null ? 0 : _communicator.PacketsSent; } } public long PacketVolumeSent { get { return _communicator == null ? 0 : _communicator.PacketVolumeSent; } } public string LastBroadcastData { get { return _communicator == null ? "" : _communicator.LastBroadcastData; } } public int BroadcastPort { get { return _broadcastPort; } set { _broadcastPort = value; } } public BroadcasterTypeEnum BroadcastType { get { return _communicationType; } set { _communicationType = value; } } public int UpdateTick { get { lock (this) return _updateTick; } set { lock (this) _updateTick = Math.Max(value,1); } } public double VelocityRetentionFactor { get { lock (this) { if (_observer != null && !_observer.IsDisposed) return _observer.VelocityRetentionFactor; } return -1; } set { lock (this) { if (_observer != null && !_observer.IsDisposed) _observer.VelocityRetentionFactor = value; } } } public string LoadedPlugins { get { lock (this) { if (_observer != null && !_observer.IsDisposed) return _observer.GetProviderList(); return ""; } } } protected IPacketBroadcaster StartCommunicator() { if (_communicator != null) throw new NotSupportedException("Can't start while already started."); switch (_communicationType) { case BroadcasterTypeEnum.UDP: _communicator = new UdpPacketBroadcaster(); break; case BroadcasterTypeEnum.TCP: //TODO: _communicator = new TcpBroadcaster(); throw new NotSupportedException("TCP Not yet supported."); break; default: throw new NotSupportedException("Developer laziness not yet supported."); } _communicator.BroadcastPort = _broadcastPort; _communicator.Start(); return _communicator; } public void Dispose() { if (_isRunning) { Stop(); } } public void Stop() { _isRunning = false; Thread.Sleep(10); } public void Start() { if (_isRunning) return; _isRunning = true; _updateThread = new Thread(BroadcastingThreadMethod) { Name = "Broadcaster Update Thread", IsBackground = true}; _updateThread.Start(); } public List<Exception> PopExceptions() { lock (this) { var result = _exceptions.ToList(); _exceptions.Clear(); return result; }} private void BroadcastingThreadMethod() { try { using (_observer = new InputDeltaObserver()) { using (StartCommunicator()) { _observer.StartCapturing(); LogExceptions(_observer.ProcessingExceptions); _communicator.Start(); OnDriversReady(); while (_isRunning) { lock (this) { _observer.UpdateTick(); LogExceptions(_observer.ProcessingExceptions); if (_observer.DirtiedDeltas.Count > 0) { //Filter dirtied deltas //TODO //Serialize and send var dirtied = _observer.SerializeDirtied(); _communicator.Broadcast(dirtied); } } Thread.Sleep(_updateTick); } _communicator.Stop(); _communicator.Dispose(); _communicator = null; } _observer.StopCapturing(); _observer.Dispose(); LogExceptions(_observer.ProcessingExceptions); } } catch (Exception ex) { LogException(ex); } } private void LogException(Exception ex) { lock (this) _exceptions.Add(ex); } private void LogExceptions(List<Exception> ex) { lock (this) _exceptions.AddRange(ex); } public List<IDriverAbstracter> GetDrivers() { if (_observer == null) return null; return _observer.Drivers; } protected void OnDriversReady() { if (DriversReady != null) DriversReady(this,null); } } }
mit
Leviyu/Maligaro
cpp_lib/01_cpp_lib/tx2011.cpp
6143
#include "hongyulibcpp.h" /************************************************************* * This C function is a 1D reference earth model for TX2011 tomography * INPUT * double depth; * * OUTPUT * double* vs * * Hongyu DATE: June 20 2014 * Key words: prem vs vp out *************************************************************/ double tx2011(double DEPTH) { //printf("input depth is %lf \n",DEPTH); if(DEPTH <0 || DEPTH > 6370) puts("ERROR in TX2011 ref, depth is negative or is greater then 6370km"); double result; int line_num = 298; //read in reference double depth[500] = { 0.0 , 3.5 , 4.0 , 34.0 , 36.0 , 60.0 , 75.0 , 100.0 , 125.0 , 150.0 , 175.0 , 200.0 , 225.0 , 250.0 , 275.0 , 300.0 , 325.0 , 350.0 , 375.0 , 395.0 , 414.0 , 416.0 , 425.0 , 450.0 , 475.0 , 500.0 , 525.0 , 550.0 , 575.0 , 600.0 , 625.0 , 645.0 , 654.0 , 656.0 , 675.0 , 700.0 , 725.0 , 750.0 , 775.0 , 800.0 , 825.0 , 850.0 , 875.0 , 900.0 , 925.0 , 950.0 , 975.0 , 1000.0 , 1025.0 , 1050.0 , 1075.0 , 1100.0 , 1125.0 , 1150.0 , 1162.5 , 1175.0 , 1187.5 , 1200.0 , 1212.5 , 1225.0 , 1237.5 , 1250.0 , 1262.5 , 1275.0 , 1287.5 , 1300.0 , 1312.5 , 1325.0 , 1337.5 , 1350.0 , 1362.5 , 1375.0 , 1387.5 , 1400.0 , 1412.5 , 1425.0 , 1437.5 , 1450.0 , 1462.5 , 1475.0 , 1487.5 , 1500.0 , 1512.5 , 1525.0 , 1537.5 , 1550.0 , 1562.5 , 1575.0 , 1587.5 , 1600.0 , 1612.5 , 1625.0 , 1637.5 , 1650.0 , 1662.5 , 1675.0 , 1687.5 , 1700.0 , 1712.5 , 1725.0 , 1737.5 , 1750.0 , 1762.5 , 1775.0 , 1787.5 , 1800.0 , 1812.5 , 1825.0 , 1837.5 , 1850.0 , 1862.5 , 1875.0 , 1887.5 , 1900.0 , 1912.5 , 1925.0 , 1937.5 , 1950.0 , 1962.5 , 1975.0 , 1987.5 , 2000.0 , 2012.5 , 2025.0 , 2037.5 , 2050.0 , 2062.5 , 2075.0 , 2087.5 , 2100.0 , 2112.5 , 2125.0 , 2137.5 , 2150.0 , 2162.5 , 2175.0 , 2187.5 , 2200.0 , 2212.5 , 2225.0 , 2237.5 , 2250.0 , 2262.5 , 2275.0 , 2287.5 , 2300.0 , 2312.5 , 2325.0 , 2337.5 , 2350.0 , 2362.5 , 2375.0 , 2387.5 , 2400.0 , 2412.5 , 2425.0 , 2437.5 , 2450.0 , 2462.5 , 2475.0 , 2487.5 , 2500.0 , 2512.5 , 2525.0 , 2537.5 , 2550.0 , 2562.5 , 2575.0 , 2587.5 , 2600.0 , 2612.5 , 2625.0 , 2637.5 , 2650.0 , 2662.5 , 2675.0 , 2687.5 , 2700.0 , 2712.5 , 2725.0 , 2737.5 , 2750.0 , 2762.5 , 2775.0 , 2787.5 , 2800.0 , 2811.4 , 2822.8 , 2834.1 , 2845.5 , 2856.9 , 2868.2 , 2879.6 , 2891.0 , 2891.1 , 2911.0 , 2931.0 , 2951.0 , 2971.0 , 2996.0 , 3021.0 , 3046.0 , 3071.0 , 3096.0 , 3121.0 , 3146.0 , 3171.0 , 3196.0 , 3221.0 , 3246.0 , 3271.0 , 3296.0 , 3321.0 , 3346.0 , 3371.0 , 3396.0 , 3421.0 , 3446.0 , 3471.0 , 3496.0 , 3521.0 , 3546.0 , 3571.0 , 3596.0 , 3621.0 , 3646.0 , 3671.0 , 3696.0 , 3721.0 , 3746.0 , 3771.0 , 3796.0 , 3821.0 , 3846.0 , 3871.0 , 3896.0 , 3921.0 , 3946.0 , 3971.0 , 3996.0 , 4021.0 , 4046.0 , 4071.0 , 4096.0 , 4121.0 , 4146.0 , 4171.0 , 4196.0 , 4221.0 , 4246.0 , 4271.0 , 4296.0 , 4321.0 , 4346.0 , 4371.0 , 4396.0 , 4421.0 , 4446.0 , 4471.0 , 4496.0 , 4521.0 , 4546.0 , 4571.0 , 4596.0 , 4621.0 , 4646.0 , 4671.0 , 4696.0 , 4721.0 , 4746.0 , 4771.0 , 4796.0 , 4821.0 , 4846.0 , 4871.0 , 4896.0 , 4921.0 , 4946.0 , 4971.0 , 4996.0 , 5021.0 , 5046.0 , 5071.0 , 5110.0 , 5129.5 , 5149.0 , 5150.0 , 5171.0 , 5271.0 , 5371.0 , 5471.0 , 5571.0 , 5671.0 , 5771.0 , 5871.0 , 5971.0 , 6071.0 , 6171.0}; double vs[500] = { 3.200 , 3.200 , 3.650 , 3.750 , 4.600 , 4.600 , 4.600 , 4.600 , 4.500 , 4.500 , 4.500 , 4.480 , 4.480 , 4.480 , 4.510 , 4.570 , 4.630 , 4.680 , 4.730 , 4.770 , 4.810 , 5.050 , 5.070 , 5.110 , 5.150 , 5.190 , 5.250 , 5.290 , 5.330 , 5.390 , 5.450 , 5.520 , 5.620 , 5.830 , 5.950 , 6.070 , 6.140 , 6.190 , 6.220 , 6.240 , 6.260 , 6.279 , 6.296 , 6.313 , 6.330 , 6.346 , 6.363 , 6.380 , 6.396 , 6.411 , 6.427 , 6.443 , 6.458 , 6.474 , 6.481 , 6.489 , 6.497 , 6.504 , 6.511 , 6.518 , 6.525 , 6.532 , 6.539 , 6.547 , 6.554 , 6.561 , 6.568 , 6.575 , 6.582 , 6.589 , 6.596 , 6.603 , 6.610 , 6.617 , 6.624 , 6.630 , 6.637 , 6.643 , 6.650 , 6.657 , 6.664 , 6.670 , 6.677 , 6.683 , 6.690 , 6.696 , 6.703 , 6.709 , 6.716 , 6.722 , 6.728 , 6.734 , 6.741 , 6.747 , 6.753 , 6.759 , 6.766 , 6.772 , 6.778 , 6.784 , 6.790 , 6.796 , 6.803 , 6.809 , 6.815 , 6.821 , 6.827 , 6.833 , 6.839 , 6.845 , 6.850 , 6.856 , 6.862 , 6.868 , 6.873 , 6.879 , 6.885 , 6.891 , 6.896 , 6.902 , 6.908 , 6.914 , 6.919 , 6.925 , 6.931 , 6.937 , 6.942 , 6.948 , 6.954 , 6.960 , 6.965 , 6.971 , 6.977 , 6.983 , 6.988 , 6.994 , 6.999 , 7.005 , 7.010 , 7.016 , 7.021 , 7.027 , 7.032 , 7.038 , 7.043 , 7.049 , 7.055 , 7.060 , 7.065 , 7.071 , 7.077 , 7.083 , 7.089 , 7.094 , 7.099 , 7.105 , 7.110 , 7.116 , 7.122 , 7.127 , 7.132 , 7.138 , 7.143 , 7.149 , 7.155 , 7.161 , 7.166 , 7.171 , 7.176 , 7.182 , 7.191 , 7.200 , 7.222 , 7.245 , 7.267 , 7.290 , 7.287 , 7.285 , 7.283 , 7.280 , 7.277 , 7.275 , 7.273 , 7.270 , 7.267 , 7.265 , 7.264 , 7.263 , 7.261 , 7.260 , 7.259 , 7.257 , 7.256 , 7.255 , 8.009 , 8.046 , 8.082 , 8.119 , 8.155 , 8.199 , 8.242 , 8.285 , 8.328 , 8.369 , 8.410 , 8.451 , 8.492 , 8.530 , 8.569 , 8.608 , 8.646 , 8.682 , 8.718 , 8.754 , 8.790 , 8.824 , 8.858 , 8.892 , 8.926 , 8.957 , 8.988 , 9.019 , 9.050 , 9.080 , 9.109 , 9.138 , 9.168 , 9.196 , 9.223 , 9.251 , 9.279 , 9.305 , 9.331 , 9.358 , 9.384 , 9.409 , 9.434 , 9.459 , 9.484 , 9.508 , 9.532 , 9.555 , 9.579 , 9.601 , 9.624 , 9.646 , 9.669 , 9.690 , 9.711 , 9.733 , 9.754 , 9.774 , 9.794 , 9.815 , 9.835 , 9.854 , 9.873 , 9.893 , 9.912 , 9.930 , 9.949 , 9.967 , 9.986 , 10.003 , 10.021 , 10.038 , 10.056 , 10.073 , 10.090 , 10.106 , 10.122 , 10.139 , 10.155 , 10.171 , 10.187 , 10.203 , 10.219 , 10.234 , 10.250 , 10.265 , 10.280 , 10.295 , 10.310 , 10.333 , 10.344 , 10.356 , 11.028 , 11.036 , 11.072 , 11.105 , 11.135 , 11.162 , 11.185 , 11.206 , 11.223 , 11.237 , 11.248 , 11.256}; int index_min = 0; int index_max = 0; for(index_max = 0; index_max < line_num; index_max ++) { if(depth[index_max] > DEPTH) break; } index_min = index_max -1; double vs_min = vs[index_min]; double vs_max = vs[index_max]; result = (DEPTH - depth[index_min])*(vs_max- vs_min)/(depth[index_max]-depth[index_min]) + vs[index_min]; //printf("depth is %lf dep minmax is %lf %lf vs is %lf \n", DEPTH ,depth[index_max], depth[index_min], result); return result; }
mit
DanielAmah/eDocCabinet
server/middleware/authentication.js
1128
import jwt from 'jsonwebtoken'; require('dotenv').config(); const authentication = { /** * verifyToken: This verifies all routes that starts with /api * It checks if there is token and check if the token is valid * if the token is valid, then it decodes it and send to the next route * @function verifyUser * @param {object} request sends a request * to check if a token has been set on the header * @param {object} response gets a response * if the request was successful or not. * @param {object} next response * @return {object} returns response status and json data */ verifyUser(request, response, next) { const token = request.headers['x-access-token'] || request.headers.authorization; if (!token) { return response.status(401).send({ message: 'Not Authorized' }); } jwt.verify(token, process.env.SECRET, (error, decoded) => { if (error) { return response.status(401).send({ message: 'Invalid Token' }); } request.decoded = decoded; next(); }); } }; export default authentication;
mit
reflectoring/coderadar
coderadar-ui/src/app/city-map/autosuggest-wrapper/autosuggest-wrapper.component.spec.ts
1088
import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {AutosuggestWrapperComponent} from './autosuggest-wrapper.component'; import {FormsModule, ReactiveFormsModule} from '@angular/forms'; import {MatAutocompleteModule, MatFormFieldModule, MatInputModule} from '@angular/material'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; describe('AutosuggestWrapperComponent', () => { let component: AutosuggestWrapperComponent; let fixture: ComponentFixture<AutosuggestWrapperComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ReactiveFormsModule, MatInputModule, MatAutocompleteModule, MatFormFieldModule, FormsModule, BrowserAnimationsModule], declarations: [AutosuggestWrapperComponent] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AutosuggestWrapperComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
mit
leventgunay/experimental
cakemake/src/main/java/org/basesource/cakemake/domain/User.java
1482
package org.basesource.cakemake.domain; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; @Entity public class User { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; private String name; @ManyToMany( cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "favoritedBy") private List<Cake> favoriteCakes = new ArrayList<Cake>(); @OneToMany( cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "author") private List<Comment> comments = new ArrayList<Comment>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Comment> getComments() { return comments; } public void setComments(List<Comment> comments) { this.comments = comments; } public List<Cake> getFavoriteCakes() { return favoriteCakes; } public void setFavoriteCakes(List<Cake> favoriteCakes) { this.favoriteCakes = favoriteCakes; } }
mit
n-pigeon/godot
core/variant.cpp
68119
/*************************************************************************/ /* variant.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "variant.h" #include "core_string_names.h" #include "io/marshalls.h" #include "math_funcs.h" #include "print_string.h" #include "resource.h" #include "scene/gui/control.h" #include "scene/main/node.h" #include "variant_parser.h" String Variant::get_type_name(Variant::Type p_type) { switch (p_type) { case NIL: { return "Nil"; } break; // atomic types case BOOL: { return "bool"; } break; case INT: { return "int"; } break; case REAL: { return "float"; } break; case STRING: { return "String"; } break; // math types case VECTOR2: { return "Vector2"; } break; case RECT2: { return "Rect2"; } break; case TRANSFORM2D: { return "Transform2D"; } break; case VECTOR3: { return "Vector3"; } break; case PLANE: { return "Plane"; } break; /* case QUAT: { } break;*/ case AABB: { return "AABB"; } break; case QUAT: { return "Quat"; } break; case BASIS: { return "Basis"; } break; case TRANSFORM: { return "Transform"; } break; // misc types case COLOR: { return "Color"; } break; case _RID: { return "RID"; } break; case OBJECT: { return "Object"; } break; case NODE_PATH: { return "NodePath"; } break; case DICTIONARY: { return "Dictionary"; } break; case ARRAY: { return "Array"; } break; // arrays case POOL_BYTE_ARRAY: { return "PoolByteArray"; } break; case POOL_INT_ARRAY: { return "PoolIntArray"; } break; case POOL_REAL_ARRAY: { return "PoolRealArray"; } break; case POOL_STRING_ARRAY: { return "PoolStringArray"; } break; case POOL_VECTOR2_ARRAY: { return "PoolVector2Array"; } break; case POOL_VECTOR3_ARRAY: { return "PoolVector3Array"; } break; case POOL_COLOR_ARRAY: { return "PoolColorArray"; } break; default: {} } return ""; } bool Variant::can_convert(Variant::Type p_type_from, Variant::Type p_type_to) { if (p_type_from == p_type_to) return true; if (p_type_to == NIL && p_type_from != NIL) //nil can convert to anything return true; if (p_type_from == NIL) { return (p_type_to == OBJECT); }; const Type *valid_types = NULL; const Type *invalid_types = NULL; switch (p_type_to) { case BOOL: { static const Type valid[] = { INT, REAL, STRING, NIL, }; valid_types = valid; } break; case INT: { static const Type valid[] = { BOOL, REAL, STRING, NIL, }; valid_types = valid; } break; case REAL: { static const Type valid[] = { BOOL, INT, STRING, NIL, }; valid_types = valid; } break; case STRING: { static const Type invalid[] = { OBJECT, NIL }; invalid_types = invalid; } break; case TRANSFORM2D: { static const Type valid[] = { TRANSFORM, NIL }; valid_types = valid; } break; case QUAT: { static const Type valid[] = { BASIS, NIL }; valid_types = valid; } break; case BASIS: { static const Type valid[] = { QUAT, NIL }; valid_types = valid; } break; case TRANSFORM: { static const Type valid[] = { TRANSFORM2D, QUAT, BASIS, NIL }; valid_types = valid; } break; case COLOR: { static const Type valid[] = { STRING, INT, NIL, }; valid_types = valid; } break; case _RID: { static const Type valid[] = { OBJECT, NIL }; valid_types = valid; } break; case OBJECT: { static const Type valid[] = { NIL }; valid_types = valid; } break; case NODE_PATH: { static const Type valid[] = { STRING, NIL }; valid_types = valid; } break; case ARRAY: { static const Type valid[] = { POOL_BYTE_ARRAY, POOL_INT_ARRAY, POOL_STRING_ARRAY, POOL_REAL_ARRAY, POOL_COLOR_ARRAY, POOL_VECTOR2_ARRAY, POOL_VECTOR3_ARRAY, NIL }; valid_types = valid; } break; // arrays case POOL_BYTE_ARRAY: { static const Type valid[] = { ARRAY, NIL }; valid_types = valid; } break; case POOL_INT_ARRAY: { static const Type valid[] = { ARRAY, NIL }; valid_types = valid; } break; case POOL_REAL_ARRAY: { static const Type valid[] = { ARRAY, NIL }; valid_types = valid; } break; case POOL_STRING_ARRAY: { static const Type valid[] = { ARRAY, NIL }; valid_types = valid; } break; case POOL_VECTOR2_ARRAY: { static const Type valid[] = { ARRAY, NIL }; valid_types = valid; } break; case POOL_VECTOR3_ARRAY: { static const Type valid[] = { ARRAY, NIL }; valid_types = valid; } break; case POOL_COLOR_ARRAY: { static const Type valid[] = { ARRAY, NIL }; valid_types = valid; } break; default: {} } if (valid_types) { int i = 0; while (valid_types[i] != NIL) { if (p_type_from == valid_types[i]) return true; i++; } } else if (invalid_types) { int i = 0; while (invalid_types[i] != NIL) { if (p_type_from == invalid_types[i]) return false; i++; } return true; } return false; } bool Variant::can_convert_strict(Variant::Type p_type_from, Variant::Type p_type_to) { if (p_type_from == p_type_to) return true; if (p_type_to == NIL && p_type_from != NIL) //nil can convert to anything return true; if (p_type_from == NIL) { return (p_type_to == OBJECT); }; const Type *valid_types = NULL; switch (p_type_to) { case BOOL: { static const Type valid[] = { INT, REAL, //STRING, NIL, }; valid_types = valid; } break; case INT: { static const Type valid[] = { BOOL, REAL, //STRING, NIL, }; valid_types = valid; } break; case REAL: { static const Type valid[] = { BOOL, INT, //STRING, NIL, }; valid_types = valid; } break; case STRING: { static const Type valid[] = { NODE_PATH, NIL }; valid_types = valid; } break; case TRANSFORM2D: { static const Type valid[] = { TRANSFORM, NIL }; valid_types = valid; } break; case QUAT: { static const Type valid[] = { BASIS, NIL }; valid_types = valid; } break; case BASIS: { static const Type valid[] = { QUAT, NIL }; valid_types = valid; } break; case TRANSFORM: { static const Type valid[] = { TRANSFORM2D, QUAT, BASIS, NIL }; valid_types = valid; } break; case COLOR: { static const Type valid[] = { STRING, INT, NIL, }; valid_types = valid; } break; case _RID: { static const Type valid[] = { OBJECT, NIL }; valid_types = valid; } break; case OBJECT: { static const Type valid[] = { NIL }; valid_types = valid; } break; case NODE_PATH: { static const Type valid[] = { STRING, NIL }; valid_types = valid; } break; case ARRAY: { static const Type valid[] = { POOL_BYTE_ARRAY, POOL_INT_ARRAY, POOL_STRING_ARRAY, POOL_REAL_ARRAY, POOL_COLOR_ARRAY, POOL_VECTOR2_ARRAY, POOL_VECTOR3_ARRAY, NIL }; valid_types = valid; } break; // arrays case POOL_BYTE_ARRAY: { static const Type valid[] = { ARRAY, NIL }; valid_types = valid; } break; case POOL_INT_ARRAY: { static const Type valid[] = { ARRAY, NIL }; valid_types = valid; } break; case POOL_REAL_ARRAY: { static const Type valid[] = { ARRAY, NIL }; valid_types = valid; } break; case POOL_STRING_ARRAY: { static const Type valid[] = { ARRAY, NIL }; valid_types = valid; } break; case POOL_VECTOR2_ARRAY: { static const Type valid[] = { ARRAY, NIL }; valid_types = valid; } break; case POOL_VECTOR3_ARRAY: { static const Type valid[] = { ARRAY, NIL }; valid_types = valid; } break; case POOL_COLOR_ARRAY: { static const Type valid[] = { ARRAY, NIL }; valid_types = valid; } break; default: {} } if (valid_types) { int i = 0; while (valid_types[i] != NIL) { if (p_type_from == valid_types[i]) return true; i++; } } return false; } bool Variant::operator==(const Variant &p_variant) const { if (type != p_variant.type) //evaluation of operator== needs to be more strict return false; bool v; Variant r; evaluate(OP_EQUAL, *this, p_variant, r, v); return r; } bool Variant::operator!=(const Variant &p_variant) const { if (type != p_variant.type) //evaluation of operator== needs to be more strict return true; bool v; Variant r; evaluate(OP_NOT_EQUAL, *this, p_variant, r, v); return r; } bool Variant::operator<(const Variant &p_variant) const { if (type != p_variant.type) //if types differ, then order by type first return type < p_variant.type; bool v; Variant r; evaluate(OP_LESS, *this, p_variant, r, v); return r; } bool Variant::is_zero() const { switch (type) { case NIL: { return true; } break; // atomic types case BOOL: { return _data._bool == false; } break; case INT: { return _data._int == 0; } break; case REAL: { return _data._real == 0; } break; case STRING: { return *reinterpret_cast<const String *>(_data._mem) == String(); } break; // math types case VECTOR2: { return *reinterpret_cast<const Vector2 *>(_data._mem) == Vector2(); } break; case RECT2: { return *reinterpret_cast<const Rect2 *>(_data._mem) == Rect2(); } break; case TRANSFORM2D: { return *_data._transform2d == Transform2D(); } break; case VECTOR3: { return *reinterpret_cast<const Vector3 *>(_data._mem) == Vector3(); } break; case PLANE: { return *reinterpret_cast<const Plane *>(_data._mem) == Plane(); } break; /* case QUAT: { } break;*/ case AABB: { return *_data._aabb == ::AABB(); } break; case QUAT: { return *reinterpret_cast<const Quat *>(_data._mem) == Quat(); } break; case BASIS: { return *_data._basis == Basis(); } break; case TRANSFORM: { return *_data._transform == Transform(); } break; // misc types case COLOR: { return *reinterpret_cast<const Color *>(_data._mem) == Color(); } break; case _RID: { return *reinterpret_cast<const RID *>(_data._mem) == RID(); } break; case OBJECT: { return _get_obj().obj == NULL; } break; case NODE_PATH: { return reinterpret_cast<const NodePath *>(_data._mem)->is_empty(); } break; case DICTIONARY: { return reinterpret_cast<const Dictionary *>(_data._mem)->empty(); } break; case ARRAY: { return reinterpret_cast<const Array *>(_data._mem)->empty(); } break; // arrays case POOL_BYTE_ARRAY: { return reinterpret_cast<const PoolVector<uint8_t> *>(_data._mem)->size() == 0; } break; case POOL_INT_ARRAY: { return reinterpret_cast<const PoolVector<int> *>(_data._mem)->size() == 0; } break; case POOL_REAL_ARRAY: { return reinterpret_cast<const PoolVector<real_t> *>(_data._mem)->size() == 0; } break; case POOL_STRING_ARRAY: { return reinterpret_cast<const PoolVector<String> *>(_data._mem)->size() == 0; } break; case POOL_VECTOR2_ARRAY: { return reinterpret_cast<const PoolVector<Vector2> *>(_data._mem)->size() == 0; } break; case POOL_VECTOR3_ARRAY: { return reinterpret_cast<const PoolVector<Vector3> *>(_data._mem)->size() == 0; } break; case POOL_COLOR_ARRAY: { return reinterpret_cast<const PoolVector<Color> *>(_data._mem)->size() == 0; } break; default: {} } return false; } bool Variant::is_one() const { switch (type) { case NIL: { return true; } break; // atomic types case BOOL: { return _data._bool == true; } break; case INT: { return _data._int == 1; } break; case REAL: { return _data._real == 1; } break; case VECTOR2: { return *reinterpret_cast<const Vector2 *>(_data._mem) == Vector2(1, 1); } break; case RECT2: { return *reinterpret_cast<const Rect2 *>(_data._mem) == Rect2(1, 1, 1, 1); } break; case VECTOR3: { return *reinterpret_cast<const Vector3 *>(_data._mem) == Vector3(1, 1, 1); } break; case PLANE: { return *reinterpret_cast<const Plane *>(_data._mem) == Plane(1, 1, 1, 1); } break; case COLOR: { return *reinterpret_cast<const Color *>(_data._mem) == Color(1, 1, 1, 1); } break; default: { return !is_zero(); } } return false; } void Variant::reference(const Variant &p_variant) { clear(); type = p_variant.type; switch (p_variant.type) { case NIL: { // none } break; // atomic types case BOOL: { _data._bool = p_variant._data._bool; } break; case INT: { _data._int = p_variant._data._int; } break; case REAL: { _data._real = p_variant._data._real; } break; case STRING: { memnew_placement(_data._mem, String(*reinterpret_cast<const String *>(p_variant._data._mem))); } break; // math types case VECTOR2: { memnew_placement(_data._mem, Vector2(*reinterpret_cast<const Vector2 *>(p_variant._data._mem))); } break; case RECT2: { memnew_placement(_data._mem, Rect2(*reinterpret_cast<const Rect2 *>(p_variant._data._mem))); } break; case TRANSFORM2D: { _data._transform2d = memnew(Transform2D(*p_variant._data._transform2d)); } break; case VECTOR3: { memnew_placement(_data._mem, Vector3(*reinterpret_cast<const Vector3 *>(p_variant._data._mem))); } break; case PLANE: { memnew_placement(_data._mem, Plane(*reinterpret_cast<const Plane *>(p_variant._data._mem))); } break; case AABB: { _data._aabb = memnew(::AABB(*p_variant._data._aabb)); } break; case QUAT: { memnew_placement(_data._mem, Quat(*reinterpret_cast<const Quat *>(p_variant._data._mem))); } break; case BASIS: { _data._basis = memnew(Basis(*p_variant._data._basis)); } break; case TRANSFORM: { _data._transform = memnew(Transform(*p_variant._data._transform)); } break; // misc types case COLOR: { memnew_placement(_data._mem, Color(*reinterpret_cast<const Color *>(p_variant._data._mem))); } break; case _RID: { memnew_placement(_data._mem, RID(*reinterpret_cast<const RID *>(p_variant._data._mem))); } break; case OBJECT: { memnew_placement(_data._mem, ObjData(p_variant._get_obj())); } break; case NODE_PATH: { memnew_placement(_data._mem, NodePath(*reinterpret_cast<const NodePath *>(p_variant._data._mem))); } break; case DICTIONARY: { memnew_placement(_data._mem, Dictionary(*reinterpret_cast<const Dictionary *>(p_variant._data._mem))); } break; case ARRAY: { memnew_placement(_data._mem, Array(*reinterpret_cast<const Array *>(p_variant._data._mem))); } break; // arrays case POOL_BYTE_ARRAY: { memnew_placement(_data._mem, PoolVector<uint8_t>(*reinterpret_cast<const PoolVector<uint8_t> *>(p_variant._data._mem))); } break; case POOL_INT_ARRAY: { memnew_placement(_data._mem, PoolVector<int>(*reinterpret_cast<const PoolVector<int> *>(p_variant._data._mem))); } break; case POOL_REAL_ARRAY: { memnew_placement(_data._mem, PoolVector<real_t>(*reinterpret_cast<const PoolVector<real_t> *>(p_variant._data._mem))); } break; case POOL_STRING_ARRAY: { memnew_placement(_data._mem, PoolVector<String>(*reinterpret_cast<const PoolVector<String> *>(p_variant._data._mem))); } break; case POOL_VECTOR2_ARRAY: { memnew_placement(_data._mem, PoolVector<Vector2>(*reinterpret_cast<const PoolVector<Vector2> *>(p_variant._data._mem))); } break; case POOL_VECTOR3_ARRAY: { memnew_placement(_data._mem, PoolVector<Vector3>(*reinterpret_cast<const PoolVector<Vector3> *>(p_variant._data._mem))); } break; case POOL_COLOR_ARRAY: { memnew_placement(_data._mem, PoolVector<Color>(*reinterpret_cast<const PoolVector<Color> *>(p_variant._data._mem))); } break; default: {} } } void Variant::zero() { switch (type) { case NIL: break; case BOOL: this->_data._bool = false; break; case INT: this->_data._int = 0; break; case REAL: this->_data._real = 0; break; case VECTOR2: *reinterpret_cast<Vector2 *>(this->_data._mem) = Vector2(); break; case RECT2: *reinterpret_cast<Rect2 *>(this->_data._mem) = Rect2(); break; case VECTOR3: *reinterpret_cast<Vector3 *>(this->_data._mem) = Vector3(); break; case PLANE: *reinterpret_cast<Plane *>(this->_data._mem) = Plane(); break; case QUAT: *reinterpret_cast<Quat *>(this->_data._mem) = Quat(); break; case COLOR: *reinterpret_cast<Color *>(this->_data._mem) = Color(); break; default: this->clear(); break; } } void Variant::clear() { switch (type) { case STRING: { reinterpret_cast<String *>(_data._mem)->~String(); } break; /* // no point, they don't allocate memory VECTOR3, PLANE, QUAT, COLOR, VECTOR2, RECT2 */ case TRANSFORM2D: { memdelete(_data._transform2d); } break; case AABB: { memdelete(_data._aabb); } break; case BASIS: { memdelete(_data._basis); } break; case TRANSFORM: { memdelete(_data._transform); } break; // misc types case NODE_PATH: { reinterpret_cast<NodePath *>(_data._mem)->~NodePath(); } break; case OBJECT: { _get_obj().obj = NULL; _get_obj().ref.unref(); } break; case _RID: { // not much need probably reinterpret_cast<RID *>(_data._mem)->~RID(); } break; case DICTIONARY: { reinterpret_cast<Dictionary *>(_data._mem)->~Dictionary(); } break; case ARRAY: { reinterpret_cast<Array *>(_data._mem)->~Array(); } break; // arrays case POOL_BYTE_ARRAY: { reinterpret_cast<PoolVector<uint8_t> *>(_data._mem)->~PoolVector<uint8_t>(); } break; case POOL_INT_ARRAY: { reinterpret_cast<PoolVector<int> *>(_data._mem)->~PoolVector<int>(); } break; case POOL_REAL_ARRAY: { reinterpret_cast<PoolVector<real_t> *>(_data._mem)->~PoolVector<real_t>(); } break; case POOL_STRING_ARRAY: { reinterpret_cast<PoolVector<String> *>(_data._mem)->~PoolVector<String>(); } break; case POOL_VECTOR2_ARRAY: { reinterpret_cast<PoolVector<Vector2> *>(_data._mem)->~PoolVector<Vector2>(); } break; case POOL_VECTOR3_ARRAY: { reinterpret_cast<PoolVector<Vector3> *>(_data._mem)->~PoolVector<Vector3>(); } break; case POOL_COLOR_ARRAY: { reinterpret_cast<PoolVector<Color> *>(_data._mem)->~PoolVector<Color>(); } break; default: {} /* not needed */ } type = NIL; } Variant::operator signed int() const { switch (type) { case NIL: return 0; case BOOL: return _data._bool ? 1 : 0; case INT: return _data._int; case REAL: return _data._real; case STRING: return operator String().to_int(); default: { return 0; } } return 0; } Variant::operator unsigned int() const { switch (type) { case NIL: return 0; case BOOL: return _data._bool ? 1 : 0; case INT: return _data._int; case REAL: return _data._real; case STRING: return operator String().to_int(); default: { return 0; } } return 0; } Variant::operator int64_t() const { switch (type) { case NIL: return 0; case BOOL: return _data._bool ? 1 : 0; case INT: return _data._int; case REAL: return _data._real; case STRING: return operator String().to_int(); default: { return 0; } } return 0; } /* Variant::operator long unsigned int() const { switch( type ) { case NIL: return 0; case BOOL: return _data._bool ? 1 : 0; case INT: return _data._int; case REAL: return _data._real; case STRING: return operator String().to_int(); default: { return 0; } } return 0; }; */ Variant::operator uint64_t() const { switch (type) { case NIL: return 0; case BOOL: return _data._bool ? 1 : 0; case INT: return _data._int; case REAL: return _data._real; case STRING: return operator String().to_int(); default: { return 0; } } return 0; } #ifdef NEED_LONG_INT Variant::operator signed long() const { switch (type) { case NIL: return 0; case BOOL: return _data._bool ? 1 : 0; case INT: return _data._int; case REAL: return _data._real; case STRING: return operator String().to_int(); default: { return 0; } } return 0; }; Variant::operator unsigned long() const { switch (type) { case NIL: return 0; case BOOL: return _data._bool ? 1 : 0; case INT: return _data._int; case REAL: return _data._real; case STRING: return operator String().to_int(); default: { return 0; } } return 0; }; #endif Variant::operator signed short() const { switch (type) { case NIL: return 0; case BOOL: return _data._bool ? 1 : 0; case INT: return _data._int; case REAL: return _data._real; case STRING: return operator String().to_int(); default: { return 0; } } return 0; } Variant::operator unsigned short() const { switch (type) { case NIL: return 0; case BOOL: return _data._bool ? 1 : 0; case INT: return _data._int; case REAL: return _data._real; case STRING: return operator String().to_int(); default: { return 0; } } return 0; } Variant::operator signed char() const { switch (type) { case NIL: return 0; case BOOL: return _data._bool ? 1 : 0; case INT: return _data._int; case REAL: return _data._real; case STRING: return operator String().to_int(); default: { return 0; } } return 0; } Variant::operator unsigned char() const { switch (type) { case NIL: return 0; case BOOL: return _data._bool ? 1 : 0; case INT: return _data._int; case REAL: return _data._real; case STRING: return operator String().to_int(); default: { return 0; } } return 0; } Variant::operator CharType() const { return operator unsigned int(); } Variant::operator float() const { switch (type) { case NIL: return 0; case BOOL: return _data._bool ? 1.0 : 0.0; case INT: return (float)_data._int; case REAL: return _data._real; case STRING: return operator String().to_double(); default: { return 0; } } return 0; } Variant::operator double() const { switch (type) { case NIL: return 0; case BOOL: return _data._bool ? 1.0 : 0.0; case INT: return (double)_data._int; case REAL: return _data._real; case STRING: return operator String().to_double(); default: { return 0; } } return true; } Variant::operator StringName() const { if (type == NODE_PATH) { return reinterpret_cast<const NodePath *>(_data._mem)->get_sname(); } return StringName(operator String()); } struct _VariantStrPair { String key; String value; bool operator<(const _VariantStrPair &p) const { return key < p.key; } }; Variant::operator String() const { switch (type) { case NIL: return "Null"; case BOOL: return _data._bool ? "True" : "False"; case INT: return itos(_data._int); case REAL: return rtos(_data._real); case STRING: return *reinterpret_cast<const String *>(_data._mem); case VECTOR2: return "(" + operator Vector2() + ")"; case RECT2: return "(" + operator Rect2() + ")"; case TRANSFORM2D: { Transform2D mat32 = operator Transform2D(); return "(" + Variant(mat32.elements[0]).operator String() + ", " + Variant(mat32.elements[1]).operator String() + ", " + Variant(mat32.elements[2]).operator String() + ")"; } break; case VECTOR3: return "(" + operator Vector3() + ")"; case PLANE: return operator Plane(); //case QUAT: case AABB: return operator ::AABB(); case QUAT: return "(" + operator Quat() + ")"; case BASIS: { Basis mat3 = operator Basis(); String mtx("("); for (int i = 0; i < 3; i++) { if (i != 0) mtx += ", "; mtx += "("; for (int j = 0; j < 3; j++) { if (j != 0) mtx += ", "; mtx += Variant(mat3.elements[i][j]).operator String(); } mtx += ")"; } return mtx + ")"; } break; case TRANSFORM: return operator Transform(); case NODE_PATH: return operator NodePath(); case COLOR: return String::num(operator Color().r) + "," + String::num(operator Color().g) + "," + String::num(operator Color().b) + "," + String::num(operator Color().a); case DICTIONARY: { const Dictionary &d = *reinterpret_cast<const Dictionary *>(_data._mem); //const String *K=NULL; String str; List<Variant> keys; d.get_key_list(&keys); Vector<_VariantStrPair> pairs; for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { _VariantStrPair sp; sp.key = String(E->get()); sp.value = d[E->get()]; pairs.push_back(sp); } pairs.sort(); for (int i = 0; i < pairs.size(); i++) { if (i > 0) str += ", "; str += "(" + pairs[i].key + ":" + pairs[i].value + ")"; } return str; } break; case POOL_VECTOR2_ARRAY: { PoolVector<Vector2> vec = operator PoolVector<Vector2>(); String str("["); for (int i = 0; i < vec.size(); i++) { if (i > 0) str += ", "; str = str + Variant(vec[i]); } str += "]"; return str; } break; case POOL_VECTOR3_ARRAY: { PoolVector<Vector3> vec = operator PoolVector<Vector3>(); String str("["); for (int i = 0; i < vec.size(); i++) { if (i > 0) str += ", "; str = str + Variant(vec[i]); } str += "]"; return str; } break; case POOL_STRING_ARRAY: { PoolVector<String> vec = operator PoolVector<String>(); String str("["); for (int i = 0; i < vec.size(); i++) { if (i > 0) str += ", "; str = str + vec[i]; } str += "]"; return str; } break; case POOL_INT_ARRAY: { PoolVector<int> vec = operator PoolVector<int>(); String str("["); for (int i = 0; i < vec.size(); i++) { if (i > 0) str += ", "; str = str + itos(vec[i]); } str += "]"; return str; } break; case POOL_REAL_ARRAY: { PoolVector<real_t> vec = operator PoolVector<real_t>(); String str("["); for (int i = 0; i < vec.size(); i++) { if (i > 0) str += ", "; str = str + rtos(vec[i]); } str += "]"; return str; } break; case ARRAY: { Array arr = operator Array(); String str("["); for (int i = 0; i < arr.size(); i++) { if (i) str += ", "; str += String(arr[i]); }; str += "]"; return str; } break; case OBJECT: { if (_get_obj().obj) { #ifdef DEBUG_ENABLED if (ScriptDebugger::get_singleton() && _get_obj().ref.is_null()) { //only if debugging! if (!ObjectDB::instance_validate(_get_obj().obj)) { return "[Deleted Object]"; }; }; #endif return "[" + _get_obj().obj->get_class() + ":" + itos(_get_obj().obj->get_instance_id()) + "]"; } else return "[Object:null]"; } break; default: { return "[" + get_type_name(type) + "]"; } } return ""; } Variant::operator Vector2() const { if (type == VECTOR2) return *reinterpret_cast<const Vector2 *>(_data._mem); else if (type == VECTOR3) return Vector2(reinterpret_cast<const Vector3 *>(_data._mem)->x, reinterpret_cast<const Vector3 *>(_data._mem)->y); else return Vector2(); } Variant::operator Rect2() const { if (type == RECT2) return *reinterpret_cast<const Rect2 *>(_data._mem); else return Rect2(); } Variant::operator Vector3() const { if (type == VECTOR3) return *reinterpret_cast<const Vector3 *>(_data._mem); else return Vector3(); } Variant::operator Plane() const { if (type == PLANE) return *reinterpret_cast<const Plane *>(_data._mem); else return Plane(); } Variant::operator ::AABB() const { if (type == AABB) return *_data._aabb; else return ::AABB(); } Variant::operator Basis() const { if (type == BASIS) return *_data._basis; else if (type == QUAT) return *reinterpret_cast<const Quat *>(_data._mem); else if (type == TRANSFORM) return _data._transform->basis; else return Basis(); } Variant::operator Quat() const { if (type == QUAT) return *reinterpret_cast<const Quat *>(_data._mem); else if (type == BASIS) return *_data._basis; else if (type == TRANSFORM) return _data._transform->basis; else return Quat(); } Variant::operator Transform() const { if (type == TRANSFORM) return *_data._transform; else if (type == BASIS) return Transform(*_data._basis, Vector3()); else if (type == QUAT) return Transform(Basis(*reinterpret_cast<const Quat *>(_data._mem)), Vector3()); else return Transform(); } Variant::operator Transform2D() const { if (type == TRANSFORM2D) { return *_data._transform2d; } else if (type == TRANSFORM) { const Transform &t = *_data._transform; Transform2D m; m.elements[0][0] = t.basis.elements[0][0]; m.elements[0][1] = t.basis.elements[1][0]; m.elements[1][0] = t.basis.elements[0][1]; m.elements[1][1] = t.basis.elements[1][1]; m.elements[2][0] = t.origin[0]; m.elements[2][1] = t.origin[1]; return m; } else return Transform2D(); } Variant::operator Color() const { if (type == COLOR) return *reinterpret_cast<const Color *>(_data._mem); else if (type == STRING) return Color::html(operator String()); else if (type == INT) return Color::hex(operator int()); else return Color(); } Variant::operator NodePath() const { if (type == NODE_PATH) return *reinterpret_cast<const NodePath *>(_data._mem); else if (type == STRING) return NodePath(operator String()); else return NodePath(); } Variant::operator RefPtr() const { if (type == OBJECT) return _get_obj().ref; else return RefPtr(); } Variant::operator RID() const { if (type == _RID) return *reinterpret_cast<const RID *>(_data._mem); else if (type == OBJECT && !_get_obj().ref.is_null()) { return _get_obj().ref.get_rid(); } else if (type == OBJECT && _get_obj().obj) { Variant::CallError ce; Variant ret = _get_obj().obj->call(CoreStringNames::get_singleton()->get_rid, NULL, 0, ce); if (ce.error == Variant::CallError::CALL_OK && ret.get_type() == Variant::_RID) { return ret; } return RID(); } else { return RID(); } } Variant::operator Object *() const { if (type == OBJECT) return _get_obj().obj; else return NULL; } Variant::operator Node *() const { if (type == OBJECT) return Object::cast_to<Node>(_get_obj().obj); else return NULL; } Variant::operator Control *() const { if (type == OBJECT) return Object::cast_to<Control>(_get_obj().obj); else return NULL; } Variant::operator Dictionary() const { if (type == DICTIONARY) return *reinterpret_cast<const Dictionary *>(_data._mem); else return Dictionary(); } template <class DA, class SA> inline DA _convert_array(const SA &p_array) { DA da; da.resize(p_array.size()); for (int i = 0; i < p_array.size(); i++) { da.set(i, Variant(p_array.get(i))); } return da; } template <class DA> inline DA _convert_array_from_variant(const Variant &p_variant) { switch (p_variant.get_type()) { case Variant::ARRAY: { return _convert_array<DA, Array>(p_variant.operator Array()); } case Variant::POOL_BYTE_ARRAY: { return _convert_array<DA, PoolVector<uint8_t> >(p_variant.operator PoolVector<uint8_t>()); } case Variant::POOL_INT_ARRAY: { return _convert_array<DA, PoolVector<int> >(p_variant.operator PoolVector<int>()); } case Variant::POOL_REAL_ARRAY: { return _convert_array<DA, PoolVector<real_t> >(p_variant.operator PoolVector<real_t>()); } case Variant::POOL_STRING_ARRAY: { return _convert_array<DA, PoolVector<String> >(p_variant.operator PoolVector<String>()); } case Variant::POOL_VECTOR2_ARRAY: { return _convert_array<DA, PoolVector<Vector2> >(p_variant.operator PoolVector<Vector2>()); } case Variant::POOL_VECTOR3_ARRAY: { return _convert_array<DA, PoolVector<Vector3> >(p_variant.operator PoolVector<Vector3>()); } case Variant::POOL_COLOR_ARRAY: { return _convert_array<DA, PoolVector<Color> >(p_variant.operator PoolVector<Color>()); } default: { return DA(); } } return DA(); } Variant::operator Array() const { if (type == ARRAY) return *reinterpret_cast<const Array *>(_data._mem); else return _convert_array_from_variant<Array>(*this); } Variant::operator PoolVector<uint8_t>() const { if (type == POOL_BYTE_ARRAY) return *reinterpret_cast<const PoolVector<uint8_t> *>(_data._mem); else return _convert_array_from_variant<PoolVector<uint8_t> >(*this); } Variant::operator PoolVector<int>() const { if (type == POOL_INT_ARRAY) return *reinterpret_cast<const PoolVector<int> *>(_data._mem); else return _convert_array_from_variant<PoolVector<int> >(*this); } Variant::operator PoolVector<real_t>() const { if (type == POOL_REAL_ARRAY) return *reinterpret_cast<const PoolVector<real_t> *>(_data._mem); else return _convert_array_from_variant<PoolVector<real_t> >(*this); } Variant::operator PoolVector<String>() const { if (type == POOL_STRING_ARRAY) return *reinterpret_cast<const PoolVector<String> *>(_data._mem); else return _convert_array_from_variant<PoolVector<String> >(*this); } Variant::operator PoolVector<Vector3>() const { if (type == POOL_VECTOR3_ARRAY) return *reinterpret_cast<const PoolVector<Vector3> *>(_data._mem); else return _convert_array_from_variant<PoolVector<Vector3> >(*this); } Variant::operator PoolVector<Vector2>() const { if (type == POOL_VECTOR2_ARRAY) return *reinterpret_cast<const PoolVector<Vector2> *>(_data._mem); else return _convert_array_from_variant<PoolVector<Vector2> >(*this); } Variant::operator PoolVector<Color>() const { if (type == POOL_COLOR_ARRAY) return *reinterpret_cast<const PoolVector<Color> *>(_data._mem); else return _convert_array_from_variant<PoolVector<Color> >(*this); } /* helpers */ Variant::operator Vector<RID>() const { Array va = operator Array(); Vector<RID> rids; rids.resize(va.size()); for (int i = 0; i < rids.size(); i++) rids[i] = va[i]; return rids; } Variant::operator Vector<Vector2>() const { PoolVector<Vector2> from = operator PoolVector<Vector2>(); Vector<Vector2> to; int len = from.size(); if (len == 0) return Vector<Vector2>(); to.resize(len); PoolVector<Vector2>::Read r = from.read(); Vector2 *w = &to[0]; for (int i = 0; i < len; i++) { w[i] = r[i]; } return to; } Variant::operator PoolVector<Plane>() const { Array va = operator Array(); PoolVector<Plane> planes; int va_size = va.size(); if (va_size == 0) return planes; planes.resize(va_size); PoolVector<Plane>::Write w = planes.write(); for (int i = 0; i < va_size; i++) w[i] = va[i]; return planes; } Variant::operator PoolVector<Face3>() const { PoolVector<Vector3> va = operator PoolVector<Vector3>(); PoolVector<Face3> faces; int va_size = va.size(); if (va_size == 0) return faces; faces.resize(va_size / 3); PoolVector<Face3>::Write w = faces.write(); PoolVector<Vector3>::Read r = va.read(); for (int i = 0; i < va_size; i++) w[i / 3].vertex[i % 3] = r[i]; return faces; } Variant::operator Vector<Plane>() const { Array va = operator Array(); Vector<Plane> planes; int va_size = va.size(); if (va_size == 0) return planes; planes.resize(va_size); for (int i = 0; i < va_size; i++) planes[i] = va[i]; return planes; } Variant::operator Vector<Variant>() const { Array from = operator Array(); Vector<Variant> to; int len = from.size(); to.resize(len); for (int i = 0; i < len; i++) { to[i] = from[i]; } return to; } Variant::operator Vector<uint8_t>() const { PoolVector<uint8_t> from = operator PoolVector<uint8_t>(); Vector<uint8_t> to; int len = from.size(); to.resize(len); for (int i = 0; i < len; i++) { to[i] = from[i]; } return to; } Variant::operator Vector<int>() const { PoolVector<int> from = operator PoolVector<int>(); Vector<int> to; int len = from.size(); to.resize(len); for (int i = 0; i < len; i++) { to[i] = from[i]; } return to; } Variant::operator Vector<real_t>() const { PoolVector<real_t> from = operator PoolVector<real_t>(); Vector<real_t> to; int len = from.size(); to.resize(len); for (int i = 0; i < len; i++) { to[i] = from[i]; } return to; } Variant::operator Vector<String>() const { PoolVector<String> from = operator PoolVector<String>(); Vector<String> to; int len = from.size(); to.resize(len); for (int i = 0; i < len; i++) { to[i] = from[i]; } return to; } Variant::operator Vector<Vector3>() const { PoolVector<Vector3> from = operator PoolVector<Vector3>(); Vector<Vector3> to; int len = from.size(); if (len == 0) return Vector<Vector3>(); to.resize(len); PoolVector<Vector3>::Read r = from.read(); Vector3 *w = &to[0]; for (int i = 0; i < len; i++) { w[i] = r[i]; } return to; } Variant::operator Vector<Color>() const { PoolVector<Color> from = operator PoolVector<Color>(); Vector<Color> to; int len = from.size(); if (len == 0) return Vector<Color>(); to.resize(len); PoolVector<Color>::Read r = from.read(); Color *w = &to[0]; for (int i = 0; i < len; i++) { w[i] = r[i]; } return to; } Variant::operator Margin() const { return (Margin) operator int(); } Variant::operator Orientation() const { return (Orientation) operator int(); } Variant::operator IP_Address() const { if (type == POOL_REAL_ARRAY || type == POOL_INT_ARRAY || type == POOL_BYTE_ARRAY) { PoolVector<int> addr = operator PoolVector<int>(); if (addr.size() == 4) { return IP_Address(addr.get(0), addr.get(1), addr.get(2), addr.get(3)); } } return IP_Address(operator String()); } Variant::Variant(bool p_bool) { type = BOOL; _data._bool = p_bool; } /* Variant::Variant(long unsigned int p_long) { type=INT; _data._int=p_long; }; */ Variant::Variant(signed int p_int) { type = INT; _data._int = p_int; } Variant::Variant(unsigned int p_int) { type = INT; _data._int = p_int; } #ifdef NEED_LONG_INT Variant::Variant(signed long p_int) { type = INT; _data._int = p_int; } Variant::Variant(unsigned long p_int) { type = INT; _data._int = p_int; } #endif Variant::Variant(int64_t p_int) { type = INT; _data._int = p_int; } Variant::Variant(uint64_t p_int) { type = INT; _data._int = p_int; } Variant::Variant(signed short p_short) { type = INT; _data._int = p_short; } Variant::Variant(unsigned short p_short) { type = INT; _data._int = p_short; } Variant::Variant(signed char p_char) { type = INT; _data._int = p_char; } Variant::Variant(unsigned char p_char) { type = INT; _data._int = p_char; } Variant::Variant(float p_float) { type = REAL; _data._real = p_float; } Variant::Variant(double p_double) { type = REAL; _data._real = p_double; } Variant::Variant(const StringName &p_string) { type = STRING; memnew_placement(_data._mem, String(p_string.operator String())); } Variant::Variant(const String &p_string) { type = STRING; memnew_placement(_data._mem, String(p_string)); } Variant::Variant(const char *const p_cstring) { type = STRING; memnew_placement(_data._mem, String((const char *)p_cstring)); } Variant::Variant(const CharType *p_wstring) { type = STRING; memnew_placement(_data._mem, String(p_wstring)); } Variant::Variant(const Vector3 &p_vector3) { type = VECTOR3; memnew_placement(_data._mem, Vector3(p_vector3)); } Variant::Variant(const Vector2 &p_vector2) { type = VECTOR2; memnew_placement(_data._mem, Vector2(p_vector2)); } Variant::Variant(const Rect2 &p_rect2) { type = RECT2; memnew_placement(_data._mem, Rect2(p_rect2)); } Variant::Variant(const Plane &p_plane) { type = PLANE; memnew_placement(_data._mem, Plane(p_plane)); } Variant::Variant(const ::AABB &p_aabb) { type = AABB; _data._aabb = memnew(::AABB(p_aabb)); } Variant::Variant(const Basis &p_matrix) { type = BASIS; _data._basis = memnew(Basis(p_matrix)); } Variant::Variant(const Quat &p_quat) { type = QUAT; memnew_placement(_data._mem, Quat(p_quat)); } Variant::Variant(const Transform &p_transform) { type = TRANSFORM; _data._transform = memnew(Transform(p_transform)); } Variant::Variant(const Transform2D &p_transform) { type = TRANSFORM2D; _data._transform2d = memnew(Transform2D(p_transform)); } Variant::Variant(const Color &p_color) { type = COLOR; memnew_placement(_data._mem, Color(p_color)); } Variant::Variant(const NodePath &p_node_path) { type = NODE_PATH; memnew_placement(_data._mem, NodePath(p_node_path)); } Variant::Variant(const RefPtr &p_resource) { type = OBJECT; memnew_placement(_data._mem, ObjData); REF *ref = reinterpret_cast<REF *>(p_resource.get_data()); _get_obj().obj = ref->ptr(); _get_obj().ref = p_resource; } Variant::Variant(const RID &p_rid) { type = _RID; memnew_placement(_data._mem, RID(p_rid)); } Variant::Variant(const Object *p_object) { type = OBJECT; memnew_placement(_data._mem, ObjData); _get_obj().obj = const_cast<Object *>(p_object); } Variant::Variant(const Dictionary &p_dictionary) { type = DICTIONARY; memnew_placement(_data._mem, (Dictionary)(p_dictionary)); } Variant::Variant(const Array &p_array) { type = ARRAY; memnew_placement(_data._mem, Array(p_array)); } Variant::Variant(const PoolVector<Plane> &p_array) { type = ARRAY; Array *plane_array = memnew_placement(_data._mem, Array); plane_array->resize(p_array.size()); for (int i = 0; i < p_array.size(); i++) { plane_array->operator[](i) = Variant(p_array[i]); } } Variant::Variant(const Vector<Plane> &p_array) { type = ARRAY; Array *plane_array = memnew_placement(_data._mem, Array); plane_array->resize(p_array.size()); for (int i = 0; i < p_array.size(); i++) { plane_array->operator[](i) = Variant(p_array[i]); } } Variant::Variant(const Vector<RID> &p_array) { type = ARRAY; Array *rid_array = memnew_placement(_data._mem, Array); rid_array->resize(p_array.size()); for (int i = 0; i < p_array.size(); i++) { rid_array->set(i, Variant(p_array[i])); } } Variant::Variant(const Vector<Vector2> &p_array) { type = NIL; PoolVector<Vector2> v; int len = p_array.size(); if (len > 0) { v.resize(len); PoolVector<Vector2>::Write w = v.write(); const Vector2 *r = p_array.ptr(); for (int i = 0; i < len; i++) w[i] = r[i]; } *this = v; } Variant::Variant(const PoolVector<uint8_t> &p_raw_array) { type = POOL_BYTE_ARRAY; memnew_placement(_data._mem, PoolVector<uint8_t>(p_raw_array)); } Variant::Variant(const PoolVector<int> &p_int_array) { type = POOL_INT_ARRAY; memnew_placement(_data._mem, PoolVector<int>(p_int_array)); } Variant::Variant(const PoolVector<real_t> &p_real_array) { type = POOL_REAL_ARRAY; memnew_placement(_data._mem, PoolVector<real_t>(p_real_array)); } Variant::Variant(const PoolVector<String> &p_string_array) { type = POOL_STRING_ARRAY; memnew_placement(_data._mem, PoolVector<String>(p_string_array)); } Variant::Variant(const PoolVector<Vector3> &p_vector3_array) { type = POOL_VECTOR3_ARRAY; memnew_placement(_data._mem, PoolVector<Vector3>(p_vector3_array)); } Variant::Variant(const PoolVector<Vector2> &p_vector2_array) { type = POOL_VECTOR2_ARRAY; memnew_placement(_data._mem, PoolVector<Vector2>(p_vector2_array)); } Variant::Variant(const PoolVector<Color> &p_color_array) { type = POOL_COLOR_ARRAY; memnew_placement(_data._mem, PoolVector<Color>(p_color_array)); } Variant::Variant(const PoolVector<Face3> &p_face_array) { PoolVector<Vector3> vertices; int face_count = p_face_array.size(); vertices.resize(face_count * 3); if (face_count) { PoolVector<Face3>::Read r = p_face_array.read(); PoolVector<Vector3>::Write w = vertices.write(); for (int i = 0; i < face_count; i++) { for (int j = 0; j < 3; j++) w[i * 3 + j] = r[i].vertex[j]; } r = PoolVector<Face3>::Read(); w = PoolVector<Vector3>::Write(); } type = NIL; *this = vertices; } /* helpers */ Variant::Variant(const Vector<Variant> &p_array) { type = NIL; Array v; int len = p_array.size(); v.resize(len); for (int i = 0; i < len; i++) v.set(i, p_array[i]); *this = v; } Variant::Variant(const Vector<uint8_t> &p_array) { type = NIL; PoolVector<uint8_t> v; int len = p_array.size(); v.resize(len); for (int i = 0; i < len; i++) v.set(i, p_array[i]); *this = v; } Variant::Variant(const Vector<int> &p_array) { type = NIL; PoolVector<int> v; int len = p_array.size(); v.resize(len); for (int i = 0; i < len; i++) v.set(i, p_array[i]); *this = v; } Variant::Variant(const Vector<real_t> &p_array) { type = NIL; PoolVector<real_t> v; int len = p_array.size(); v.resize(len); for (int i = 0; i < len; i++) v.set(i, p_array[i]); *this = v; } Variant::Variant(const Vector<String> &p_array) { type = NIL; PoolVector<String> v; int len = p_array.size(); v.resize(len); for (int i = 0; i < len; i++) v.set(i, p_array[i]); *this = v; } Variant::Variant(const Vector<Vector3> &p_array) { type = NIL; PoolVector<Vector3> v; int len = p_array.size(); if (len > 0) { v.resize(len); PoolVector<Vector3>::Write w = v.write(); const Vector3 *r = p_array.ptr(); for (int i = 0; i < len; i++) w[i] = r[i]; } *this = v; } Variant::Variant(const Vector<Color> &p_array) { type = NIL; PoolVector<Color> v; int len = p_array.size(); v.resize(len); for (int i = 0; i < len; i++) v.set(i, p_array[i]); *this = v; } void Variant::operator=(const Variant &p_variant) { if (unlikely(this == &p_variant)) return; if (unlikely(type != p_variant.type)) { reference(p_variant); return; } switch (p_variant.type) { case NIL: { // none } break; // atomic types case BOOL: { _data._bool = p_variant._data._bool; } break; case INT: { _data._int = p_variant._data._int; } break; case REAL: { _data._real = p_variant._data._real; } break; case STRING: { *reinterpret_cast<String *>(_data._mem) = *reinterpret_cast<const String *>(p_variant._data._mem); } break; // math types case VECTOR2: { *reinterpret_cast<Vector2 *>(_data._mem) = *reinterpret_cast<const Vector2 *>(p_variant._data._mem); } break; case RECT2: { *reinterpret_cast<Rect2 *>(_data._mem) = *reinterpret_cast<const Rect2 *>(p_variant._data._mem); } break; case TRANSFORM2D: { *_data._transform2d = *(p_variant._data._transform2d); } break; case VECTOR3: { *reinterpret_cast<Vector3 *>(_data._mem) = *reinterpret_cast<const Vector3 *>(p_variant._data._mem); } break; case PLANE: { *reinterpret_cast<Plane *>(_data._mem) = *reinterpret_cast<const Plane *>(p_variant._data._mem); } break; case AABB: { *_data._aabb = *(p_variant._data._aabb); } break; case QUAT: { *reinterpret_cast<Quat *>(_data._mem) = *reinterpret_cast<const Quat *>(p_variant._data._mem); } break; case BASIS: { *_data._basis = *(p_variant._data._basis); } break; case TRANSFORM: { *_data._transform = *(p_variant._data._transform); } break; // misc types case COLOR: { *reinterpret_cast<Color *>(_data._mem) = *reinterpret_cast<const Color *>(p_variant._data._mem); } break; case _RID: { *reinterpret_cast<RID *>(_data._mem) = *reinterpret_cast<const RID *>(p_variant._data._mem); } break; case OBJECT: { *reinterpret_cast<ObjData *>(_data._mem) = p_variant._get_obj(); } break; case NODE_PATH: { *reinterpret_cast<NodePath *>(_data._mem) = *reinterpret_cast<const NodePath *>(p_variant._data._mem); } break; case DICTIONARY: { *reinterpret_cast<Dictionary *>(_data._mem) = *reinterpret_cast<const Dictionary *>(p_variant._data._mem); } break; case ARRAY: { *reinterpret_cast<Array *>(_data._mem) = *reinterpret_cast<const Array *>(p_variant._data._mem); } break; // arrays case POOL_BYTE_ARRAY: { *reinterpret_cast<PoolVector<uint8_t> *>(_data._mem) = *reinterpret_cast<const PoolVector<uint8_t> *>(p_variant._data._mem); } break; case POOL_INT_ARRAY: { *reinterpret_cast<PoolVector<int> *>(_data._mem) = *reinterpret_cast<const PoolVector<int> *>(p_variant._data._mem); } break; case POOL_REAL_ARRAY: { *reinterpret_cast<PoolVector<real_t> *>(_data._mem) = *reinterpret_cast<const PoolVector<real_t> *>(p_variant._data._mem); } break; case POOL_STRING_ARRAY: { *reinterpret_cast<PoolVector<String> *>(_data._mem) = *reinterpret_cast<const PoolVector<String> *>(p_variant._data._mem); } break; case POOL_VECTOR2_ARRAY: { *reinterpret_cast<PoolVector<Vector2> *>(_data._mem) = *reinterpret_cast<const PoolVector<Vector2> *>(p_variant._data._mem); } break; case POOL_VECTOR3_ARRAY: { *reinterpret_cast<PoolVector<Vector3> *>(_data._mem) = *reinterpret_cast<const PoolVector<Vector3> *>(p_variant._data._mem); } break; case POOL_COLOR_ARRAY: { *reinterpret_cast<PoolVector<Color> *>(_data._mem) = *reinterpret_cast<const PoolVector<Color> *>(p_variant._data._mem); } break; default: {} } } Variant::Variant(const IP_Address &p_address) { type = STRING; memnew_placement(_data._mem, String(p_address)); } Variant::Variant(const Variant &p_variant) { type = NIL; reference(p_variant); } /* Variant::~Variant() { clear(); }*/ uint32_t Variant::hash() const { switch (type) { case NIL: { return 0; } break; case BOOL: { return _data._bool ? 1 : 0; } break; case INT: { return _data._int; } break; case REAL: { return hash_djb2_one_float(_data._real); } break; case STRING: { return reinterpret_cast<const String *>(_data._mem)->hash(); } break; // math types case VECTOR2: { uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Vector2 *>(_data._mem)->x); return hash_djb2_one_float(reinterpret_cast<const Vector2 *>(_data._mem)->y, hash); } break; case RECT2: { uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Rect2 *>(_data._mem)->position.x); hash = hash_djb2_one_float(reinterpret_cast<const Rect2 *>(_data._mem)->position.y, hash); hash = hash_djb2_one_float(reinterpret_cast<const Rect2 *>(_data._mem)->size.x, hash); return hash_djb2_one_float(reinterpret_cast<const Rect2 *>(_data._mem)->size.y, hash); } break; case TRANSFORM2D: { uint32_t hash = 5831; for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { hash = hash_djb2_one_float(_data._transform2d->elements[i][j], hash); } } return hash; } break; case VECTOR3: { uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Vector3 *>(_data._mem)->x); hash = hash_djb2_one_float(reinterpret_cast<const Vector3 *>(_data._mem)->y, hash); return hash_djb2_one_float(reinterpret_cast<const Vector3 *>(_data._mem)->z, hash); } break; case PLANE: { uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Plane *>(_data._mem)->normal.x); hash = hash_djb2_one_float(reinterpret_cast<const Plane *>(_data._mem)->normal.y, hash); hash = hash_djb2_one_float(reinterpret_cast<const Plane *>(_data._mem)->normal.z, hash); return hash_djb2_one_float(reinterpret_cast<const Plane *>(_data._mem)->d, hash); } break; /* case QUAT: { } break;*/ case AABB: { uint32_t hash = 5831; for (int i = 0; i < 3; i++) { hash = hash_djb2_one_float(_data._aabb->position[i], hash); hash = hash_djb2_one_float(_data._aabb->size[i], hash); } return hash; } break; case QUAT: { uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Quat *>(_data._mem)->x); hash = hash_djb2_one_float(reinterpret_cast<const Quat *>(_data._mem)->y, hash); hash = hash_djb2_one_float(reinterpret_cast<const Quat *>(_data._mem)->z, hash); return hash_djb2_one_float(reinterpret_cast<const Quat *>(_data._mem)->w, hash); } break; case BASIS: { uint32_t hash = 5831; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { hash = hash_djb2_one_float(_data._basis->elements[i][j], hash); } } return hash; } break; case TRANSFORM: { uint32_t hash = 5831; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { hash = hash_djb2_one_float(_data._transform->basis.elements[i][j], hash); } hash = hash_djb2_one_float(_data._transform->origin[i], hash); } return hash; } break; // misc types case COLOR: { uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Color *>(_data._mem)->r); hash = hash_djb2_one_float(reinterpret_cast<const Color *>(_data._mem)->g, hash); hash = hash_djb2_one_float(reinterpret_cast<const Color *>(_data._mem)->b, hash); return hash_djb2_one_float(reinterpret_cast<const Color *>(_data._mem)->a, hash); } break; case _RID: { return hash_djb2_one_64(reinterpret_cast<const RID *>(_data._mem)->get_id()); } break; case OBJECT: { return hash_djb2_one_64(make_uint64_t(_get_obj().obj)); } break; case NODE_PATH: { return reinterpret_cast<const NodePath *>(_data._mem)->hash(); } break; case DICTIONARY: { return reinterpret_cast<const Dictionary *>(_data._mem)->hash(); } break; case ARRAY: { const Array &arr = *reinterpret_cast<const Array *>(_data._mem); return arr.hash(); } break; case POOL_BYTE_ARRAY: { const PoolVector<uint8_t> &arr = *reinterpret_cast<const PoolVector<uint8_t> *>(_data._mem); int len = arr.size(); PoolVector<uint8_t>::Read r = arr.read(); return hash_djb2_buffer((uint8_t *)&r[0], len); } break; case POOL_INT_ARRAY: { const PoolVector<int> &arr = *reinterpret_cast<const PoolVector<int> *>(_data._mem); int len = arr.size(); PoolVector<int>::Read r = arr.read(); return hash_djb2_buffer((uint8_t *)&r[0], len * sizeof(int)); } break; case POOL_REAL_ARRAY: { const PoolVector<real_t> &arr = *reinterpret_cast<const PoolVector<real_t> *>(_data._mem); int len = arr.size(); PoolVector<real_t>::Read r = arr.read(); return hash_djb2_buffer((uint8_t *)&r[0], len * sizeof(real_t)); } break; case POOL_STRING_ARRAY: { uint32_t hash = 5831; const PoolVector<String> &arr = *reinterpret_cast<const PoolVector<String> *>(_data._mem); int len = arr.size(); PoolVector<String>::Read r = arr.read(); for (int i = 0; i < len; i++) { hash = hash_djb2_one_32(r[i].hash(), hash); } return hash; } break; case POOL_VECTOR2_ARRAY: { uint32_t hash = 5831; const PoolVector<Vector2> &arr = *reinterpret_cast<const PoolVector<Vector2> *>(_data._mem); int len = arr.size(); PoolVector<Vector2>::Read r = arr.read(); for (int i = 0; i < len; i++) { hash = hash_djb2_one_float(r[i].x, hash); hash = hash_djb2_one_float(r[i].y, hash); } return hash; } break; case POOL_VECTOR3_ARRAY: { uint32_t hash = 5831; const PoolVector<Vector3> &arr = *reinterpret_cast<const PoolVector<Vector3> *>(_data._mem); int len = arr.size(); PoolVector<Vector3>::Read r = arr.read(); for (int i = 0; i < len; i++) { hash = hash_djb2_one_float(r[i].x, hash); hash = hash_djb2_one_float(r[i].y, hash); hash = hash_djb2_one_float(r[i].z, hash); } return hash; } break; case POOL_COLOR_ARRAY: { uint32_t hash = 5831; const PoolVector<Color> &arr = *reinterpret_cast<const PoolVector<Color> *>(_data._mem); int len = arr.size(); PoolVector<Color>::Read r = arr.read(); for (int i = 0; i < len; i++) { hash = hash_djb2_one_float(r[i].r, hash); hash = hash_djb2_one_float(r[i].g, hash); hash = hash_djb2_one_float(r[i].b, hash); hash = hash_djb2_one_float(r[i].a, hash); } return hash; } break; default: {} } return 0; } #define hash_compare_scalar(p_lhs, p_rhs) \ ((p_lhs) == (p_rhs)) || (Math::is_nan(p_lhs) && Math::is_nan(p_rhs)) #define hash_compare_vector2(p_lhs, p_rhs) \ (hash_compare_scalar((p_lhs).x, (p_rhs).x)) && \ (hash_compare_scalar((p_lhs).y, (p_rhs).y)) #define hash_compare_vector3(p_lhs, p_rhs) \ (hash_compare_scalar((p_lhs).x, (p_rhs).x)) && \ (hash_compare_scalar((p_lhs).y, (p_rhs).y)) && \ (hash_compare_scalar((p_lhs).z, (p_rhs).z)) #define hash_compare_quat(p_lhs, p_rhs) \ (hash_compare_scalar((p_lhs).x, (p_rhs).x)) && \ (hash_compare_scalar((p_lhs).y, (p_rhs).y)) && \ (hash_compare_scalar((p_lhs).z, (p_rhs).z)) && \ (hash_compare_scalar((p_lhs).w, (p_rhs).w)) #define hash_compare_color(p_lhs, p_rhs) \ (hash_compare_scalar((p_lhs).r, (p_rhs).r)) && \ (hash_compare_scalar((p_lhs).g, (p_rhs).g)) && \ (hash_compare_scalar((p_lhs).b, (p_rhs).b)) && \ (hash_compare_scalar((p_lhs).a, (p_rhs).a)) #define hash_compare_pool_array(p_lhs, p_rhs, p_type, p_compare_func) \ const PoolVector<p_type> &l = *reinterpret_cast<const PoolVector<p_type> *>(p_lhs); \ const PoolVector<p_type> &r = *reinterpret_cast<const PoolVector<p_type> *>(p_rhs); \ \ if (l.size() != r.size()) \ return false; \ \ PoolVector<p_type>::Read lr = l.read(); \ PoolVector<p_type>::Read rr = r.read(); \ \ for (int i = 0; i < l.size(); ++i) { \ if (!p_compare_func((lr[i]), (rr[i]))) \ return false; \ } \ \ return true bool Variant::hash_compare(const Variant &p_variant) const { if (type != p_variant.type) return false; switch (type) { case REAL: { return hash_compare_scalar(_data._real, p_variant._data._real); } break; case VECTOR2: { const Vector2 *l = reinterpret_cast<const Vector2 *>(_data._mem); const Vector2 *r = reinterpret_cast<const Vector2 *>(p_variant._data._mem); return hash_compare_vector2(*l, *r); } break; case RECT2: { const Rect2 *l = reinterpret_cast<const Rect2 *>(_data._mem); const Rect2 *r = reinterpret_cast<const Rect2 *>(p_variant._data._mem); return (hash_compare_vector2(l->position, r->position)) && (hash_compare_vector2(l->size, r->size)); } break; case TRANSFORM2D: { Transform2D *l = _data._transform2d; Transform2D *r = p_variant._data._transform2d; for (int i = 0; i < 3; i++) { if (!(hash_compare_vector2(l->elements[i], r->elements[i]))) return false; } return true; } break; case VECTOR3: { const Vector3 *l = reinterpret_cast<const Vector3 *>(_data._mem); const Vector3 *r = reinterpret_cast<const Vector3 *>(p_variant._data._mem); return hash_compare_vector3(*l, *r); } break; case PLANE: { const Plane *l = reinterpret_cast<const Plane *>(_data._mem); const Plane *r = reinterpret_cast<const Plane *>(p_variant._data._mem); return (hash_compare_vector3(l->normal, r->normal)) && (hash_compare_scalar(l->d, r->d)); } break; case AABB: { const ::AABB *l = _data._aabb; const ::AABB *r = p_variant._data._aabb; return (hash_compare_vector3(l->position, r->position) && (hash_compare_vector3(l->size, r->size))); } break; case QUAT: { const Quat *l = reinterpret_cast<const Quat *>(_data._mem); const Quat *r = reinterpret_cast<const Quat *>(p_variant._data._mem); return hash_compare_quat(*l, *r); } break; case BASIS: { const Basis *l = _data._basis; const Basis *r = p_variant._data._basis; for (int i = 0; i < 3; i++) { if (!(hash_compare_vector3(l->elements[i], r->elements[i]))) return false; } return true; } break; case TRANSFORM: { const Transform *l = _data._transform; const Transform *r = p_variant._data._transform; for (int i = 0; i < 3; i++) { if (!(hash_compare_vector3(l->basis.elements[i], r->basis.elements[i]))) return false; } return hash_compare_vector3(l->origin, r->origin); } break; case COLOR: { const Color *l = reinterpret_cast<const Color *>(_data._mem); const Color *r = reinterpret_cast<const Color *>(p_variant._data._mem); return hash_compare_color(*l, *r); } break; case ARRAY: { const Array &l = *(reinterpret_cast<const Array *>(_data._mem)); const Array &r = *(reinterpret_cast<const Array *>(p_variant._data._mem)); if (l.size() != r.size()) return false; for (int i = 0; i < l.size(); ++i) { if (!l[i].hash_compare(r[i])) return false; } return true; } break; case POOL_REAL_ARRAY: { hash_compare_pool_array(_data._mem, p_variant._data._mem, real_t, hash_compare_scalar); } break; case POOL_VECTOR2_ARRAY: { hash_compare_pool_array(_data._mem, p_variant._data._mem, Vector2, hash_compare_vector2); } break; case POOL_VECTOR3_ARRAY: { hash_compare_pool_array(_data._mem, p_variant._data._mem, Vector3, hash_compare_vector3); } break; case POOL_COLOR_ARRAY: { hash_compare_pool_array(_data._mem, p_variant._data._mem, Color, hash_compare_color); } break; default: bool v; Variant r; evaluate(OP_EQUAL, *this, p_variant, r, v); return r; } return false; } bool Variant::is_ref() const { return type == OBJECT && !_get_obj().ref.is_null(); } Vector<Variant> varray() { return Vector<Variant>(); } Vector<Variant> varray(const Variant &p_arg1) { Vector<Variant> v; v.push_back(p_arg1); return v; } Vector<Variant> varray(const Variant &p_arg1, const Variant &p_arg2) { Vector<Variant> v; v.push_back(p_arg1); v.push_back(p_arg2); return v; } Vector<Variant> varray(const Variant &p_arg1, const Variant &p_arg2, const Variant &p_arg3) { Vector<Variant> v; v.push_back(p_arg1); v.push_back(p_arg2); v.push_back(p_arg3); return v; } Vector<Variant> varray(const Variant &p_arg1, const Variant &p_arg2, const Variant &p_arg3, const Variant &p_arg4) { Vector<Variant> v; v.push_back(p_arg1); v.push_back(p_arg2); v.push_back(p_arg3); v.push_back(p_arg4); return v; } Vector<Variant> varray(const Variant &p_arg1, const Variant &p_arg2, const Variant &p_arg3, const Variant &p_arg4, const Variant &p_arg5) { Vector<Variant> v; v.push_back(p_arg1); v.push_back(p_arg2); v.push_back(p_arg3); v.push_back(p_arg4); v.push_back(p_arg5); return v; } void Variant::static_assign(const Variant &p_variant) { } bool Variant::is_shared() const { switch (type) { case OBJECT: return true; case ARRAY: return true; case DICTIONARY: return true; default: {} } return false; } Variant Variant::call(const StringName &p_method, VARIANT_ARG_DECLARE) { VARIANT_ARGPTRS; int argc = 0; for (int i = 0; i < VARIANT_ARG_MAX; i++) { if (argptr[i]->get_type() == Variant::NIL) break; argc++; } CallError error; Variant ret = call(p_method, argptr, argc, error); switch (error.error) { case CallError::CALL_ERROR_INVALID_ARGUMENT: { String err = "Invalid type for argument #" + itos(error.argument) + ", expected '" + Variant::get_type_name(error.expected) + "'."; ERR_PRINT(err.utf8().get_data()); } break; case CallError::CALL_ERROR_INVALID_METHOD: { String err = "Invalid method '" + p_method + "' for type '" + Variant::get_type_name(type) + "'."; ERR_PRINT(err.utf8().get_data()); } break; case CallError::CALL_ERROR_TOO_MANY_ARGUMENTS: { String err = "Too many arguments for method '" + p_method + "'"; ERR_PRINT(err.utf8().get_data()); } break; default: {} } return ret; } void Variant::construct_from_string(const String &p_string, Variant &r_value, ObjectConstruct p_obj_construct, void *p_construct_ud) { r_value = Variant(); } String Variant::get_construct_string() const { String vars; VariantWriter::write_to_string(*this, vars); return vars; } String Variant::get_call_error_text(Object *p_base, const StringName &p_method, const Variant **p_argptrs, int p_argcount, const Variant::CallError &ce) { String err_text; if (ce.error == Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) { int errorarg = ce.argument; err_text = "Cannot convert argument " + itos(errorarg + 1) + " from " + Variant::get_type_name(p_argptrs[errorarg]->get_type()) + " to " + Variant::get_type_name(ce.expected) + "."; } else if (ce.error == Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS) { err_text = "Method expected " + itos(ce.argument) + " arguments, but called with " + itos(p_argcount) + "."; } else if (ce.error == Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS) { err_text = "Method expected " + itos(ce.argument) + " arguments, but called with " + itos(p_argcount) + "."; } else if (ce.error == Variant::CallError::CALL_ERROR_INVALID_METHOD) { err_text = "Method not found."; } else if (ce.error == Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL) { err_text = "Instance is null"; } else if (ce.error == Variant::CallError::CALL_OK) { return "Call OK"; } String class_name = p_base->get_class(); Ref<Script> script = p_base->get_script(); if (script.is_valid() && script->get_path().is_resource_file()) { class_name += "(" + script->get_path().get_file() + ")"; } return "'" + class_name + "::" + String(p_method) + "': " + err_text; } String vformat(const String &p_text, const Variant &p1, const Variant &p2, const Variant &p3, const Variant &p4, const Variant &p5) { Array args; if (p1.get_type() != Variant::NIL) { args.push_back(p1); if (p2.get_type() != Variant::NIL) { args.push_back(p2); if (p3.get_type() != Variant::NIL) { args.push_back(p3); if (p4.get_type() != Variant::NIL) { args.push_back(p4); if (p5.get_type() != Variant::NIL) { args.push_back(p5); } } } } } bool error = false; String fmt = p_text.sprintf(args, &error); ERR_FAIL_COND_V(error, String()); return fmt; }
mit
pmq20/ruby-compiler
ruby/lib/rubygems/commands/build_command.rb
2702
# frozen_string_literal: true require 'rubygems/command' require 'rubygems/package' class Gem::Commands::BuildCommand < Gem::Command def initialize super 'build', 'Build a gem from a gemspec' add_option '--force', 'skip validation of the spec' do |value, options| options[:force] = true end add_option '--strict', 'consider warnings as errors when validating the spec' do |value, options| options[:strict] = true end add_option '-o', '--output FILE', 'output gem with the given filename' do |value, options| options[:output] = value end add_option '-C PATH', '', 'Run as if gem build was started in <PATH> instead of the current working directory.' do |value, options| options[:build_path] = value end end def arguments # :nodoc: "GEMSPEC_FILE gemspec file name to build a gem for" end def description # :nodoc: <<-EOF The build command allows you to create a gem from a ruby gemspec. The best way to build a gem is to use a Rakefile and the Gem::PackageTask which ships with RubyGems. The gemspec can either be created by hand or extracted from an existing gem with gem spec: $ gem unpack my_gem-1.0.gem Unpacked gem: '.../my_gem-1.0' $ gem spec my_gem-1.0.gem --ruby > my_gem-1.0/my_gem-1.0.gemspec $ cd my_gem-1.0 [edit gem contents] $ gem build my_gem-1.0.gemspec Gems can be saved to a specified filename with the output option: $ gem build my_gem-1.0.gemspec --output=release.gem EOF end def usage # :nodoc: "#{program_name} GEMSPEC_FILE" end def execute gem_name = get_one_optional_argument || find_gemspec build_gem(gem_name) end private def find_gemspec gemspecs = Dir.glob("*.gemspec").sort if gemspecs.size > 1 alert_error "Multiple gemspecs found: #{gemspecs}, please specify one" terminate_interaction(1) end gemspecs.first end def build_gem(gem_name) gemspec = File.exist?(gem_name) ? gem_name : "#{gem_name}.gemspec" if File.exist?(gemspec) spec = Gem::Specification.load(gemspec) if options[:build_path] Dir.chdir(File.dirname(gemspec)) do spec = Gem::Specification.load(File.basename(gemspec)) build_package(spec) end else build_package(spec) end else alert_error "Gemspec file not found: #{gemspec}" terminate_interaction(1) end end def build_package(spec) if spec Gem::Package.build( spec, options[:force], options[:strict], options[:output] ) else alert_error "Error loading gemspec. Aborting." terminate_interaction 1 end end end
mit
lodemo/CATANA
src/face_recognition/MtcnnModel.py
794
# -*- coding: utf-8 -*- ''' Model file module, so that model files are only loaded once when imported ''' import os import sys import tensorflow as tf from facenet.src import facenet from facenet.src.align import detect_face fileDir = os.path.dirname(os.path.realpath(__file__)) facenetDir = os.path.join(fileDir, 'facenet') facenetModelDir = os.path.join(facenetDir, 'src', 'align',) session = None graph = None # Actual models used for face detection pnet = None rnet = None onet = None graph = tf.Graph() session = tf.Session(graph=graph) #config=tf.ConfigProto(inter_op_parallelism_threads=24, intra_op_parallelism_threads=24)) with graph.as_default(): with session.as_default(): pnet, rnet, onet = detect_face.create_mtcnn(session, facenetModelDir) graph.finalize()
mit
mmckegg/mutant
lib/release-next-tick.js
321
var queue = [] module.exports = function (item) { if (queue.length === 0) { setImmediate(flush) } queue.push(item) } function flush () { while (queue.length) { var item = queue.pop() if (!item.bound && typeof item.release === 'function') { item.release() item.release = null } } }
mit
fgrid/iso20022
CashOption10.go
2937
package iso20022 // Provides information about the cash option. type CashOption10 struct { // Indicates whether the value is a debit or a credit. CreditDebitIndicator *CreditDebitCode `xml:"CdtDbtInd"` // Specifies information regarding outturn resources that cannot be processed by the Central Securities Depository (CSD). Special delivery instruction is required from the account owner for the corporate action outcome to be credited. NonEligibleProceedsIndicator *NonEligibleProceedsIndicator1Choice `xml:"NonElgblPrcdsInd,omitempty"` // Specifies the type of income. // The lists of income type codes to be used, are available on the SMPG website at www.smpg.info. IncomeType *GenericIdentification20 `xml:"IncmTp,omitempty"` // Identification of the account in which cash is maintained. CashAccountIdentification *CashAccountIdentification5Choice `xml:"CshAcctId,omitempty"` // Provides information about the amounts related to a cash movement. AmountDetails *CorporateActionAmounts10 `xml:"AmtDtls,omitempty"` // Provides information about the dates related to a cash movement. DateDetails *CorporateActionDate17 `xml:"DtDtls"` // Exchange rate between the amount and the resulting amount ForeignExchangeDetails *ForeignExchangeTerms13 `xml:"FXDtls,omitempty"` // Provides information about the corporate action option. RateAndAmountDetails *RateDetails3 `xml:"RateAndAmtDtls,omitempty"` // Provides information about the prices related to a corporate action option. PriceDetails *PriceDetails3 `xml:"PricDtls,omitempty"` } func (c *CashOption10) SetCreditDebitIndicator(value string) { c.CreditDebitIndicator = (*CreditDebitCode)(&value) } func (c *CashOption10) AddNonEligibleProceedsIndicator() *NonEligibleProceedsIndicator1Choice { c.NonEligibleProceedsIndicator = new(NonEligibleProceedsIndicator1Choice) return c.NonEligibleProceedsIndicator } func (c *CashOption10) AddIncomeType() *GenericIdentification20 { c.IncomeType = new(GenericIdentification20) return c.IncomeType } func (c *CashOption10) AddCashAccountIdentification() *CashAccountIdentification5Choice { c.CashAccountIdentification = new(CashAccountIdentification5Choice) return c.CashAccountIdentification } func (c *CashOption10) AddAmountDetails() *CorporateActionAmounts10 { c.AmountDetails = new(CorporateActionAmounts10) return c.AmountDetails } func (c *CashOption10) AddDateDetails() *CorporateActionDate17 { c.DateDetails = new(CorporateActionDate17) return c.DateDetails } func (c *CashOption10) AddForeignExchangeDetails() *ForeignExchangeTerms13 { c.ForeignExchangeDetails = new(ForeignExchangeTerms13) return c.ForeignExchangeDetails } func (c *CashOption10) AddRateAndAmountDetails() *RateDetails3 { c.RateAndAmountDetails = new(RateDetails3) return c.RateAndAmountDetails } func (c *CashOption10) AddPriceDetails() *PriceDetails3 { c.PriceDetails = new(PriceDetails3) return c.PriceDetails }
mit
artofhuman/django-youtube-wrapper
youtube_wrapper/tests/test_field.py
1851
# coding: utf-8 from django.test import TestCase from django import forms from django.db import models from ..fields import YoutubeField class TestModel(models.Model): youtube = YoutubeField() class TestModelForm(forms.ModelForm): class Meta: model = TestModel class FormTest(TestCase): def test_validation(self): form = TestModelForm(data={'youtube': 'http://youtu.be/jRKrZ6X5WSw'}) self.assertTrue(form.is_valid()) invalid = TestModelForm(data={'youtube': 'http://yandex.ru'}) self.assertFalse(invalid.is_valid()) self.assertTrue('Invalid youtube url' in str(invalid.errors)) invalid = TestModelForm(data={'youtube': 'http://youtu.be/'}) self.assertFalse(invalid.is_valid()) self.assertTrue('Youtube url has not video param' in str(invalid.errors)) class FieldTest(TestCase): def setUp(self): self.video_url = 'http://youtu.be/jRKrZ6X5WSw' self.field = YoutubeField() def test_to_python(self): self.res = self.field.to_python(self.video_url) self.assertEqual(u'http://youtu.be/jRKrZ6X5WSw', self.res) def test_video_id(self): self.assertEqual(u'jRKrZ6X5WSw', self.field.to_python(self.video_url).video_id) def test_embed_url(self): expected = u'http://youtube.com/embed/jRKrZ6X5WSw/' self.assertEqual(expected, self.field.to_python(self.video_url).embed_url) def test_images(self): default_image_url = 'http://img.youtube.com/vi/jRKrZ6X5WSw/0.jpg' thumb_url = 'http://img.youtube.com/vi/jRKrZ6X5WSw/1.jpg' self.assertEqual(default_image_url, self.field.to_python(self.video_url).default_image_url) self.assertEqual(thumb_url, self.field.to_python(self.video_url).thumb_url)
mit
sburnett/seattle
repy/tests/ut_repytests_testremovefilefnf.py
88
#pragma error #pragma repy removefile("this.file.does.not.exist") # should fail (FNF)
mit
juan-urtazun/Taller_de_Software
app/cache/dev/assetic/config/1/1f046d9a4caab1d49db643c62dcabba9.php
65
<?php // BackendBundle:Persona:show.html.twig return array ( );
mit
fanlinchong/TechMixture
TechMixture.Blog.Domain.Repositories/EntityFramework/BlogContext.cs
1124
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; using TechMixture.Blog.Domain.Model; using TechMixture.Blog.Domain.Repositories.EntityFramework.ModelConfigurations; namespace TechMixture.Blog.Domain.Repositories.EntityFramework { public sealed class BlogContext:DbContext { public BlogContext():base("blog") { } public DbSet<Post> Posts { get { return Set<Post>(); } } public DbSet<Comment> Comments { get { return Set<Comment>(); } } public DbSet<Category> Categories { get { return Set<Category>(); } } public DbSet<Tag> Tags { get { return Set<Tag>(); } } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Configurations .Add(new PostTypeConfiguration()) .Add(new CommentTypeConfiguration()) .Add(new CategoryTypeConfiguration()) .Add(new TagTypeConfiguration()); base.OnModelCreating(modelBuilder); } } }
mit
wizawu/1c
@types/jdk/java.nio.file.OpenOption.d.ts
115
declare namespace java { namespace nio { namespace file { interface OpenOption { } } } }
mit
tomlandau/material2-new
src/lib/sidenav/sidenav.spec.ts
19030
import {fakeAsync, async, tick, ComponentFixture, TestBed} from '@angular/core/testing'; import {Component, ElementRef, ViewChild} from '@angular/core'; import {By} from '@angular/platform-browser'; import {MdSidenav, MdSidenavModule, MdSidenavContainer} from './index'; import {A11yModule} from '@angular/cdk'; import {PlatformModule} from '@angular/cdk'; import {ESCAPE} from '../core/keyboard/keycodes'; function endSidenavTransition(fixture: ComponentFixture<any>) { let sidenav: any = fixture.debugElement.query(By.directive(MdSidenav)).componentInstance; sidenav._onTransitionEnd(<any> { target: (<any>sidenav)._elementRef.nativeElement, propertyName: 'transform' }); fixture.detectChanges(); } describe('MdSidenav', () => { beforeEach(async(() => { TestBed.configureTestingModule({ imports: [MdSidenavModule, A11yModule, PlatformModule], declarations: [ BasicTestApp, SidenavContainerNoSidenavTestApp, SidenavSetToOpenedFalse, SidenavSetToOpenedTrue, SidenavDynamicAlign, SidenavWitFocusableElements, ], }); TestBed.compileComponents(); })); describe('methods', () => { it('should be able to open and close', fakeAsync(() => { let fixture = TestBed.createComponent(BasicTestApp); let testComponent: BasicTestApp = fixture.debugElement.componentInstance; let openButtonElement = fixture.debugElement.query(By.css('.open')); openButtonElement.nativeElement.click(); fixture.detectChanges(); tick(); expect(testComponent.openStartCount).toBe(1); expect(testComponent.openCount).toBe(0); endSidenavTransition(fixture); tick(); expect(testComponent.openStartCount).toBe(1); expect(testComponent.openCount).toBe(1); expect(testComponent.closeStartCount).toBe(0); expect(testComponent.closeCount).toBe(0); let sidenavElement = fixture.debugElement.query(By.css('md-sidenav')); let sidenavBackdropElement = fixture.debugElement.query(By.css('.mat-sidenav-backdrop')); expect(getComputedStyle(sidenavElement.nativeElement).visibility).toEqual('visible'); expect(getComputedStyle(sidenavBackdropElement.nativeElement).visibility) .toEqual('visible'); // Close it. let closeButtonElement = fixture.debugElement.query(By.css('.close')); closeButtonElement.nativeElement.click(); fixture.detectChanges(); tick(); expect(testComponent.openStartCount).toBe(1); expect(testComponent.openCount).toBe(1); expect(testComponent.closeStartCount).toBe(1); expect(testComponent.closeCount).toBe(0); endSidenavTransition(fixture); tick(); expect(testComponent.openStartCount).toBe(1); expect(testComponent.openCount).toBe(1); expect(testComponent.closeStartCount).toBe(1); expect(testComponent.closeCount).toBe(1); expect(getComputedStyle(sidenavElement.nativeElement).visibility).toEqual('hidden'); expect(getComputedStyle(sidenavBackdropElement.nativeElement).visibility).toEqual('hidden'); })); it('open/close() return a promise that resolves after animation end', fakeAsync(() => { let fixture = TestBed.createComponent(BasicTestApp); let sidenav: MdSidenav = fixture.debugElement .query(By.directive(MdSidenav)).componentInstance; let called = false; sidenav.open().then(() => { called = true; }); expect(called).toBe(false); endSidenavTransition(fixture); tick(); expect(called).toBe(true); called = false; sidenav.close().then(() => { called = true; }); expect(called).toBe(false); endSidenavTransition(fixture); tick(); expect(called).toBe(true); })); it('open/close() twice returns the same promise', fakeAsync(() => { let fixture = TestBed.createComponent(BasicTestApp); let sidenav: MdSidenav = fixture.debugElement .query(By.directive(MdSidenav)).componentInstance; let promise = sidenav.open(); expect(sidenav.open()).toBe(promise); fixture.detectChanges(); tick(); promise = sidenav.close(); expect(sidenav.close()).toBe(promise); tick(); })); it('open() then close() cancel animations when called too fast', fakeAsync(() => { let fixture = TestBed.createComponent(BasicTestApp); let sidenav: MdSidenav = fixture.debugElement .query(By.directive(MdSidenav)).componentInstance; sidenav.open().then(openResult => { expect(openResult.type).toBe('open'); expect(openResult.animationFinished).toBe(false); }); // We do not call transition end, close directly. sidenav.close().then(closeResult => { expect(closeResult.type).toBe('close'); expect(closeResult.animationFinished).toBe(true); }); endSidenavTransition(fixture); tick(); })); it('close() then open() cancel animations when called too fast', fakeAsync(() => { let fixture = TestBed.createComponent(BasicTestApp); let sidenav: MdSidenav = fixture.debugElement .query(By.directive(MdSidenav)).componentInstance; // First, open the sidenav completely. sidenav.open(); endSidenavTransition(fixture); tick(); // Then close and check behavior. sidenav.close().then(closeResult => { expect(closeResult.type).toBe('close'); expect(closeResult.animationFinished).toBe(false); }); // We do not call transition end, open directly. sidenav.open().then(openResult => { expect(openResult.type).toBe('open'); expect(openResult.animationFinished).toBe(true); }); endSidenavTransition(fixture); tick(); })); it('does not throw when created without a sidenav', fakeAsync(() => { expect(() => { let fixture = TestBed.createComponent(BasicTestApp); fixture.detectChanges(); tick(); }).not.toThrow(); })); it('should emit the backdropClick event when the backdrop is clicked', fakeAsync(() => { let fixture = TestBed.createComponent(BasicTestApp); let testComponent: BasicTestApp = fixture.debugElement.componentInstance; let openButtonElement = fixture.debugElement.query(By.css('.open')); openButtonElement.nativeElement.click(); fixture.detectChanges(); tick(); endSidenavTransition(fixture); tick(); expect(testComponent.backdropClickedCount).toBe(0); let sidenavBackdropElement = fixture.debugElement.query(By.css('.mat-sidenav-backdrop')); sidenavBackdropElement.nativeElement.click(); fixture.detectChanges(); tick(); expect(testComponent.backdropClickedCount).toBe(1); endSidenavTransition(fixture); tick(); openButtonElement.nativeElement.click(); fixture.detectChanges(); tick(); endSidenavTransition(fixture); tick(); let closeButtonElement = fixture.debugElement.query(By.css('.close')); closeButtonElement.nativeElement.click(); fixture.detectChanges(); tick(); endSidenavTransition(fixture); tick(); expect(testComponent.backdropClickedCount).toBe(1); })); it('should close when pressing escape', fakeAsync(() => { let fixture = TestBed.createComponent(BasicTestApp); let testComponent: BasicTestApp = fixture.debugElement.componentInstance; let sidenav: MdSidenav = fixture.debugElement .query(By.directive(MdSidenav)).componentInstance; sidenav.open(); fixture.detectChanges(); endSidenavTransition(fixture); tick(); expect(testComponent.openCount).toBe(1); expect(testComponent.closeCount).toBe(0); // Simulate pressing the escape key. sidenav.handleKeydown({ keyCode: ESCAPE, stopPropagation: () => {} } as KeyboardEvent); fixture.detectChanges(); endSidenavTransition(fixture); tick(); expect(testComponent.closeCount).toBe(1); })); it('should not close by pressing escape when disableClose is set', fakeAsync(() => { let fixture = TestBed.createComponent(BasicTestApp); let testComponent = fixture.debugElement.componentInstance; let sidenav = fixture.debugElement.query(By.directive(MdSidenav)).componentInstance; sidenav.disableClose = true; sidenav.open(); fixture.detectChanges(); endSidenavTransition(fixture); tick(); sidenav.handleKeydown({ keyCode: ESCAPE, stopPropagation: () => {} }); fixture.detectChanges(); endSidenavTransition(fixture); tick(); expect(testComponent.closeCount).toBe(0); })); it('should not close by clicking on the backdrop when disableClose is set', fakeAsync(() => { let fixture = TestBed.createComponent(BasicTestApp); let testComponent = fixture.debugElement.componentInstance; let sidenav = fixture.debugElement.query(By.directive(MdSidenav)).componentInstance; sidenav.disableClose = true; sidenav.open(); fixture.detectChanges(); endSidenavTransition(fixture); tick(); let backdropEl = fixture.debugElement.query(By.css('.mat-sidenav-backdrop')).nativeElement; backdropEl.click(); fixture.detectChanges(); tick(); fixture.detectChanges(); endSidenavTransition(fixture); tick(); expect(testComponent.closeCount).toBe(0); })); it('should restore focus on close if focus is inside sidenav', fakeAsync(() => { let fixture = TestBed.createComponent(BasicTestApp); let sidenav: MdSidenav = fixture.debugElement .query(By.directive(MdSidenav)).componentInstance; let openButton = fixture.componentInstance.openButton.nativeElement; let sidenavButton = fixture.componentInstance.sidenavButton.nativeElement; openButton.focus(); sidenav.open(); fixture.detectChanges(); endSidenavTransition(fixture); tick(); sidenavButton.focus(); sidenav.close(); fixture.detectChanges(); endSidenavTransition(fixture); tick(); expect(document.activeElement) .toBe(openButton, 'Expected focus to be restored to the open button on close.'); })); it('should not restore focus on close if focus is outside sidenav', fakeAsync(() => { let fixture = TestBed.createComponent(BasicTestApp); let sidenav: MdSidenav = fixture.debugElement .query(By.directive(MdSidenav)).componentInstance; let openButton = fixture.componentInstance.openButton.nativeElement; let closeButton = fixture.componentInstance.closeButton.nativeElement; openButton.focus(); sidenav.open(); fixture.detectChanges(); endSidenavTransition(fixture); tick(); closeButton.focus(); sidenav.close(); fixture.detectChanges(); endSidenavTransition(fixture); tick(); expect(document.activeElement) .toBe(closeButton, 'Expected focus not to be restored to the open button on close.'); })); }); describe('attributes', () => { it('should correctly parse opened="false"', () => { let fixture = TestBed.createComponent(SidenavSetToOpenedFalse); fixture.detectChanges(); let sidenavEl = fixture.debugElement.query(By.css('md-sidenav')).nativeElement; expect(sidenavEl.classList).toContain('mat-sidenav-closed'); expect(sidenavEl.classList).not.toContain('mat-sidenav-opened'); }); it('should correctly parse opened="true"', () => { let fixture = TestBed.createComponent(SidenavSetToOpenedTrue); fixture.detectChanges(); endSidenavTransition(fixture); let sidenavEl = fixture.debugElement.query(By.css('md-sidenav')).nativeElement; let testComponent = fixture.debugElement.query(By.css('md-sidenav')).componentInstance; expect(sidenavEl.classList).not.toContain('mat-sidenav-closed'); expect(sidenavEl.classList).toContain('mat-sidenav-opened'); expect((testComponent as any)._toggleAnimationPromise).toBeNull(); }); it('should remove align attr from DOM', () => { const fixture = TestBed.createComponent(BasicTestApp); fixture.detectChanges(); const sidenavEl = fixture.debugElement.query(By.css('md-sidenav')).nativeElement; expect(sidenavEl.hasAttribute('align')) .toBe(false, 'Expected sidenav not to have a native align attribute.'); }); it('should throw when multiple sidenavs have the same align', () => { const fixture = TestBed.createComponent(SidenavDynamicAlign); fixture.detectChanges(); const testComponent: SidenavDynamicAlign = fixture.debugElement.componentInstance; testComponent.sidenav1Align = 'end'; expect(() => fixture.detectChanges()).toThrow(); }); it('should not throw when sidenavs swap sides', () => { const fixture = TestBed.createComponent(SidenavDynamicAlign); fixture.detectChanges(); const testComponent: SidenavDynamicAlign = fixture.debugElement.componentInstance; testComponent.sidenav1Align = 'end'; testComponent.sidenav2Align = 'start'; expect(() => fixture.detectChanges()).not.toThrow(); }); }); describe('focus trapping behavior', () => { let fixture: ComponentFixture<SidenavWitFocusableElements>; let testComponent: SidenavWitFocusableElements; let sidenav: MdSidenav; let firstFocusableElement: HTMLElement; let lastFocusableElement: HTMLElement; beforeEach(() => { fixture = TestBed.createComponent(SidenavWitFocusableElements); testComponent = fixture.debugElement.componentInstance; sidenav = fixture.debugElement.query(By.directive(MdSidenav)).componentInstance; firstFocusableElement = fixture.debugElement.query(By.css('.link1')).nativeElement; lastFocusableElement = fixture.debugElement.query(By.css('.link1')).nativeElement; lastFocusableElement.focus(); }); it('should trap focus when opened in "over" mode', fakeAsync(() => { testComponent.mode = 'over'; lastFocusableElement.focus(); sidenav.open(); endSidenavTransition(fixture); tick(); expect(document.activeElement).toBe(firstFocusableElement); })); it('should trap focus when opened in "push" mode', fakeAsync(() => { testComponent.mode = 'push'; lastFocusableElement.focus(); sidenav.open(); endSidenavTransition(fixture); tick(); expect(document.activeElement).toBe(firstFocusableElement); })); it('should not trap focus when opened in "side" mode', fakeAsync(() => { testComponent.mode = 'side'; lastFocusableElement.focus(); sidenav.open(); endSidenavTransition(fixture); tick(); expect(document.activeElement).toBe(lastFocusableElement); })); }); }); describe('MdSidenavContainer', () => { beforeEach(async(() => { TestBed.configureTestingModule({ imports: [MdSidenavModule, A11yModule, PlatformModule], declarations: [ SidenavContainerTwoSidenavTestApp ], }); TestBed.compileComponents(); })); describe('methods', () => { it('should be able to open and close', async(() => { const fixture = TestBed.createComponent(SidenavContainerTwoSidenavTestApp); fixture.detectChanges(); const testComponent: SidenavContainerTwoSidenavTestApp = fixture.debugElement.componentInstance; const sidenavs = fixture.debugElement.queryAll(By.directive(MdSidenav)); expect(sidenavs.every(sidenav => sidenav.componentInstance.opened)).toBeFalsy(); return testComponent.sidenavContainer.open() .then(() => { expect(sidenavs.every(sidenav => sidenav.componentInstance.opened)).toBeTruthy(); return testComponent.sidenavContainer.close(); }) .then(() => { expect(sidenavs.every(sidenav => sidenav.componentInstance.opened)).toBeTruthy(); }); })); }); }); /** Test component that contains an MdSidenavContainer but no MdSidenav. */ @Component({template: `<md-sidenav-container></md-sidenav-container>`}) class SidenavContainerNoSidenavTestApp { } /** Test component that contains an MdSidenavContainer and 2 MdSidenav on the same side. */ @Component({ template: ` <md-sidenav-container> <md-sidenav align="start"> </md-sidenav> <md-sidenav align="end"> </md-sidenav> </md-sidenav-container>`, }) class SidenavContainerTwoSidenavTestApp { @ViewChild(MdSidenavContainer) sidenavContainer: MdSidenavContainer; } /** Test component that contains an MdSidenavContainer and one MdSidenav. */ @Component({ template: ` <md-sidenav-container (backdropClick)="backdropClicked()"> <md-sidenav #sidenav align="start" (open-start)="openStart()" (open)="open()" (close-start)="closeStart()" (close)="close()"> <button #sidenavButton>Content.</button> </md-sidenav> <button (click)="sidenav.open()" class="open" #openButton></button> <button (click)="sidenav.close()" class="close" #closeButton></button> </md-sidenav-container>`, }) class BasicTestApp { openStartCount: number = 0; openCount: number = 0; closeStartCount: number = 0; closeCount: number = 0; backdropClickedCount: number = 0; @ViewChild('sidenavButton') sidenavButton: ElementRef; @ViewChild('openButton') openButton: ElementRef; @ViewChild('closeButton') closeButton: ElementRef; openStart() { this.openStartCount++; } open() { this.openCount++; } closeStart() { this.closeStartCount++; } close() { this.closeCount++; } backdropClicked() { this.backdropClickedCount++; } } @Component({ template: ` <md-sidenav-container> <md-sidenav #sidenav mode="side" opened="false"> Closed Sidenav. </md-sidenav> </md-sidenav-container>`, }) class SidenavSetToOpenedFalse { } @Component({ template: ` <md-sidenav-container> <md-sidenav #sidenav mode="side" opened="true"> Closed Sidenav. </md-sidenav> </md-sidenav-container>`, }) class SidenavSetToOpenedTrue { } @Component({ template: ` <md-sidenav-container> <md-sidenav #sidenav1 [align]="sidenav1Align"></md-sidenav> <md-sidenav #sidenav2 [align]="sidenav2Align"></md-sidenav> </md-sidenav-container>`, }) class SidenavDynamicAlign { sidenav1Align = 'start'; sidenav2Align = 'end'; } @Component({ template: ` <md-sidenav-container> <md-sidenav align="start" [mode]="mode"> <a class="link1" href="#">link1</a> </md-sidenav> <a class="link2" href="#">link2</a> </md-sidenav-container>`, }) class SidenavWitFocusableElements { mode: string = 'over'; }
mit
pegurnee/2013-01-111
Projects/P1 - Fortress Management/P1 - Fortress Management 3 with Classes Update/SinglePlayer.java
50230
/* Single player form of the game * */ import java.util.Comparator; // imports comparator import java.util.Scanner; // imports scanner import java.util.Random; // imports random import java.util.Arrays; // imports arrays import java.io.*; // imports all input/output java public class SinglePlayer { public static void run() { Scanner keyboard = new Scanner(System.in); // creates keyboard scanner Random rand = new Random(); // creates random CurrentUser user = new CurrentUser(); CommonChecks.checkDifficulty(user); StartGame.run(user); LoadGame.run(user); if (!user.loaded()) { EnterName.run(user); } LoadCustomNames.run(user); SeeIntro.run(user); GameCycle.run(user, true); int numMinions = 7, gold = 5; // defines starting variables (gold & minions) int defendBonus = 0, gatherBonus = 0, recruitBonus = 0, luck = 0; // defines premanent nighttime variables int oldNumMinions = 0; // defines temporary nighttime variables int defend = 0, gather = 0, recruit = 0; // defines daytime variables boolean fullMinions = false; // another daytime variable int difficulty = 1; // normal difficulty setting char confirm = 'y', deny = 'n'; // allows editing confirm/deny keys int day = 1, maxGold = 0, maxMinions = 0, numDragonKill = 0, numBattlesWon = 0, itemsFound = 0; // defines scoring variables boolean runGame = true; // defines the check to run the game final int CUSTOMLENGTH = 17; // sets int to establish array length String[] customNames = new String [CUSTOMLENGTH]; // defines custom name array String name = null; String fSave = "saveGame.txt"; String fLoad = "saveGame.txt"; String fName = null; final int NUMARRAYS = 4; final int NUMPERARRAY = 13; String[][] loadGame = new String [NUMARRAYS][NUMPERARRAY]; String[][] saveGame = new String [NUMARRAYS][NUMPERARRAY]; saveGame[0][0] = "13"; saveGame[1][0] = "3"; saveGame[2][0] = "3"; saveGame[3][0] = "2"; String [][] variableNames = { {"numInArrayInt", "numMinions", "gold", "defendBonus", "gatherBonus", "luck", "day", "maxGold", "maxMinions", "numDragonKill", "numBattlesWon", "itemsFound", "difficulty"}, {"numInArrayString", "name", "fName"}, {"numInArrayChar", "confirm", "deny"}, {"numInArrayBoolean", "debug", "male"} }; boolean male = true; boolean debug = false; // allows for debugging options boolean loading = false; // allows for loading save games boolean startGame = false; while (startGame != true) { String stCheckDebug = keyboard.nextLine().trim().toLowerCase(); if (stCheckDebug.isEmpty()) { startGame = true; } else if (stCheckDebug.equals("debug")) { debug = true; startGame = true; } else if (stCheckDebug.equals("hello world")) { System.out.println("Oh, I'm sorry, you are looking at the wrong program."); System.out.println("Please open some other boring program."); System.out.println("This one is too badass for that."); keyboard.nextLine(); System.exit(0); } else { } } if (loading) { boolean checkLoadGame = false; while (!checkLoadGame) { System.out.print("Would you like to load the previous save file? [y/n] "); String stLoadGame = keyboard.nextLine().trim().toLowerCase(); if (stLoadGame.isEmpty()) { System.out.println("Invalid Command."); } else if (stLoadGame.charAt(0) == 'y' || stLoadGame.charAt(0) == 'n') { if (stLoadGame.charAt(0) == 'y') { int[] loadLimit = new int[4]; fLoad = "saveGame.txt"; try { //InputStream stream = MainClass.class.getResourceAsStream(fLoad); //Scanner inLoad = new Scanner(stream); Scanner inLoad = new Scanner(new FileInputStream(fLoad)); for (int k = 0; k < NUMARRAYS; k++) { //String tempLoad = ; loadLimit[k] = Integer.parseInt(inLoad.nextLine()); for (int j = 1; j < loadLimit[k]; j++) { loadGame[k][j] = inLoad.nextLine(); } } inLoad.close(); } catch (Exception e) { System.out.println("Load failed."); System.exit(0); } for (int k = 0; k < NUMARRAYS; k++) { for (int j = 1; j < loadLimit[k]; j++) { if (variableNames[k][j].equals("numMinions")) { numMinions = Integer.parseInt(loadGame[k][j]); } else if (variableNames[k][j].equals("gold")) { gold = Integer.parseInt(loadGame[k][j]); } else if (variableNames[k][j].equals("defendBonus")) { defendBonus = Integer.parseInt(loadGame[k][j]); } else if (variableNames[k][j].equals("gatherBonus")) { gatherBonus = Integer.parseInt(loadGame[k][j]); } else if (variableNames[k][j].equals("luck")) { luck = Integer.parseInt(loadGame[k][j]); } else if (variableNames[k][j].equals("day")) { day = Integer.parseInt(loadGame[k][j]); } else if (variableNames[k][j].equals("maxMinions")) { maxMinions = Integer.parseInt(loadGame[k][j]); } else if (variableNames[k][j].equals("maxGold")) { maxGold = Integer.parseInt(loadGame[k][j]); } else if (variableNames[k][j].equals("numDragonKill")) { numDragonKill = Integer.parseInt(loadGame[k][j]); } else if (variableNames[k][j].equals("numBattlesWon")) { numBattlesWon = Integer.parseInt(loadGame[k][j]); } else if (variableNames[k][j].equals("itemsFound")) { itemsFound = Integer.parseInt(loadGame[k][j]); } else if (variableNames[k][j].equals("difficulty")) { difficulty = Integer.parseInt(loadGame[k][j]); } else if (variableNames[k][j].equals("name")) { name = loadGame[k][j]; } else if (variableNames[k][j].equals("fName")) { fName = loadGame[k][j]; } else if (variableNames[k][j].equals("confirm")) { confirm = loadGame[k][j].charAt(0); } else if (variableNames[k][j].equals("deny")) { deny = loadGame[k][j].charAt(0); } else if (variableNames[k][j].equals("debug")) { debug = Boolean.parseBoolean(loadGame[k][j]); } else if (variableNames[k][j].equals("male")) { male = Boolean.parseBoolean(loadGame[k][j]); } } } try { Scanner inName = new Scanner(new FileInputStream(fName)); for (int k = 0; k < CUSTOMLENGTH; k++) { customNames[k] = inName.nextLine(); } inName.close(); } catch (Exception e) { System.out.println("Error loading race names."); System.exit(0); } System.out.println(); System.out.println(customNames[0]); System.out.println("Welcome back, " + customNames[1] + " " + name + ". \nYour " + customNames[2] + " awaits you."); } else { loading = false; } checkLoadGame = true; } else { System.out.println("Invalid Command."); } } } if (!loading) { if (debug == true) { boolean checkCustomNames = false; while (checkCustomNames != true) { System.out.print("Would you like to enter custom system names? [y/n] "); String stCheckCustomNames = keyboard.nextLine().trim().toLowerCase(); if (stCheckCustomNames.isEmpty()) { System.out.println("Invalid Command."); } else if (stCheckCustomNames.charAt(0) == 'y' || stCheckCustomNames.charAt(0) == 'n') { if (stCheckCustomNames.charAt(0) == 'y') { boolean checkCustomLoad = false; while (checkCustomLoad != true) { System.out.print("Would you like to load a specific custom file? [y/n] "); String stCheckCustomLoad = keyboard.nextLine().trim().toLowerCase(); if (stCheckCustomLoad.isEmpty()) { System.out.println("Invalid Command."); } else if (stCheckCustomLoad.charAt(0) == 'y' || stCheckCustomLoad.charAt(0) == 'n') { if (stCheckCustomLoad.charAt(0) == 'y') { boolean confirmCustomLoad = false; while (confirmCustomLoad != true) { System.out.print("Enter complete file name (including \".txt\"): "); fName = keyboard.nextLine().trim(); int fNameLength = fName.length(); String fNameFE = fName.substring(fName.length() - 4); if (fName.isEmpty()) { System.out.println("Invalid Command."); } else if (!fNameFE.equals(".txt")) { System.out.println("Improper format."); } else { checkCustomLoad = true; } } } else { System.out.print("Enter Custom User Name: "); name = keyboard.nextLine().trim(); // creates a complete custom set of system names try { String fCustom = "10customNames.txt"; fName = "00example.txt"; String [][] exampleCustom = new String [CUSTOMLENGTH][CUSTOMLENGTH]; Scanner inName = new Scanner(new FileInputStream(fName)); PrintWriter outCustom = new PrintWriter(new FileOutputStream(fCustom)); for (int k = 0; k < CUSTOMLENGTH; k++) { exampleCustom[0][k] = inName.nextLine(); boolean checkCustom = false; while (checkCustom != true) { System.out.print("Enter custom name for \"" + exampleCustom[0][k] + "\": "); exampleCustom[1][k] = keyboard.nextLine().trim(); if (exampleCustom[1][k].isEmpty()) { System.out.println("Invalid Command."); } else { outCustom.println(exampleCustom[1][k]); checkCustom = true; } } } outCustom.close(); inName.close(); } catch (Exception e) { System.out.println("Error writing custom race names."); System.exit(0); } fName = "10customNames.txt"; } try { // loads custom names Scanner inName = new Scanner(new FileInputStream(fName)); for (int k = 0; k < CUSTOMLENGTH; k++) { customNames[k] = inName.nextLine(); } inName.close(); System.out.println("Custom names loaded from " + fName); } catch (Exception e) { System.out.println("Error reading custom race names."); System.exit(0); } checkCustomLoad = true; } else { System.out.println("Invalid Command."); } } } else { } checkCustomNames = true; } else { System.out.println("Invalid Command."); } } } System.out.println(); System.out.println(customNames[0]); System.out.println("Welcome " + customNames[1] + " " + name + ", to your new " + customNames[2] + "."); } System.out.println("__________________________________________"); System.out.println(); System.out.println("If at anytime you need to see the command"); // informs how to see commands System.out.println("choices again, just enter 'h' or '?'"); System.out.println(); System.out.println(customNames[1] + " " + name + ", your " + customNames[3] + " await:"); System.out.print("Press Enter to Play!"); keyboard.nextLine(); System.out.println("__________________________________________"); while (runGame == true) // while runGame is true, run the game; for each game period, add one day { System.out.println(); System.out.println("Press Enter to start Day " + day + ", " + customNames[1] + " " + name + "."); keyboard.nextLine(); boolean endDay = false, checkMinions = false ; // defines endDay if (day > 1 && oldNumMinions == numMinions) // on days later than day 1 and where no one died or was recruited the day before { while (checkMinions != true) { System.out.println("Would you like to keep the same number "); System.out.print("of " + customNames[4] + ", " + customNames[5] + ", and " + customNames[6] + " as yesterday? [y/n] "); // checks if user wants to keep same number of defenders, gatherers, and recruiters String sameWork = keyboard.nextLine().trim().toLowerCase(); // defines question exclusive variable if (sameWork.isEmpty() || sameWork.charAt(0) == 'y' || sameWork.charAt(0) == 'n') { if (sameWork.isEmpty() || sameWork.charAt(0) == 'y') { System.out.println(); boolean checkEndDay = false; while (checkEndDay != true) { System.out.print("Would you like to end the day? [y/n] "); // checks if the user wants to end the day String checkEnd = keyboard.nextLine().trim().toLowerCase(); // defines question exclusive variable if (checkEnd.isEmpty() || checkEnd.charAt(0) == 'y' || checkEnd.charAt(0) == 'n') { if (checkEnd.isEmpty() || checkEnd.charAt(0) == 'y') { endDay = true; // ends the day } else { } checkEndDay = true; } else { System.out.println("Invalid Command."); } } } checkMinions = true; } else { System.out.println("Invalid Command."); } } } else if (oldNumMinions != numMinions) // will reset defenders, gatherers, and recruiters if someone died { fullMinions = false; } while (endDay != true && runGame == true) // daytime of the game, assigns minions to various actions { // stCommand; // defines the command selector System.out.print("What is your command? "); String stCommand = keyboard.nextLine().trim().toLowerCase(); if (stCommand.isEmpty()) { System.out.println("Invalid Command."); } else { char command = stCommand.charAt(0); if (command == 'h' || command == '?') // if 'h' is pressed, show command options { System.out.println("Press 'd' to set " + customNames[4] + "."); System.out.println("Press 'g' to set " + customNames[5] + "."); System.out.println("Press 'r' to set " + customNames[6] + "."); System.out.println("Press 's' to see economic status."); System.out.println("Press 'm' to see reset " + customNames[3] + " distribution."); System.out.println("Press 'e' to end the day."); System.out.println("Press 'o' to access options."); System.out.println("Press 'q' to quit game."); System.out.println("Press Enter to continue."); keyboard.nextLine(); } else if (command == 'd' || command == 'g' || command == 'r') // if 'd', 'g', or 'r' is pressed set/add defenders, gatherers, or recruiters { String customNamesDGR = null; fullMinions = false; int other1 = 0, other2 = 0; if (command == 'd') { customNamesDGR = customNames[4]; other1 = gather; other2 = recruit; } else if (command == 'g') { customNamesDGR = customNames[5]; other1 = recruit; other2 = defend; } else if (command == 'r') { customNamesDGR = customNames[6]; other1 = defend; other2 = gather; } boolean checkAddOrSet = false; while (checkAddOrSet != true) { System.out.print("Do you want to add " + customNamesDGR + ", or set total " + customNamesDGR + "? [add/set] "); String stAddOrSet = keyboard.nextLine().trim().toLowerCase(); if (stAddOrSet.isEmpty()) { System.out.println("Invalid Command."); } else if (stAddOrSet.equals("add") || stAddOrSet.equals("set")) { boolean checkDGR = false; while (checkDGR != true) { stAddOrSet = stAddOrSet.substring(0, 1).toUpperCase() + stAddOrSet.substring(1); System.out.print(stAddOrSet + " how many " + customNamesDGR + "? "); String stTempDGR = keyboard.next().trim(); keyboard.nextLine(); int stTempDGRLength = stTempDGR.length(); boolean validDGR = true; for (int k = 0; k < stTempDGRLength; k++) { if (Character.isDigit(stTempDGR.charAt(k)) != true) { System.out.println("Invalid Command."); validDGR = false; } } if (validDGR == true) { int tempDGR = Integer.parseInt(stTempDGR), compareDGR = 0; stAddOrSet = stAddOrSet.toLowerCase(); if (stAddOrSet.equals("add")) { compareDGR = (tempDGR + defend + gather + recruit); } else if (stAddOrSet.equals("set")) { compareDGR = (tempDGR + other1 + other2); } if (compareDGR > numMinions) { System.out.println(); System.out.println("Error!"); System.out.println("You don't have enough " + customNames[3] + " to do that."); System.out.println("Press 'm' to reset " + customNames[3] + " distribution."); System.out.println("Or press 's' to see where they are distributed."); } else { boolean confirmDGR = false; while (confirmDGR != true) { System.out.print("Confirm " + stAddOrSet); if (stAddOrSet.equals("set")) { System.out.print("t"); } System.out.print("ing " + tempDGR + " " + customNamesDGR + "? [y/n] "); String stConfirmDGR = keyboard.nextLine().trim().toLowerCase(); if (stConfirmDGR.isEmpty()) { System.out.println("Invalid Command."); } else if (stConfirmDGR.charAt(0) == 'y' || stConfirmDGR.charAt(0) == 'n') { if (stConfirmDGR.charAt(0) == 'y') { if (stAddOrSet.equals("add")) { if (command == 'd') { defend = defend + tempDGR; } else if (command == 'g') { gather = gather + tempDGR; } else if (command == 'r') { recruit = recruit + tempDGR; } } else if (stAddOrSet.equals("set")) { if (command == 'd') { defend = tempDGR; } else if (command == 'g') { gather = tempDGR; } else if (command == 'r') { recruit = tempDGR; } } System.out.print(tempDGR + " " + customNamesDGR + " " + stAddOrSet); if (stAddOrSet.equals("add")) { System.out.print("ed"); } System.out.println("."); } else { } confirmDGR = true; } else { System.out.println("Invalid Command."); } } } checkDGR = true; } } checkAddOrSet = true; } else { System.out.println("Invalid Command."); } System.out.println(); } } else if (command == 's') // if 's' is pressed, see the economic status { } else if (command == 'm') // if 'm' is pressed, unassign all minion jobs { } else if (command == 'e') // if 'e' is pressed, end the day { boolean confirmEndDay = false; while (confirmEndDay != true) { System.out.print("Are you sure you want to end the day? [y/n] "); String stConfirmEndDay = keyboard.nextLine().trim().toLowerCase(); if (stConfirmEndDay.isEmpty()) { System.out.println("Invalid Command."); } else if (stConfirmEndDay.charAt(0) == 'y' || stConfirmEndDay.charAt(0) == 'n') { if (stConfirmEndDay.charAt(0) == 'y') { if (fullMinions != true) // if there are unassigned minions, double checks end day { System.out.println(); System.out.println("You still have " + (numMinions - gather - defend - recruit) + " unassigned " + customNames[3] + "."); boolean confirmEndEnd = false; while (confirmEndEnd != true) { System.out.print("Are you absolutely positive you want to end the day? [y/n] "); String stConfirmEndEnd = keyboard.nextLine().trim().toLowerCase(); if (stConfirmEndEnd.isEmpty()) { System.out.println("Invalid Command."); } else if (stConfirmEndEnd.charAt(0) == 'y' || stConfirmEndEnd.charAt(0) == 'n') { if (stConfirmEndEnd.charAt(0) == 'y') { endDay = true; } else { } confirmEndEnd = true; } else { System.out.println("Invalid Command."); } } } else { endDay = true; } } else { } confirmEndDay = true; } else { System.out.println("Invalid Command."); } } System.out.println(); } else if (command == 'o') // if 'o' is pressed, choose options { } else if (command == 'q') // if 'q' is pressed, quit the game { boolean checkQuitGame = false; while (checkQuitGame != true) { System.out.print("Are you sure you want to quit? [y/n] "); String stQuitGame = keyboard.nextLine().trim().toLowerCase(); if (stQuitGame.isEmpty()) { System.out.println("Invalid Command."); } else if (stQuitGame.charAt(0) == 'y' || stQuitGame.charAt(0) == 'n') { if (stQuitGame.charAt(0) == 'y') { boolean checkSaveGame = false; while (checkSaveGame != true) { System.out.print("Would you like to save the game? [y/n] "); String stSaveGame = keyboard.nextLine().trim().toLowerCase(); if (stSaveGame.isEmpty()) { System.out.println("Invalid Command."); } else if (stSaveGame.charAt(0) == 'y' || stSaveGame.charAt(0) == 'n') { if (stSaveGame.charAt(0) == 'y') { try { PrintWriter outSave = new PrintWriter(new FileOutputStream(fSave)); for (int k = 0; k < NUMARRAYS; k++) { int saveLimit = Integer.parseInt(saveGame[k][0]); for (int j = 0; j < saveLimit; j++) { outSave.println(saveGame[k][j]); } } outSave.close(); } catch (Exception e) { System.out.println("Saving Error. \nTerminating Program."); System.exit(0); } } boolean checkHighScore = false; while (checkHighScore != true) { System.out.print("Would you like to see your score? [y/n] "); String stSeeScore = keyboard.nextLine().trim().toLowerCase(); if (stSeeScore.isEmpty()) { System.out.println("Invalid Command."); } else if (stSeeScore.charAt(0) == 'y' || stSeeScore.charAt(0) == 'n') { if (stSeeScore.charAt(0) == 'y') { runGame = false; } else { System.out.println("Well, thanks for playing!"); System.exit(0); } checkHighScore = true; } else { System.out.println("Invalid Command."); } } checkSaveGame = true; } else { System.out.println("Invalid Command."); } } } else { System.out.println("That's the spirit! \nNow get back in there!!"); } checkQuitGame = true; } else { System.out.println("Invalid Command."); } } } else // if anything else is pressed, error code { System.out.println("Invalid Command. Press 'h' or '?' for help."); System.out.println("Press Enter to continue."); //keyboard.nextLine(); } } if (numMinions == (gather + recruit + defend)) { fullMinions = true; System.out.println("All of your " + customNames[3] + " are assigned."); boolean checkFullMinions = false; while (checkFullMinions != true) { System.out.print("Would you like to end the day? [y/n] "); String stFull = keyboard.nextLine().trim().toLowerCase(); if (stFull.isEmpty()) { System.out.println("Invalid Command."); } else if (stFull.charAt(0) == 'y' || stFull.charAt(0) == 'n') { if (stFull.charAt(0) == 'y') { endDay = true; } else { } checkFullMinions = true; } else { System.out.println("Invalid Command."); } } } } if (endDay) { oldNumMinions = numMinions; System.out.println("__________________________________________"); System.out.println(); System.out.println("Press Enter to see the day's events."); keyboard.nextLine(); int serendipity = rand.nextInt(day + defendBonus + gatherBonus + luck); if (serendipity < 1) { } System.out.println(); System.out.println("Press Enter to go on to the battle report."); keyboard.nextLine(); keyboard.nextLine(); System.out.println("__________________________________________"); } if (maxMinions < numMinions) // checks and sets maxMinions for scoring { maxMinions = numMinions; } if (maxGold < gold) // checks and sets maxGold for storing { maxGold = gold; } for (int k = 0; k < NUMARRAYS; k++) { int saveLimit = Integer.parseInt(saveGame[k][0]); for (int j = 1; j < saveLimit; j++) { if (variableNames[k][j].equals("numMinions")) { saveGame[k][j] = Integer.toString(numMinions); } else if (variableNames[k][j].equals("gold")) { saveGame[k][j] = Integer.toString(gold); } else if (variableNames[k][j].equals("defendBonus")) { saveGame[k][j] = Integer.toString(defendBonus); } else if (variableNames[k][j].equals("gatherBonus")) { saveGame[k][j] = Integer.toString(gatherBonus); } else if (variableNames[k][j].equals("luck")) { saveGame[k][j] = Integer.toString(luck); } else if (variableNames[k][j].equals("day")) { saveGame[k][j] = Integer.toString(day); } else if (variableNames[k][j].equals("maxMinions")) { saveGame[k][j] = Integer.toString(maxMinions); } else if (variableNames[k][j].equals("maxGold")) { saveGame[k][j] = Integer.toString(maxGold); } else if (variableNames[k][j].equals("numDragonKill")) { saveGame[k][j] = Integer.toString(numDragonKill); } else if (variableNames[k][j].equals("numBattlesWon")) { saveGame[k][j] = Integer.toString(numBattlesWon); } else if (variableNames[k][j].equals("itemsFound")) { saveGame[k][j] = Integer.toString(itemsFound); } else if (variableNames[k][j].equals("difficulty")) { saveGame[k][j] = Integer.toString(difficulty); } else if (variableNames[k][j].equals("name")) { saveGame[k][j] = name; } else if (variableNames[k][j].equals("fName")) { saveGame[k][j] = fName; } else if (variableNames[k][j].equals("confirm")) { saveGame[k][j] = Character.toString(confirm); } else if (variableNames[k][j].equals("deny")) { saveGame[k][j] = Character.toString(deny); } else if (variableNames[k][j].equals("debug")) { saveGame[k][j] = Boolean.toString(debug); } else if (variableNames[k][j].equals("male")) { saveGame[k][j] = Boolean.toString(male); } } } if (numMinions <= 0) // checks current number of minions for game over { runGame = false; // if user has less than or equal to zero minions, the game is over } } System.out.println(); System.out.println("That was an excellent game!"); System.out.println(); } }
mit
plutoniumRODS/Plutonium
src/rpcwallet.cpp
63058
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet.h" #include "walletdb.h" #include "bitcoinrpc.h" #include "init.h" #include "base58.h" using namespace json_spirit; using namespace std; int64 nWalletUnlockTime; static CCriticalSection cs_nWalletUnlockTime; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry); std::string HelpRequiringPassphrase() { return pwalletMain->IsCrypted() ? "\nrequires wallet passphrase to be set with walletpassphrase first" : ""; } void EnsureWalletIsUnlocked() { if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); if (fWalletUnlockMintOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Wallet unlocked for block minting only."); } void WalletTxToJSON(const CWalletTx& wtx, Object& entry) { int confirms = wtx.GetDepthInMainChain(); entry.push_back(Pair("confirmations", confirms)); if (wtx.IsCoinBase() || wtx.IsCoinStake()) entry.push_back(Pair("generated", true)); if (confirms) { entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex())); entry.push_back(Pair("blockindex", wtx.nIndex)); entry.push_back(Pair("blocktime", (boost::int64_t)(mapBlockIndex[wtx.hashBlock]->nTime))); } entry.push_back(Pair("txid", wtx.GetHash().GetHex())); entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime())); entry.push_back(Pair("timereceived", (boost::int64_t)wtx.nTimeReceived)); BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue) entry.push_back(Pair(item.first, item.second)); } string AccountFromValue(const Value& value) { string strAccount = value.get_str(); if (strAccount == "*") throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name"); return strAccount; } Value getinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getinfo\n" "Returns an object containing various state info."); proxyType proxy; GetProxy(NET_IPV4, proxy); Object obj; obj.push_back(Pair("version", FormatFullVersion())); obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION)); obj.push_back(Pair("walletversion", pwalletMain->GetVersion())); obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance()))); obj.push_back(Pair("newmint", ValueFromAmount(pwalletMain->GetNewMint()))); obj.push_back(Pair("stake", ValueFromAmount(pwalletMain->GetStake()))); obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("moneysupply", ValueFromAmount(pindexBest->nMoneySupply))); obj.push_back(Pair("connections", (int)vNodes.size())); obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string()))); obj.push_back(Pair("ip", addrSeenByPeer.ToStringIP())); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("testnet", fTestNet)); obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime())); obj.push_back(Pair("keypoolsize", pwalletMain->GetKeyPoolSize())); obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee))); if (pwalletMain->IsCrypted()) obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime / 1000)); obj.push_back(Pair("errors", GetWarnings("statusbar"))); return obj; } Value getnewpubkey(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getnewpubkey [account]\n" "Returns new public key for coinbase generation."); // Parse the account first so we don't generate a key if there's an error string strAccount; if (params.size() > 0) strAccount = AccountFromValue(params[0]); if (!pwalletMain->IsLocked()) pwalletMain->TopUpKeyPool(); // Generate a new key that is added to wallet CPubKey newKey; if (!pwalletMain->GetKeyFromPool(newKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); CKeyID keyID = newKey.GetID(); pwalletMain->SetAddressBookName(keyID, strAccount); vector<unsigned char> vchPubKey = newKey.Raw(); return HexStr(vchPubKey.begin(), vchPubKey.end()); } Value getnewaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getnewaddress [account]\n" "Returns a new Plutonium address for receiving payments. " "If [account] is specified (recommended), it is added to the address book " "so payments received with the address will be credited to [account]."); // Parse the account first so we don't generate a key if there's an error string strAccount; if (params.size() > 0) strAccount = AccountFromValue(params[0]); if (!pwalletMain->IsLocked()) pwalletMain->TopUpKeyPool(); // Generate a new key that is added to wallet CPubKey newKey; if (!pwalletMain->GetKeyFromPool(newKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); CKeyID keyID = newKey.GetID(); pwalletMain->SetAddressBookName(keyID, strAccount); return CBitcoinAddress(keyID).ToString(); } CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false) { CWalletDB walletdb(pwalletMain->strWalletFile); CAccount account; walletdb.ReadAccount(strAccount, account); bool bKeyUsed = false; // Check if the current key has been used if (account.vchPubKey.IsValid()) { CScript scriptPubKey; scriptPubKey.SetDestination(account.vchPubKey.GetID()); for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid(); ++it) { const CWalletTx& wtx = (*it).second; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) bKeyUsed = true; } } // Generate a new key if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed) { if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount); walletdb.WriteAccount(strAccount, account); } return CBitcoinAddress(account.vchPubKey.GetID()); } Value getaccountaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccountaddress <account>\n" "Returns the current Plutonium address for receiving payments to this account."); // Parse the account first so we don't generate a key if there's an error string strAccount = AccountFromValue(params[0]); Value ret; ret = GetAccountAddress(strAccount).ToString(); return ret; } Value setaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setaccount <Plutonium address> <account>\n" "Sets the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Plutonium address"); string strAccount; if (params.size() > 1) strAccount = AccountFromValue(params[1]); // Detect when changing the account of an address that is the 'unused current key' of another account: if (pwalletMain->mapAddressBook.count(address.Get())) { string strOldAccount = pwalletMain->mapAddressBook[address.Get()]; if (address == GetAccountAddress(strOldAccount)) GetAccountAddress(strOldAccount, true); } pwalletMain->SetAddressBookName(address.Get(), strAccount); return Value::null; } Value getaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccount <Plutonium address>\n" "Returns the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Plutonium address"); string strAccount; map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get()); if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty()) strAccount = (*mi).second; return strAccount; } Value getaddressesbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaddressesbyaccount <account>\n" "Returns the list of addresses for the given account."); string strAccount = AccountFromValue(params[0]); // Find all addresses that have the given account Array ret; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strName = item.second; if (strName == strAccount) ret.push_back(address.ToString()); } return ret; } Value sendtoaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendtoaddress <Plutonium address> <amount> [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.000001" + HelpRequiringPassphrase()); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Plutonium address"); // Amount int64 nAmount = AmountFromValue(params[1]); if (nAmount < MIN_TXOUT_AMOUNT) throw JSONRPCError(-101, "Send amount too small"); // Wallet comments CWalletTx wtx; if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty()) wtx.mapValue["comment"] = params[2].get_str(); if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["to"] = params[3].get_str(); if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(RPC_WALLET_ERROR, strError); return wtx.GetHash().GetHex(); } Value listaddressgroupings(const Array& params, bool fHelp) { if (fHelp) throw runtime_error( "listaddressgroupings\n" "Lists groups of addresses which have had their common ownership\n" "made public by common use as inputs or as the resulting change\n" "in past transactions"); Array jsonGroupings; map<CTxDestination, int64> balances = pwalletMain->GetAddressBalances(); BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings()) { Array jsonGrouping; BOOST_FOREACH(CTxDestination address, grouping) { Array addressInfo; addressInfo.push_back(CBitcoinAddress(address).ToString()); addressInfo.push_back(ValueFromAmount(balances[address])); { LOCK(pwalletMain->cs_wallet); if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end()) addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second); } jsonGrouping.push_back(addressInfo); } jsonGroupings.push_back(jsonGrouping); } return jsonGroupings; } Value signmessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "signmessage <Plutonium address> <message>\n" "Sign a message with the private key of an address"); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); string strMessage = params[1].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); CKey key; if (!pwalletMain->GetKey(keyID, key)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available"); CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; vector<unsigned char> vchSig; if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed"); return EncodeBase64(&vchSig[0], vchSig.size()); } Value verifymessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 3) throw runtime_error( "verifymessage <Plutonium address> <signature> <message>\n" "Verify a signed message"); string strAddress = params[0].get_str(); string strSign = params[1].get_str(); string strMessage = params[2].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); bool fInvalid = false; vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid); if (fInvalid) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding"); CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; CKey key; if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig)) return false; return (key.GetPubKey().GetID() == keyID); } Value getreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaddress <Plutonium address> [minconf=1]\n" "Returns the total amount received by <Plutonium address> in transactions with at least [minconf] confirmations."); // Bitcoin address CBitcoinAddress address = CBitcoinAddress(params[0].get_str()); CScript scriptPubKey; if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Plutonium address"); scriptPubKey.SetDestination(address.Get()); if (!IsMine(*pwalletMain,scriptPubKey)) return (double)0.0; // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Tally int64 nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal()) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } return ValueFromAmount(nAmount); } void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook) { const CTxDestination& address = item.first; const string& strName = item.second; if (strName == strAccount) setAddress.insert(address); } } Value getreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaccount <account> [minconf=1]\n" "Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations."); // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Get the set of pub keys assigned to account string strAccount = AccountFromValue(params[0]); set<CTxDestination> setAddress; GetAccountAddresses(strAccount, setAddress); // Tally int64 nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal()) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address)) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } } return (double)nAmount / (double)COIN; } int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth) { int64 nBalance = 0; // Tally wallet transactions for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!wtx.IsFinal()) continue; int64 nGeneratedImmature, nGeneratedMature, nReceived, nSent, nFee; wtx.GetAccountAmounts(strAccount, nGeneratedImmature, nGeneratedMature, nReceived, nSent, nFee); if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth) nBalance += nReceived; if((wtx.IsCoinBaseOrStake() && wtx.GetDepthInMainChain() >= nMinDepth && wtx.GetBlocksToMaturity() == 0) || !wtx.IsCoinBaseOrStake()) { nBalance += nGeneratedMature - nSent - nFee; } } // Tally internal accounting entries nBalance += walletdb.GetAccountCreditDebit(strAccount); return nBalance; } int64 GetAccountBalance(const string& strAccount, int nMinDepth) { CWalletDB walletdb(pwalletMain->strWalletFile); return GetAccountBalance(walletdb, strAccount, nMinDepth); } Value getbalance(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getbalance [account] [minconf=1]\n" "If [account] is not specified, returns the server's total available balance.\n" "If [account] is specified, returns the balance in the account."); if (params.size() == 0) return ValueFromAmount(pwalletMain->GetBalance()); int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); if (params[0].get_str() == "*") { // Calculate total balance a different way from GetBalance() // (GetBalance() sums up all unspent TxOuts) // getbalance and getbalance '*' should always return the same number. int64 nBalance = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!wtx.IsFinal()) continue; int64 allGeneratedImmature, allGeneratedMature, allFee; allGeneratedImmature = allGeneratedMature = allFee = 0; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount); if (wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived) nBalance += r.second; } if((wtx.IsCoinBaseOrStake() && wtx.GetDepthInMainChain() >= nMinDepth && wtx.GetBlocksToMaturity() == 0) || !wtx.IsCoinBaseOrStake()) { BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listSent) nBalance -= r.second; nBalance -= allFee; nBalance += allGeneratedMature; } } return ValueFromAmount(nBalance); } string strAccount = AccountFromValue(params[0]); int64 nBalance = GetAccountBalance(strAccount, nMinDepth); return ValueFromAmount(nBalance); } Value movecmd(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 5) throw runtime_error( "move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n" "Move from one account in your wallet to another."); string strFrom = AccountFromValue(params[0]); string strTo = AccountFromValue(params[1]); int64 nAmount = AmountFromValue(params[2]); if (nAmount < MIN_TXOUT_AMOUNT) throw JSONRPCError(-101, "Send amount too small"); if (params.size() > 3) // unused parameter, used to be nMinDepth, keep type-checking it though (void)params[3].get_int(); string strComment; if (params.size() > 4) strComment = params[4].get_str(); CWalletDB walletdb(pwalletMain->strWalletFile); if (!walletdb.TxnBegin()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); int64 nNow = GetAdjustedTime(); // Debit CAccountingEntry debit; debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); debit.strAccount = strFrom; debit.nCreditDebit = -nAmount; debit.nTime = nNow; debit.strOtherAccount = strTo; debit.strComment = strComment; walletdb.WriteAccountingEntry(debit); // Credit CAccountingEntry credit; credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); credit.strAccount = strTo; credit.nCreditDebit = nAmount; credit.nTime = nNow; credit.strOtherAccount = strFrom; credit.strComment = strComment; walletdb.WriteAccountingEntry(credit); if (!walletdb.TxnCommit()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); return true; } Value sendfrom(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 6) throw runtime_error( "sendfrom <fromaccount> <toPlutonium address> <amount> [minconf=1] [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.000001" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); CBitcoinAddress address(params[1].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Plutonium address"); int64 nAmount = AmountFromValue(params[2]); if (nAmount < MIN_TXOUT_AMOUNT) throw JSONRPCError(-101, "Send amount too small"); int nMinDepth = 1; if (params.size() > 3) nMinDepth = params[3].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty()) wtx.mapValue["comment"] = params[4].get_str(); if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty()) wtx.mapValue["to"] = params[5].get_str(); EnsureWalletIsUnlocked(); // Check funds int64 nBalance = GetAccountBalance(strAccount, nMinDepth); if (nAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); // Send string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(RPC_WALLET_ERROR, strError); return wtx.GetHash().GetHex(); } Value sendmany(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n" "amounts are double-precision floating point numbers" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); Object sendTo = params[1].get_obj(); int nMinDepth = 1; if (params.size() > 2) nMinDepth = params[2].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["comment"] = params[3].get_str(); set<CBitcoinAddress> setAddress; vector<pair<CScript, int64> > vecSend; int64 totalAmount = 0; BOOST_FOREACH(const Pair& s, sendTo) { CBitcoinAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Plutonium address: ")+s.name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_); setAddress.insert(address); CScript scriptPubKey; scriptPubKey.SetDestination(address.Get()); int64 nAmount = AmountFromValue(s.value_); if (nAmount < MIN_TXOUT_AMOUNT) throw JSONRPCError(-101, "Send amount too small"); totalAmount += nAmount; vecSend.push_back(make_pair(scriptPubKey, nAmount)); } EnsureWalletIsUnlocked(); // Check funds int64 nBalance = GetAccountBalance(strAccount, nMinDepth); if (totalAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); // Send CReserveKey keyChange(pwalletMain); int64 nFeeRequired = 0; bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired); if (!fCreated) { if (totalAmount + nFeeRequired > pwalletMain->GetBalance()) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds"); throw JSONRPCError(RPC_WALLET_ERROR, "Transaction creation failed"); } if (!pwalletMain->CommitTransaction(wtx, keyChange)) throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed"); return wtx.GetHash().GetHex(); } Value addmultisigaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) { string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n" "Add a nrequired-to-sign multisignature address to the wallet\"\n" "each key is a Plutonium address or hex-encoded public key\n" "If [account] is specified, assign address to [account]."; throw runtime_error(msg); } int nRequired = params[0].get_int(); const Array& keys = params[1].get_array(); string strAccount; if (params.size() > 2) strAccount = AccountFromValue(params[2]); // Gather public keys if (nRequired < 1) throw runtime_error("a multisignature address must require at least one key to redeem"); if ((int)keys.size() < nRequired) throw runtime_error( strprintf("not enough keys supplied " "(got %"PRIszu" keys, but need at least %d to redeem)", keys.size(), nRequired)); std::vector<CKey> pubkeys; pubkeys.resize(keys.size()); for (unsigned int i = 0; i < keys.size(); i++) { const std::string& ks = keys[i].get_str(); // Case 1: Bitcoin address and we have full public key: CBitcoinAddress address(ks); if (address.IsValid()) { CKeyID keyID; if (!address.GetKeyID(keyID)) throw runtime_error( strprintf("%s does not refer to a key",ks.c_str())); CPubKey vchPubKey; if (!pwalletMain->GetPubKey(keyID, vchPubKey)) throw runtime_error( strprintf("no full public key for address %s",ks.c_str())); if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey)) throw runtime_error(" Invalid public key: "+ks); } // Case 2: hex public key else if (IsHex(ks)) { CPubKey vchPubKey(ParseHex(ks)); if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey)) throw runtime_error(" Invalid public key: "+ks); } else { throw runtime_error(" Invalid public key: "+ks); } } // Construct using pay-to-script-hash: CScript inner; inner.SetMultisig(nRequired, pubkeys); CScriptID innerID = inner.GetID(); pwalletMain->AddCScript(inner); pwalletMain->SetAddressBookName(innerID, strAccount); return CBitcoinAddress(innerID).ToString(); } struct tallyitem { int64 nAmount; int nConf; tallyitem() { nAmount = 0; nConf = std::numeric_limits<int>::max(); } }; Value ListReceived(const Array& params, bool fByAccounts) { // Minimum confirmations int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); // Whether to include empty accounts bool fIncludeEmpty = false; if (params.size() > 1) fIncludeEmpty = params[1].get_bool(); // Tally map<CBitcoinAddress, tallyitem> mapTally; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal()) continue; int nDepth = wtx.GetDepthInMainChain(); if (nDepth < nMinDepth) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address)) continue; tallyitem& item = mapTally[address]; item.nAmount += txout.nValue; item.nConf = min(item.nConf, nDepth); } } // Reply Array ret; map<string, tallyitem> mapAccountTally; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strAccount = item.second; map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address); if (it == mapTally.end() && !fIncludeEmpty) continue; int64 nAmount = 0; int nConf = std::numeric_limits<int>::max(); if (it != mapTally.end()) { nAmount = (*it).second.nAmount; nConf = (*it).second.nConf; } if (fByAccounts) { tallyitem& item = mapAccountTally[strAccount]; item.nAmount += nAmount; item.nConf = min(item.nConf, nConf); } else { Object obj; obj.push_back(Pair("address", address.ToString())); obj.push_back(Pair("account", strAccount)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); ret.push_back(obj); } } if (fByAccounts) { for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it) { int64 nAmount = (*it).second.nAmount; int nConf = (*it).second.nConf; Object obj; obj.push_back(Pair("account", (*it).first)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); ret.push_back(obj); } } return ret; } Value listreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaddress [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include addresses that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"address\" : receiving address\n" " \"account\" : the account of the receiving address\n" " \"amount\" : total amount received by the address\n" " \"confirmations\" : number of confirmations of the most recent transaction included"); return ListReceived(params, false); } Value listreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaccount [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include accounts that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"account\" : the account of the receiving addresses\n" " \"amount\" : total amount received by addresses with this account\n" " \"confirmations\" : number of confirmations of the most recent transaction included"); return ListReceived(params, true); } void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret) { int64 nGeneratedImmature, nGeneratedMature, nFee; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount); bool fAllAccounts = (strAccount == string("*")); // Generated blocks assigned to account "" if ((nGeneratedMature+nGeneratedImmature) != 0 && (fAllAccounts || strAccount == "")) { Object entry; entry.push_back(Pair("account", string(""))); if (nGeneratedImmature) { entry.push_back(Pair("category", wtx.GetDepthInMainChain() ? "immature" : "orphan")); entry.push_back(Pair("amount", ValueFromAmount(nGeneratedImmature))); } else { entry.push_back(Pair("category", "generate")); entry.push_back(Pair("amount", ValueFromAmount(nGeneratedMature))); } if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } // Sent if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount)) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent) { Object entry; entry.push_back(Pair("account", strSentAccount)); entry.push_back(Pair("address", CBitcoinAddress(s.first).ToString())); entry.push_back(Pair("category", "send")); entry.push_back(Pair("amount", ValueFromAmount(-s.second))); entry.push_back(Pair("fee", ValueFromAmount(-nFee))); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } // Received if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived) { string account; if (pwalletMain->mapAddressBook.count(r.first)) account = pwalletMain->mapAddressBook[r.first]; if (fAllAccounts || (account == strAccount)) { Object entry; entry.push_back(Pair("account", account)); entry.push_back(Pair("address", CBitcoinAddress(r.first).ToString())); if (wtx.IsCoinBase()) { if (wtx.GetDepthInMainChain() < 1) entry.push_back(Pair("category", "orphan")); else if (wtx.GetBlocksToMaturity() > 0) entry.push_back(Pair("category", "immature")); else entry.push_back(Pair("category", "generate")); } else entry.push_back(Pair("category", "receive")); entry.push_back(Pair("amount", ValueFromAmount(r.second))); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } } } void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret) { bool fAllAccounts = (strAccount == string("*")); if (fAllAccounts || acentry.strAccount == strAccount) { Object entry; entry.push_back(Pair("account", acentry.strAccount)); entry.push_back(Pair("category", "move")); entry.push_back(Pair("time", (boost::int64_t)acentry.nTime)); entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit))); entry.push_back(Pair("otheraccount", acentry.strOtherAccount)); entry.push_back(Pair("comment", acentry.strComment)); ret.push_back(entry); } } Value listtransactions(const Array& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "listtransactions [account] [count=10] [from=0]\n" "Returns up to [count] most recent transactions skipping the first [from] transactions for account [account]."); string strAccount = "*"; if (params.size() > 0) strAccount = params[0].get_str(); int nCount = 10; if (params.size() > 1) nCount = params[1].get_int(); int nFrom = 0; if (params.size() > 2) nFrom = params[2].get_int(); if (nCount < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count"); if (nFrom < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from"); Array ret; std::list<CAccountingEntry> acentries; CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount); // iterate backwards until we have nCount items to return: for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) { CWalletTx *const pwtx = (*it).second.first; if (pwtx != 0) ListTransactions(*pwtx, strAccount, 0, true, ret); CAccountingEntry *const pacentry = (*it).second.second; if (pacentry != 0) AcentryToJSON(*pacentry, strAccount, ret); if ((int)ret.size() >= (nCount+nFrom)) break; } // ret is newest to oldest if (nFrom > (int)ret.size()) nFrom = ret.size(); if ((nFrom + nCount) > (int)ret.size()) nCount = ret.size() - nFrom; Array::iterator first = ret.begin(); std::advance(first, nFrom); Array::iterator last = ret.begin(); std::advance(last, nFrom+nCount); if (last != ret.end()) ret.erase(last, ret.end()); if (first != ret.begin()) ret.erase(ret.begin(), first); std::reverse(ret.begin(), ret.end()); // Return oldest to newest return ret; } Value listaccounts(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "listaccounts [minconf=1]\n" "Returns Object that has account names as keys, account balances as values."); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); map<string, int64> mapAccountBalances; BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) { if (IsMine(*pwalletMain, entry.first)) // This address belongs to me mapAccountBalances[entry.second] = 0; } for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if(!wtx.IsFinal()) continue; int64 nGeneratedImmature, nGeneratedMature, nFee; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount); if (wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived) if (pwalletMain->mapAddressBook.count(r.first)) mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second; else mapAccountBalances[""] += r.second; } if((wtx.IsCoinBaseOrStake() && wtx.GetDepthInMainChain() >= nMinDepth && wtx.GetBlocksToMaturity() == 0) || !wtx.IsCoinBaseOrStake()) { mapAccountBalances[strSentAccount] -= nFee; mapAccountBalances[""] += nGeneratedMature; BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent) mapAccountBalances[strSentAccount] -= s.second; } } list<CAccountingEntry> acentries; CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries); BOOST_FOREACH(const CAccountingEntry& entry, acentries) mapAccountBalances[entry.strAccount] += entry.nCreditDebit; Object ret; BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) { ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second))); } return ret; } Value listsinceblock(const Array& params, bool fHelp) { if (fHelp) throw runtime_error( "listsinceblock [blockhash] [target-confirmations]\n" "Get all transactions in blocks since block [blockhash], or all transactions if omitted"); CBlockIndex *pindex = NULL; int target_confirms = 1; if (params.size() > 0) { uint256 blockId = 0; blockId.SetHex(params[0].get_str()); pindex = CBlockLocator(blockId).GetBlockIndex(); } if (params.size() > 1) { target_confirms = params[1].get_int(); if (target_confirms < 1) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); } int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1; Array transactions; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++) { CWalletTx tx = (*it).second; if (depth == -1 || tx.GetDepthInMainChain() < depth) ListTransactions(tx, "*", 0, true, transactions); } uint256 lastblock; if (target_confirms == 1) { lastblock = hashBestChain; } else { int target_height = pindexBest->nHeight + 1 - target_confirms; CBlockIndex *block; for (block = pindexBest; block && block->nHeight > target_height; block = block->pprev) { } lastblock = block ? block->GetBlockHash() : 0; } Object ret; ret.push_back(Pair("transactions", transactions)); ret.push_back(Pair("lastblock", lastblock.GetHex())); return ret; } Value gettransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "gettransaction <txid>\n" "Get detailed information about <txid>"); uint256 hash; hash.SetHex(params[0].get_str()); Object entry; if (pwalletMain->mapWallet.count(hash)) { const CWalletTx& wtx = pwalletMain->mapWallet[hash]; TxToJSON(wtx, 0, entry); int64 nCredit = wtx.GetCredit(); int64 nDebit = wtx.GetDebit(); int64 nNet = nCredit - nDebit; int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0); entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee))); if (wtx.IsFromMe()) entry.push_back(Pair("fee", ValueFromAmount(nFee))); WalletTxToJSON(wtx, entry); Array details; ListTransactions(pwalletMain->mapWallet[hash], "*", 0, false, details); entry.push_back(Pair("details", details)); } else { CTransaction tx; uint256 hashBlock = 0; if (GetTransaction(hash, tx, hashBlock)) { entry.push_back(Pair("txid", hash.GetHex())); TxToJSON(tx, 0, entry); if (hashBlock == 0) entry.push_back(Pair("confirmations", 0)); else { entry.push_back(Pair("blockhash", hashBlock.GetHex())); map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) { entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight)); entry.push_back(Pair("txntime", (boost::int64_t)tx.nTime)); entry.push_back(Pair("time", (boost::int64_t)pindex->nTime)); } else entry.push_back(Pair("confirmations", 0)); } } } else throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction"); } return entry; } Value backupwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "backupwallet <destination>\n" "Safely copies wallet.dat to destination, which can be a directory or a path with filename."); string strDest = params[0].get_str(); if (!BackupWallet(*pwalletMain, strDest)) throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!"); return Value::null; } Value keypoolrefill(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "keypoolrefill\n" "Fills the keypool." + HelpRequiringPassphrase()); EnsureWalletIsUnlocked(); pwalletMain->TopUpKeyPool(); if (pwalletMain->GetKeyPoolSize() < GetArg("-keypool", 100)) throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool."); return Value::null; } void ThreadTopUpKeyPool(void* parg) { // Make this thread recognisable as the key-topping-up thread RenameThread("bitcoin-key-top"); pwalletMain->TopUpKeyPool(); } void ThreadCleanWalletPassphrase(void* parg) { // Make this thread recognisable as the wallet relocking thread RenameThread("bitcoin-lock-wa"); int64 nMyWakeTime = GetTimeMillis() + *((int64*)parg) * 1000; ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime); if (nWalletUnlockTime == 0) { nWalletUnlockTime = nMyWakeTime; do { if (nWalletUnlockTime==0) break; int64 nToSleep = nWalletUnlockTime - GetTimeMillis(); if (nToSleep <= 0) break; LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime); Sleep(nToSleep); ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime); } while(1); if (nWalletUnlockTime) { nWalletUnlockTime = 0; pwalletMain->Lock(); } } else { if (nWalletUnlockTime < nMyWakeTime) nWalletUnlockTime = nMyWakeTime; } LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime); delete (int64*)parg; } Value walletpassphrase(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 3)) throw runtime_error( "walletpassphrase <passphrase> <timeout> [mintonly]\n" "Stores the wallet decryption key in memory for <timeout> seconds.\n" "mintonly is optional true/false allowing only block minting."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called."); if (!pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked, use walletlock first if need to change unlock settings."); // Note that the walletpassphrase is stored in params[0] which is not mlock()ed SecureString strWalletPass; strWalletPass.reserve(100); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() > 0) { if (!pwalletMain->Unlock(strWalletPass)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); } else throw runtime_error( "walletpassphrase <passphrase> <timeout>\n" "Stores the wallet decryption key in memory for <timeout> seconds."); NewThread(ThreadTopUpKeyPool, NULL); int64* pnSleepTime = new int64(params[1].get_int64()); NewThread(ThreadCleanWalletPassphrase, pnSleepTime); // Plutonium: if user OS account compromised prevent trivial sendmoney commands if (params.size() > 2) fWalletUnlockMintOnly = params[2].get_bool(); else fWalletUnlockMintOnly = false; return Value::null; } Value walletpassphrasechange(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2)) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called."); // TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strOldWalletPass; strOldWalletPass.reserve(100); strOldWalletPass = params[0].get_str().c_str(); SecureString strNewWalletPass; strNewWalletPass.reserve(100); strNewWalletPass = params[1].get_str().c_str(); if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); return Value::null; } Value walletlock(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0)) throw runtime_error( "walletlock\n" "Removes the wallet encryption key from memory, locking the wallet.\n" "After calling this method, you will need to call walletpassphrase again\n" "before being able to call any methods which require the wallet to be unlocked."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called."); { LOCK(cs_nWalletUnlockTime); pwalletMain->Lock(); nWalletUnlockTime = 0; } return Value::null; } Value encryptwallet(const Array& params, bool fHelp) { if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1)) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (fHelp) return true; if (pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called."); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strWalletPass; strWalletPass.reserve(100); strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() < 1) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (!pwalletMain->EncryptWallet(strWalletPass)) throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet."); // BDB seems to have a bad habit of writing old data into // slack space in .dat files; that is bad if the old data is // unencrypted private keys. So: StartShutdown(); return "wallet encrypted; Plutonium server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup."; } class DescribeAddressVisitor : public boost::static_visitor<Object> { public: Object operator()(const CNoDestination &dest) const { return Object(); } Object operator()(const CKeyID &keyID) const { Object obj; CPubKey vchPubKey; pwalletMain->GetPubKey(keyID, vchPubKey); obj.push_back(Pair("isscript", false)); obj.push_back(Pair("pubkey", HexStr(vchPubKey.Raw()))); obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed())); return obj; } Object operator()(const CScriptID &scriptID) const { Object obj; obj.push_back(Pair("isscript", true)); CScript subscript; pwalletMain->GetCScript(scriptID, subscript); std::vector<CTxDestination> addresses; txnouttype whichType; int nRequired; ExtractDestinations(subscript, whichType, addresses, nRequired); obj.push_back(Pair("script", GetTxnOutputType(whichType))); Array a; BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); obj.push_back(Pair("addresses", a)); if (whichType == TX_MULTISIG) obj.push_back(Pair("sigsrequired", nRequired)); return obj; } }; Value validateaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "validateaddress <Plutonium address>\n" "Return information about <Plutonium address>."); CBitcoinAddress address(params[0].get_str()); bool isValid = address.IsValid(); Object ret; ret.push_back(Pair("isvalid", isValid)); if (isValid) { CTxDestination dest = address.Get(); string currentAddress = address.ToString(); ret.push_back(Pair("address", currentAddress)); bool fMine = IsMine(*pwalletMain, dest); ret.push_back(Pair("ismine", fMine)); if (fMine) { Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest); ret.insert(ret.end(), detail.begin(), detail.end()); } if (pwalletMain->mapAddressBook.count(dest)) ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest])); } return ret; } Value validatepubkey(const Array& params, bool fHelp) { if (fHelp || !params.size() || params.size() > 2) throw runtime_error( "validatepubkey <Plutoniumpubkey>\n" "Return information about <Plutoniumpubkey>."); std::vector<unsigned char> vchPubKey = ParseHex(params[0].get_str()); CPubKey pubKey(vchPubKey); bool isValid = pubKey.IsValid(); bool isCompressed = pubKey.IsCompressed(); CKeyID keyID = pubKey.GetID(); CBitcoinAddress address; address.Set(keyID); Object ret; ret.push_back(Pair("isvalid", isValid)); if (isValid) { CTxDestination dest = address.Get(); string currentAddress = address.ToString(); ret.push_back(Pair("address", currentAddress)); bool fMine = IsMine(*pwalletMain, dest); ret.push_back(Pair("ismine", fMine)); ret.push_back(Pair("iscompressed", isCompressed)); if (fMine) { Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest); ret.insert(ret.end(), detail.begin(), detail.end()); } if (pwalletMain->mapAddressBook.count(dest)) ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest])); } return ret; } // Plutonium: reserve balance from being staked for network protection Value reservebalance(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "reservebalance [<reserve> [amount]]\n" "<reserve> is true or false to turn balance reserve on or off.\n" "<amount> is a real and rounded to cent.\n" "Set reserve amount not participating in network protection.\n" "If no parameters provided current setting is printed.\n"); if (params.size() > 0) { bool fReserve = params[0].get_bool(); if (fReserve) { if (params.size() == 1) throw runtime_error("must provide amount to reserve balance.\n"); int64 nAmount = AmountFromValue(params[1]); nAmount = (nAmount / CENT) * CENT; // round to cent if (nAmount < 0) throw runtime_error("amount cannot be negative.\n"); mapArgs["-reservebalance"] = FormatMoney(nAmount).c_str(); } else { if (params.size() > 1) throw runtime_error("cannot specify amount to turn off reserve.\n"); mapArgs["-reservebalance"] = "0"; } } Object result; int64 nReserveBalance = 0; if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance)) throw runtime_error("invalid reserve balance amount\n"); result.push_back(Pair("reserve", (nReserveBalance > 0))); result.push_back(Pair("amount", ValueFromAmount(nReserveBalance))); return result; } // Plutonium: check wallet integrity Value checkwallet(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "checkwallet\n" "Check wallet for integrity.\n"); int nMismatchSpent; int64 nBalanceInQuestion; pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion, true); Object result; if (nMismatchSpent == 0) result.push_back(Pair("wallet check passed", true)); else { result.push_back(Pair("mismatched spent coins", nMismatchSpent)); result.push_back(Pair("amount in question", ValueFromAmount(nBalanceInQuestion))); } return result; } // Plutonium: repair wallet Value repairwallet(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "repairwallet\n" "Repair wallet if checkwallet reports any problem.\n"); int nMismatchSpent; int64 nBalanceInQuestion; pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion); Object result; if (nMismatchSpent == 0) result.push_back(Pair("wallet check passed", true)); else { result.push_back(Pair("mismatched spent coins", nMismatchSpent)); result.push_back(Pair("amount affected by repair", ValueFromAmount(nBalanceInQuestion))); } return result; } // Plutonium: resend unconfirmed wallet transactions Value resendtx(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "resendtx\n" "Re-send unconfirmed transactions.\n" ); ResendWalletTransactions(); return Value::null; } // Plutonium: make a public-private key pair Value makekeypair(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "makekeypair [prefix]\n" "Make a public/private key pair.\n" "[prefix] is optional preferred prefix for the public key.\n"); string strPrefix = ""; if (params.size() > 0) strPrefix = params[0].get_str(); CKey key; key.MakeNewKey(false); CPrivKey vchPrivKey = key.GetPrivKey(); Object result; result.push_back(Pair("PrivateKey", HexStr<CPrivKey::iterator>(vchPrivKey.begin(), vchPrivKey.end()))); result.push_back(Pair("PublicKey", HexStr(key.GetPubKey().Raw()))); return result; }
mit
latteware/marble-seed
api/middlewares/errorHandler.js
284
module.exports = async function (ctx, next) { ctx.type = 'application/json' try { await next() } catch (err) { ctx.body = { message: err.message } ctx.status = err.status || 500 if (ctx.status === 500) { console.error('=>', err.message, err) } } }
mit
teki-io/teki
server/config/routes.rb
940
Rails.application.routes.draw do devise_for :users, controllers: { sessions: 'users/sessions', registrations: 'users/registrations' } # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html # Serve websocket cable requests in-process # mount ActionCable.server => '/cable' mount Wupee::Engine, at: "/wupee" mount ActionCable.server => '/cable' namespace :api do resources :employees, only: [:index] resources :shifts, only: [:index] resources :profile, only: [:index] resources :notifications, only: [:index, :update, :update_all] scope '/admin', as: 'admin', module: 'admin' do resources :employees, only: [:index, :create, :update, :destroy] resources :shift_templates, only: [:index, :create, :update, :destroy] resources :shifts, only: [:index, :create, :update] resource :companies, only: [:update] end end end
mit
MrRobb/CodeFights
The Core/2. Corner of 0s and 1s/second-rightmostZeroBit.cpp
147
int secondRightmostZeroBit(int n) { return ~(n | (n+1)) & ((n | (n+1))+1); } /* 00100101 +1 00100110 | 00100111 ~ 11011000 +1 ~ 00101000 & */
mit
steinkel/cakefest-basic-workshop-2013
Config/email.php
2531
<?php /** * This is email configuration file. * * Use it to configure email transports of Cake. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package app.Config * @since CakePHP(tm) v 2.0.0 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ /** * Email configuration class. * You can specify multiple configurations for production, development and testing. * * transport => The name of a supported transport; valid options are as follows: * Mail - Send using PHP mail function * Smtp - Send using SMTP * Debug - Do not send the email, just return the result * * You can add custom transports (or override existing transports) by adding the * appropriate file to app/Network/Email. Transports should be named 'YourTransport.php', * where 'Your' is the name of the transport. * * from => * The origin email. See CakeEmail::from() about the valid values * */ class EmailConfig { public $default = array( 'transport' => 'Debug', 'log' => true, 'from' => '[email protected]', //'charset' => 'utf-8', //'headerCharset' => 'utf-8', ); public $smtp = array( 'transport' => 'Smtp', 'from' => array('site@localhost' => 'My Site'), 'host' => 'localhost', 'port' => 25, 'timeout' => 30, 'username' => 'user', 'password' => 'secret', 'client' => null, 'log' => false, //'charset' => 'utf-8', //'headerCharset' => 'utf-8', ); public $fast = array( 'from' => 'you@localhost', 'sender' => null, 'to' => null, 'cc' => null, 'bcc' => null, 'replyTo' => null, 'readReceipt' => null, 'returnPath' => null, 'messageId' => true, 'subject' => null, 'message' => null, 'headers' => null, 'viewRender' => null, 'template' => false, 'layout' => false, 'viewVars' => null, 'attachments' => null, 'emailFormat' => null, 'transport' => 'Smtp', 'host' => 'localhost', 'port' => 25, 'timeout' => 30, 'username' => 'user', 'password' => 'secret', 'client' => null, 'log' => true, //'charset' => 'utf-8', //'headerCharset' => 'utf-8', ); }
mit
lauracurley/2016-08-ps-react
node_modules/eslint/lib/rules/no-trailing-spaces.js
4823
/** * @fileoverview Disallow trailing spaces at the end of lines. * @author Nodeca Team <https://github.com/nodeca> */ "use strict"; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { docs: { description: "disallow trailing whitespace at the end of lines", category: "Stylistic Issues", recommended: false }, fixable: "whitespace", schema: [ { type: "object", properties: { skipBlankLines: { type: "boolean" } }, additionalProperties: false } ] }, create: function(context) { let sourceCode = context.getSourceCode(); let BLANK_CLASS = "[ \t\u00a0\u2000-\u200b\u2028\u2029\u3000]", SKIP_BLANK = "^" + BLANK_CLASS + "*$", NONBLANK = BLANK_CLASS + "+$"; let options = context.options[0] || {}, skipBlankLines = options.skipBlankLines || false; /** * Report the error message * @param {ASTNode} node node to report * @param {int[]} location range information * @param {int[]} fixRange Range based on the whole program * @returns {void} */ function report(node, location, fixRange) { /* * Passing node is a bit dirty, because message data will contain big * text in `source`. But... who cares :) ? * One more kludge will not make worse the bloody wizardry of this * plugin. */ context.report({ node: node, loc: location, message: "Trailing spaces not allowed.", fix: function(fixer) { return fixer.removeRange(fixRange); } }); } //-------------------------------------------------------------------------- // Public //-------------------------------------------------------------------------- return { Program: function checkTrailingSpaces(node) { // Let's hack. Since Espree does not return whitespace nodes, // fetch the source code and do matching via regexps. let re = new RegExp(NONBLANK), skipMatch = new RegExp(SKIP_BLANK), matches, lines = sourceCode.lines, linebreaks = sourceCode.getText().match(/\r\n|\r|\n|\u2028|\u2029/g), location, totalLength = 0, rangeStart, rangeEnd, fixRange = [], containingNode; for (let i = 0, ii = lines.length; i < ii; i++) { matches = re.exec(lines[i]); // Always add linebreak length to line length to accommodate for line break (\n or \r\n) // Because during the fix time they also reserve one spot in the array. // Usually linebreak length is 2 for \r\n (CRLF) and 1 for \n (LF) let linebreakLength = linebreaks && linebreaks[i] ? linebreaks[i].length : 1; let lineLength = lines[i].length + linebreakLength; if (matches) { location = { line: i + 1, column: matches.index }; rangeStart = totalLength + location.column; rangeEnd = totalLength + lineLength - linebreakLength; containingNode = sourceCode.getNodeByRangeIndex(rangeStart); if (containingNode && containingNode.type === "TemplateElement" && rangeStart > containingNode.parent.range[0] && rangeEnd < containingNode.parent.range[1]) { totalLength += lineLength; continue; } // If the line has only whitespace, and skipBlankLines // is true, don't report it if (skipBlankLines && skipMatch.test(lines[i])) { continue; } fixRange = [rangeStart, rangeEnd]; report(node, location, fixRange); } totalLength += lineLength; } } }; } };
mit
thatswhatyouget/tpp-progress
display/elements/run-status/game-stats.tsx
2165
/// <reference path="../pokebox.tsx" /> /// <reference path="../../shared.ts" /> namespace TPP.Display.Elements.RunStatus { interface GameStatsDisplayProps { gameStats: { [key: string]: number }; title: string; } export class GameStats extends React.Component<GameStatsDisplayProps, {}> { render() { var statsList = Object.keys(this.props.gameStats || {}); if (!statsList.length) return null; return <PokeBox title={`${this.props.title}`} className="itemsList gameStats"> <ul> {statsList.map(k => <GameStat key={k} name={k} value={this.props.gameStats[k]} />)} </ul> </PokeBox>; } } const secondsDetectExp = /(Seconds Spent)/i; const timeDetectExp = /\bTime\b/i; const percentDetectExp = /Percentage/i; const moneyDetectExp = /Money/i; class GameStat extends React.PureComponent<{ name: string, value: number }, {}> { render() { let name = this.props.name; let value = this.props.value.toLocaleString(); if (timeDetectExp.test(name)) value = new Duration(0) .AddHours(this.props.value >> 16) .AddMinutes((this.props.value >> 8) & 0xFF) .AddSeconds(this.props.value & 0xFF) .MultiplyBy(65835/65536) // fix GB/GBA clock drift .toString(); else if (secondsDetectExp.test(name)) { const dur = new Duration(0); dur.TotalSeconds = this.props.value; value = dur.toString(dur.TotalDays >= 1 ? TPP.Scale.Days : dur.TotalHours >= 1 ? TPP.Scale.Hours : TPP.Scale.Minutes); name = name.replace(secondsDetectExp, "Time Spent"); } // else if (percentDetectExp.test(name)) // value = value + "%"; // % doesn't exist in Pokered font else if (moneyDetectExp.test(name)) value = "$" + value; return <li data-quantity={value}>{pokeRedCondenseText(name)}:</li>; } } }
mit
spkm/isamsapi
src/Commands/EstateManagerBuildingCommand.php
1309
<?php namespace spkm\IsamsApi\Commands; use Illuminate\Console\Command; use spkm\IsamsApi\Models\School; use spkm\IsamsApi\Models\Building; use spkm\IsamsApi\Isams\EstatesManager\Buildings; class EstateManagerBuildingCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'isams:buildings {schoolId}'; /** * The console command description. * * @var string */ protected $description = 'Refresh Estates Manager Buildings'; /** * The school the command is being run for * @var \spkm\IsamsApi\Models\School */ protected $school; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $this->school = School::findOrFail($this->argument('schoolId')); $api = (new Buildings($this->school)); $api->execute(); $recordCount = Building::where('school_id','=',$this->argument('schoolId'))->count(); $this->info('There are now ' . $recordCount . ' buildings associated with ' . $this->school->name); } }
mit
battlesuit/str-inflections
lib/str/inflections.php
3583
<?php namespace str; if(defined('loader\available')) require __DIR__."/autoload.php"; require __DIR__."/functions.php"; /** * Inflections for pluralize() and singularize() functions * * PHP Version 5.3+ * @author Thomas Monzel <[email protected]> * @version $Revision$ * @package Battlesuit * @subpackage str */ class Inflections { /** * Full words for singular and plural inflections * * @access private * @var array */ private $words = array(); /** * Replacement rules * * @access private * @var array */ private $rules = array(); /** * Finalized rules by rules_for() * This array serves as a cache for singular and plural inflections * * @access private * @var array */ private $finalized_rules = array(); /** * Creates a new word inflection. Leaving out the plural form means that * singular and plural is the same. * * @access public * @param string $singular * @param string $plural Optional */ function word($singular, $plural = null) { if(empty($plural)) $plural = $singular; $this->words['singular'][$plural] = $singular; $this->words['plural'][$singular] = $plural; } /** * Creates many new word inflections by every given argument. * Uses the word() method within a foreach loop * * Example * $inflections->many_words('equipment', 'sheep', array('basis', 'bases'), 'status'); * * @access public */ function many_words() { foreach(func_get_args() as $arg) call_user_func_array(array($this, 'word'), (array)$arg); } /** * Returns the finalized rules array and regex for the given inflection form (singular or plural) * * @access public * @param string $form 'singular' or 'plural' * @return array [Regex, Rules] */ function rules_for($form) { if(isset($this->finalized_rules[$form])) return $this->finalized_rules[$form]; if(isset($this->rules[$form])) { $rules = $this->rules[$form]; $matchable_segments = array_keys($rules); } $regex = "/(".join('|', $matchable_segments).")$/i"; return $this->finalized_rules[$form] = array($regex, $rules); } /** * Adds a new rule for singular and plural inflections * * @access public * @param string $singular * @param string $plural */ function rule($singular, $plural) { $this->singular($singular, $plural); $this->plural($plural, $singular); } /** * Adds a new plural inflection rule * * @access public * @param string $singular * @param string $plural */ function plural($plural, $singular) { $this->rules['plural'][$singular] = $plural; } /** * Adds a new singular inflection rule * * @access public * @param string $singular * @param string $plural */ function singular($singular, $plural) { $this->rules['singular'][$plural] = $singular; } /** * Inflects a word into a given inflection form (singular or plural) * * @access public * @param string $form * @param string $word * @return string Inflected word */ function inflect_to($form, $word) { if(empty($word)) return ''; if(isset($this->words[$form][$word])) { return $this->words[$form][$word]; } list($expr, $rules) = $this->rules_for($form); $inflected_word = $word; $inflected_word = preg_replace_callback($expr, function($m) use($rules) { return $rules[$m[1]]; }, $inflected_word, 1); return $this->words[$form][$word] = $inflected_word; } } ?>
mit
wmira/react-icons-kit
src/md/ic_save.js
327
export const ic_save = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z"},"children":[]}]};
mit
xavividal/kanboard
app/Helper/SubtaskHelper.php
3613
<?php namespace Kanboard\Helper; use Kanboard\Core\Base; /** * Subtask helpers * * @package helper * @author Frederic Guillot */ class SubtaskHelper extends Base { public function getTitle(array $subtask) { if ($subtask['status'] == 0) { $html = '<i class="fa fa-square-o fa-fw"></i>'; } elseif ($subtask['status'] == 1) { $html = '<i class="fa fa-gears fa-fw"></i>'; } else { $html = '<i class="fa fa-check-square-o fa-fw"></i>'; } return $html.$this->helper->text->e($subtask['title']); } /** * Get the link to toggle subtask status * * @access public * @param array $subtask * @param integer $project_id * @param boolean $refresh_table * @return string */ public function toggleStatus(array $subtask, $project_id, $refresh_table = false) { if (! $this->helper->user->hasProjectAccess('SubtaskController', 'edit', $project_id)) { return $this->getTitle($subtask); } $params = array('task_id' => $subtask['task_id'], 'subtask_id' => $subtask['id'], 'refresh-table' => (int) $refresh_table); if ($subtask['status'] == 0 && isset($this->sessionStorage->hasSubtaskInProgress) && $this->sessionStorage->hasSubtaskInProgress) { return $this->helper->url->link($this->getTitle($subtask), 'SubtaskRestrictionController', 'show', $params, false, 'popover'); } $class = 'subtask-toggle-status '.($refresh_table ? 'subtask-refresh-table' : ''); return $this->helper->url->link($this->getTitle($subtask), 'SubtaskStatusController', 'change', $params, false, $class); } public function renderTitleField(array $values, array $errors = array(), array $attributes = array()) { $attributes = array_merge(array('tabindex="1"', 'required', 'maxlength="255"'), $attributes); $html = $this->helper->form->label(t('Title'), 'title'); $html .= $this->helper->form->text('title', $values, $errors, $attributes); return $html; } public function renderAssigneeField(array $users, array $values, array $errors = array(), array $attributes = array()) { $attributes = array_merge(array('tabindex="2"'), $attributes); $html = $this->helper->form->label(t('Assignee'), 'user_id'); $html .= $this->helper->form->select('user_id', $users, $values, $errors, $attributes); $html .= '&nbsp;'; $html .= '<small>'; $html .= '<a href="#" class="assign-me" data-target-id="form-user_id" data-current-id="'.$this->userSession->getId().'" title="'.t('Assign to me').'">'.t('Me').'</a>'; $html .= '</small>'; return $html; } public function renderTimeEstimatedField(array $values, array $errors = array(), array $attributes = array()) { $attributes = array_merge(array('tabindex="3"'), $attributes); $html = $this->helper->form->label(t('Original estimate'), 'time_estimated'); $html .= $this->helper->form->numeric('time_estimated', $values, $errors, $attributes); $html .= ' '.t('hours'); return $html; } public function renderTimeSpentField(array $values, array $errors = array(), array $attributes = array()) { $attributes = array_merge(array('tabindex="4"'), $attributes); $html = $this->helper->form->label(t('Time spent'), 'time_spent'); $html .= $this->helper->form->numeric('time_spent', $values, $errors, $attributes); $html .= ' '.t('hours'); return $html; } }
mit
alkcxy/flickrize
test/dummy/test/unit/with_gallery_test.rb
125
require 'test_helper' class WithGalleryTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
mit
yusukemurayama/ppytrading
manager.py
2313
#!/usr/bin/env python # coding: utf-8 import os import sys import argparse import importlib from ppyt.const import BASE_DIR # locale.setlocale(locale.LC_ALL, 'en_US') SCRIPT_DIR = os.path.join(BASE_DIR, 'commands') def main(): # パスを追加します。 sys.path.append(BASE_DIR) # 実行するコマンドを決定します。 if len(sys.argv) <= 1: show_command_list() # コマンド一覧を表示して終了します。 # 実行するコマンド名と、そのコマンド名を除外した引数のリストを取得します。 command, newargs = None, [] parser = argparse.ArgumentParser() parser.add_argument('command', type=str, nargs=1) # 最初のコマンドライン引数をコマンド名とします。 for args in parser.parse_known_args(): # parse_known_argsで余分な引数を無視します。 if hasattr(args, 'command'): # nargs=1を指定しているので、サイズ1のlistにコマンド名が入っています。 command = args.command[0] continue newargs.extend(args) # コマンド名以外を引数のリストに追加していきます。 # 実行するスクリプトを決定します。 if command is None or command + '.py' not in os.listdir(SCRIPT_DIR): show_command_list() # コマンド一覧を表示して終了します。 script_path = 'ppyt.commands.' + command # 実行するクラスのインスタンスを生成してキックします。 module = importlib.import_module(script_path) try: instance = getattr(module, 'Command')(manager=os.path.basename(__file__), command=command, args=newargs) except Exception as e: print(e) print('コマンドを実行できませんでした。' '{}がCommandBaseを継承しているかを確認してください。'.format(module.__name__)) exit() instance.start() def show_command_list(): print('# コマンド一覧') for filename in os.listdir(SCRIPT_DIR): command, ext = os.path.splitext(filename) if ext != '.py' or command.startswith('_'): continue print('* ' + command) exit() if __name__ == '__main__': main()
mit
cliffano/swaggy-jenkins
clients/scala-finch/generated/src/main/scala/org/openapitools/models/PipelineBranchesitemlatestRun.scala
1450
package org.openapitools.models import io.circe._ import io.finch.circe._ import io.circe.generic.semiauto._ import io.circe.java8.time._ import org.openapitools._ /** * * @param durationInMillis * @param estimatedDurationInMillis * @param enQueueTime * @param endTime * @param id * @param organization * @param pipeline * @param result * @param runSummary * @param startTime * @param state * @param _type * @param commitId * @param Underscoreclass */ case class PipelineBranchesitemlatestRun(durationInMillis: Option[Int], estimatedDurationInMillis: Option[Int], enQueueTime: Option[String], endTime: Option[String], id: Option[String], organization: Option[String], pipeline: Option[String], result: Option[String], runSummary: Option[String], startTime: Option[String], state: Option[String], _type: Option[String], commitId: Option[String], Underscoreclass: Option[String] ) object PipelineBranchesitemlatestRun { /** * Creates the codec for converting PipelineBranchesitemlatestRun from and to JSON. */ implicit val decoder: Decoder[PipelineBranchesitemlatestRun] = deriveDecoder implicit val encoder: ObjectEncoder[PipelineBranchesitemlatestRun] = deriveEncoder }
mit
drakmail/mandarin_pay
lib/mandarin_pay.rb
678
require "mandarin_pay/engine" require "mandarin_pay/client" require "mandarin_pay/payment_interface" require "mandarin_pay/notification" module MandarinPay def configure(&block) MandarinPay::Client.configure(&block) end MandarinPay::Configuration::ATTRIBUTES.map do |name| define_singleton_method name do MandarinPay::Client.configuration.send(name) end end def pay_url(invoice_id, total, custom_params, extra_params = {}) MandarinPay::PaymentInterface.new do self.total = total self.invoice_id = invoice_id self.params = custom_params end.pay_url(extra_params) end module_function :configure, :pay_url end
mit
zepi/turbo
tests/modules-not-working/WrongModule/Module.php
2098
<?php /* * The MIT License (MIT) * * Copyright (c) 2015 zepi * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ /** * zepi Turbo Starter * * @package WrongModule * @author Matthias Zobrist <[email protected]> * @copyright Copyright (c) 2015 zepi */ namespace WrongModule; use \Zepi\Turbo\Module\ModuleAbstract; /** * zepi Turbo Starter * * @author Matthias Zobrist <[email protected]> * @copyright Copyright (c) 2015 zepi */ class Module extends ModuleAbstract { /** * Initializes the module * * @access public */ public function initialize() { } /** * This action will be executed on the activation of the module * * @access public * @param string $versionNumber * @param string $oldVersionNumber */ public function activate($versionNumber, $oldVersionNumber = '') { } /** * This action will be executed on the deactiviation of the module * * @access public */ public function deactivate() { } }
mit
AshV/Design-Patterns
H-Command Pattern/H Solution 3/AbstractCommand.cs
337
namespace H_Solution_3 { public abstract class AbstractCommand { protected Square square; public AbstractCommand(Square square) { this.square = square; } public Square getSquare() { return square; } public abstract void undo(); } }
mit
paulpatarinski/WebClientGenerator
ServerComponent/WebClientAutomatorTest/WebApiSchemaReaderTest.cs
2851
using System.Linq; using System.Reflection; using FluentAssertions; using NUnit.Framework; using WebClientAutomator; using WebClientAutomator.Models; namespace WebClientAutomatorTest { [TestFixture] public class WebApiSchemaReaderTest { private Assembly _webApiAssembly; private WebApiSchemaReader _webApiSchemaReader; [SetUp] public void SetUp() { _webApiAssembly = Assembly.LoadFrom(@"..\..\..\WebApi\bin\WebApi.dll"); Assert.IsNotNull(_webApiAssembly); _webApiSchemaReader = new WebApiSchemaReader(); } [Test] public void GetWebApiSchema_ShouldReturnCorrectSchema() { var webApiSchema = _webApiSchemaReader.GetWebApiSchema(_webApiAssembly); webApiSchema.Should().NotBeNull(); webApiSchema.Controllers.Count.Should().Be(4); } [Test] public void GetWebApiSchema_ShouldReturnCorrectNumberOfMethods() { var webApiSchema = _webApiSchemaReader.GetWebApiSchema(_webApiAssembly); var methods = webApiSchema.Controllers.SelectMany(x => x.Methods).ToList(); var parameterComplexTypes = methods.SelectMany(x => x.Parameters).Where(x => x.ComplexType != null).Select(x => x.ComplexType).ToList(); //Account Controller var accountController = webApiSchema.Controllers.FirstOrDefault(x => x.Name.Equals("AccountController")); accountController.Should().NotBeNull(); accountController.Methods.Count.Should().Be(12); //Values Controller var valuesController = webApiSchema.Controllers.FirstOrDefault(x => x.Name.Equals("ValuesController")); valuesController.Should().NotBeNull(); valuesController.Methods.Count.Should().Be(5); } [Test] public void GetComplexType_ShouldReturnAComplexType() { var type = _webApiAssembly.Types().FirstOrDefault(x => x.Name.Equals("UserViewModel")); type.Should().NotBeNull(); var complexType = _webApiSchemaReader.GetComplexType(type); complexType.Properties.Count.Should().Be(10); complexType.Properties.Count(x => x.PropertyType == PropertyType.Primitive).Should().Be(7); complexType.Properties.Count(x => x.PropertyType == PropertyType.IEnumerableT && x.PrimitiveType == PrimitiveType.String).Should().Be(1); var childComplexTypes = complexType.Properties.Where(x => x.ComplexType != null).ToList(); childComplexTypes.Should().NotBeNull(); childComplexTypes.Count().Should().Be(2); var userDetailViewModel = childComplexTypes[0]; userDetailViewModel.PropertyType.Should().Be(PropertyType.Complex); userDetailViewModel.ComplexType.Properties.Count.Should().Be(2); var departments = childComplexTypes[1]; departments.PropertyType.Should().Be(PropertyType.IEnumerableT); departments.ComplexType.Properties.Count.Should().Be(1); } } }
mit
CvetoslavSimeonov/TelerikAcademy
C#/1-Intro-Programming-Homework/03. Print Numbers/Properties/AssemblyInfo.cs
1410
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("03. Print Numbers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("03. Print Numbers")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e46e61cd-d059-4f6b-9ebb-548d99beaf49")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
MrRacoon/reredeux
dist/deux.js
4773
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.patchAction = undefined; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _empty; var _ramda = require('ramda'); var _tools = require('./tools'); var _labels = require('./labels'); function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var empty = (_empty = {}, _defineProperty(_empty, _labels.INIT, {}), _defineProperty(_empty, _labels.SELECT, {}), _defineProperty(_empty, _labels.DUCKS, []), _empty); var deux = function deux(obj) { var _ref4; var post = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (0, _ramda.always)(empty); if (obj && typeof obj[_labels.INIT] !== 'undefined') { return obj; } var constructed = (0, _ramda.reduce)(function (acc, _ref) { var _ref3; var _ref2 = _slicedToArray(_ref, 2), name = _ref2[0], value = _ref2[1]; var cur = deux(value); return _ref3 = {}, _defineProperty(_ref3, _labels.NAME, ''), _defineProperty(_ref3, _labels.INIT, _extends({}, acc[_labels.INIT] || {}, _defineProperty({}, name, cur[_labels.INIT] || {}))), _defineProperty(_ref3, _labels.SELECT, _extends({}, acc[_labels.SELECT] || {}, _defineProperty({}, name, _extends({}, selectorPatch(name, cur[_labels.SELECT] || {}), _defineProperty({}, _labels.BOTTOM, (0, _ramda.prop)(name)))))), _defineProperty(_ref3, _labels.DUCKS, (0, _ramda.compose)((0, _ramda.concat)(acc[_labels.DUCKS]), (0, _ramda.map)(patchReducer(name)), (0, _ramda.map)(patchAction(name)), (0, _ramda.map)(addType(name)), (0, _ramda.chain)(_tools.expandDefers))(cur[_labels.DUCKS])), _ref3; }, empty, (0, _ramda.toPairs)(obj)); var toMerge = post(constructed); return _ref4 = {}, _defineProperty(_ref4, _labels.NAME, ''), _defineProperty(_ref4, _labels.INIT, _extends({}, constructed[_labels.INIT], toMerge[_labels.INIT])), _defineProperty(_ref4, _labels.SELECT, _extends({}, constructed[_labels.SELECT], toMerge[_labels.SELECT])), _defineProperty(_ref4, _labels.DUCKS, [].concat(_toConsumableArray(constructed[_labels.DUCKS]), _toConsumableArray(toMerge[_labels.DUCKS]))), _ref4; }; exports.default = deux; var selectorPatch = (0, _ramda.curry)(function (n, sel) { switch (typeof sel === 'undefined' ? 'undefined' : _typeof(sel)) { case 'object': return (0, _ramda.map)(selectorPatch(n), sel); case 'function': return function (state) { return sel(state[n]); }; default: return sel; } }); var patchAction = exports.patchAction = (0, _ramda.curry)(function (name, duck) { if (duck[_labels.PROMISE]) return duck; return _extends({}, duck, _defineProperty({}, _labels.ACTION, function () { return _extends({}, duck[_labels.ACTION].apply(duck, arguments), _defineProperty({}, _labels.TYPE, duck[_labels.TYPE])); })); }); var addType = (0, _ramda.curry)(function (name, duck) { return _extends({}, duck, _defineProperty({}, _labels.TYPE, name + '/' + (duck[_labels.TYPE] || duck[_labels.NAME]))); }); var patchReducer = (0, _ramda.curry)(function (name, duck) { return _extends({}, duck, _defineProperty({}, _labels.REDUCER, function (state, action) { return _extends({}, state, _defineProperty({}, name, duck[_labels.REDUCER](state[name], action))); })); });
mit
Hayawi/TAB2PDF
src/ParseFile.java
6412
import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.IOUtils; import com.itextpdf.text.DocumentException; public class ParseFile { public static String openFile(String filePath) throws IOException{ FileInputStream inputStream = new FileInputStream(filePath); String file; try { file = IOUtils.toString(inputStream); } finally { inputStream.close(); } return file; } public static ArrayList<Measure> sortMeasure(String body) { String line = ""; int indexOfNewLine = 0; int indexOfVerticalLine = 0; String checkString = ""; Pattern pattern = Pattern.compile("\\|?(\\||([0-9]))(-|\\*)"); Pattern pattern2 = Pattern.compile("\\|?(\\|)(-|\\*)"); ArrayList<String> blockOfMeasures = new ArrayList<String>(); ArrayList<Measure> measures = new ArrayList<Measure>(); // forgot why body length > 0 is used, check again later while (indexOfNewLine != -1 && body.length() > 0) { for (int i = 0; i < 6; i ++) { Matcher matcher = pattern.matcher(body); if (matcher.find()) { indexOfVerticalLine = matcher.start(); indexOfNewLine = body.indexOf('\n', indexOfVerticalLine + 1); int check2 = body.indexOf('\n', indexOfNewLine + 1); checkString = body.substring(indexOfNewLine, check2).trim(); Matcher check = pattern2.matcher(checkString); if (!check.find() && i != 5) { blockOfMeasures.clear(); break; } line = body.substring(indexOfVerticalLine, indexOfNewLine).trim(); if (line.lastIndexOf("| ") > 0) line = line.substring(0, line.lastIndexOf("| ") + 2).trim(); body = body.substring(indexOfNewLine + 1); blockOfMeasures.add(line); } } if (unevenBlockLengthCheck(blockOfMeasures)) { String message = ""; for (String s : blockOfMeasures) { message = message + s + '\n'; } throw new InvalidMeasureException("This measure is formatted incorrectly.\n" + message); } if (blockOfMeasures.size() > 0) measures.addAll(convertToMeasures(blockOfMeasures)); blockOfMeasures.clear(); body = body.substring(body.indexOf('\n') + 1); if (body.indexOf('\n') <= 1) { // something idk check again later while (body.indexOf('\n') >= 0 && body.indexOf('\n') <= 1) body = body.substring(body.indexOf('\n') + 1); } } return measures; } public static ArrayList<String> parse(String string) { ArrayList<String> token = new ArrayList<String>(); String hyphen = ""; Pattern isDigit = Pattern.compile("^[0-9]"); for (int i = 0; i < string.length(); i++) { Matcher matcher = isDigit.matcher(string); if (string.charAt(i) == '|') { if ((i + 1 < string.length()) && (i + 2 < string.length()) && string.charAt(i+1) == '|' && string.charAt(i+2) == '|') { token.add("|||"); i = i + 2; } else if ((i + 1 < string.length()) && string.charAt(i+1) == '|') { token.add("||"); i++; } else if ((i + 1 < string.length()) && (i + 2 < string.length()) && string.charAt(i+1) == '|' && string.charAt(i+2) == '|') { token.add("|||"); i = i + 2; } else if ((i + 1 < string.length()) && (string.charAt(i+1) >= '0' && (string.charAt(i+1) <= '9'))) { token.add("|" + string.charAt(i+1)); i++; } else token.add("|"); } else if (string.charAt(i) == '-') { while (string.charAt(i) == '-') { hyphen = hyphen + "-"; // use stringbuilder or something for this later i++; if (i == string.length()) break; } token.add(hyphen); hyphen = ""; i--; } else if (string.charAt(i) == ' ') { i++; while (string.charAt(i) == ' ') { hyphen = hyphen + "-"; i++; if (i == string.length()) break; } token.add(hyphen); hyphen = ""; i--; } else if ((string.charAt(i) >= '0' && (string.charAt(i) <= '9')) && i > 0) { //check the second digit only if index + 1 is not equal to the length of the string if (i + 1 < string.length()) // if the second digit is a number, we will treat it as a two-digit number. if (string.charAt(i + 1) >= '0' && (string.charAt(i + 1) <= '9')) { if (string.charAt(i-1) == '<') { token.add(string.substring(i-1, i+3)); i = i + 2; } else { token.add(string.substring(i, i+2)); i = i + 1; } } // if the character ahead is not a digit, we check if the previous character is a angle bracket else if (string.charAt(i-1) == '<') { token.add(string.substring(i-1,i+2)); i = i + 1; } // if not we just add the number itself. else { token.add("" + string.charAt(i)); } } else if (string.charAt(i) == 's') token.add("s"); else if (string.charAt(i) == '*') token.add("*"); else if (string.charAt(i) == 'h') token.add("h"); else if (string.charAt(i) == 'p') token.add("p"); else if (matcher.find()) { token.add("" + string.charAt(i)); } else { if (string.charAt(i) != '>' && string.charAt(i) != '<') token.add("-"); } } return token; } public static ArrayList<Measure> convertToMeasures(ArrayList<String> block) { Pattern separator = Pattern.compile("(\\||^[0-9])([0-9]|\\|)?\\|?"); Matcher matcher = separator.matcher(block.get(2)); ArrayList<String> measure = new ArrayList<String>(); ArrayList<Measure> newMeasures = new ArrayList<Measure>(); int indexOfBeginningStaff = 0; matcher.find(); while (matcher.find()) { for (String s : block) { measure.add(s.substring(indexOfBeginningStaff, matcher.end())); } newMeasures.add(new Measure(measure)); measure.clear(); indexOfBeginningStaff = matcher.start(); } return newMeasures; } public static boolean unevenBlockLengthCheck(ArrayList<String> blockOfMeasures) { HashSet<Integer> lengths = new HashSet<Integer>(); for (String s : blockOfMeasures) { lengths.add(s.length()); } if (lengths.size() > 1) return true; return false; } }
mit
mryyomutga/CS_Exercise
Beginners/p3/Iteration1.cs
704
/* * while文による繰り返し処理 */ using System; namespace iteration1{ class Program{ public static void Main(string[] args){ int a, b; Console.WriteLine("ユークリッドの互除法を用いて最大公約数を求めます"); Console.Write("1つめの整数を入力してください : "); a = int.Parse(Console.ReadLine()); Console.Write("2つめの整数を入力してください : "); b = int.Parse(Console.ReadLine()); Console.Write("{0}と{1}の最大公約数は", a, b); // while : 条件がtrueになるまで繰り返す while(b != 0){ int r = a % b; a = b; b = r; } Console.Write("{0}", a); } } }
mit
connectim/Android
app/src/main/java/connect/ui/activity/login/KeepLiveActivity.java
2436
package connect.ui.activity.login; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.PowerManager; import android.view.Gravity; import android.view.Window; import android.view.WindowManager; import org.greenrobot.eventbus.EventBus; import connect.ui.base.BaseActivity; /** * Monitor the phone lock screen to unlock the event, when the screen lock screen to start the 1 pixel Activity, * the user will be destroyed when unlocking Activity. Note that the Activity needs to be designed to be user aware. * Created by pujin on 2017/5/11. */ public class KeepLiveActivity extends BaseActivity { private final static String Tag = "KeepLive"; public KeepLiveActivity activity; private BroadcastReceiver receiver = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initView(); } public static void startActity(Context context) { Intent intent = new Intent(context, KeepLiveActivity.class); context.startActivity(intent); } @Override public void initView() { activity = this; Window window = getWindow(); window.setGravity(Gravity.LEFT | Gravity.TOP); WindowManager.LayoutParams params = window.getAttributes(); params.x = 0; params.y = 0; params.width = 1; params.height = 1; window.setAttributes(params); receiver =new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { finish(); } }; IntentFilter filter = new IntentFilter(); filter.addAction("KeepLive"); registerReceiver(receiver, filter); } @Override protected void onResume() { super.onResume(); checkScreenOn(); } @Override protected void onDestroy() { super.onDestroy(); try { unregisterReceiver(receiver); } catch (Exception e) { e.printStackTrace(); } } private void checkScreenOn() { PowerManager manager = (PowerManager) activity.getSystemService(Context.POWER_SERVICE); boolean isScreenOn = manager.isScreenOn(); if (isScreenOn) { finish(); } } }
mit
freedot/uts
Assets/Resources/tss/test/test_dynamic_load_ui.ts
5078
import ut = require("../unittest/unittest"); import uts = require("../uts/uts"); namespace UnityEngine { export class UObject extends __DynBind { constructor(isCreate: boolean = true, name: string = 'UnityEngine.Object,UnityEngine') { if (isCreate) super(name); } static Instantiate(object: GameObject): GameObject { return __DynBind.__call(0, 'UnityEngine.Object,UnityEngine.Instantiate', uts.RET_TYPE.CLASSOBJECT, UnityEngine.GameObject, object, uts.ARG_TYPE.OBJECT); } } export class Component extends UObject { constructor(isCreate: boolean = true) { if (isCreate) super(isCreate, 'UnityEngine.Component,UnityEngine'); } } export class GameObject extends UObject { constructor(isCreate: boolean = true) { if (isCreate) super(isCreate, 'UnityEngine.GameObject,UnityEngine'); } static Find(name: string): GameObject { return __DynBind.__call(0, 'UnityEngine.GameObject,UnityEngine.Find', uts.RET_TYPE.CLASSOBJECT, UnityEngine.GameObject, name); } static ToType(o: UObject): GameObject { return __DynBind.__as(o, 'UnityEngine.GameObject,UnityEngine', UnityEngine.GameObject); } GetComponent(stype: string): Component { return super.__call(0, 'GetComponent', uts.RET_TYPE.CLASSOBJECT, UnityEngine.Component, stype); } } export class Resources extends __DynBind { constructor(isCreate: boolean = true) { if (isCreate) super('UnityEngine.Resources,UnityEngine'); } static Load(name: string): GameObject { return __DynBind.__call(0, 'UnityEngine.Resources,UnityEngine.Load', uts.RET_TYPE.CLASSOBJECT, UnityEngine.GameObject, name); } } export namespace UI { export class ButtonClickedEvent extends __DynBind { AddListener(callback: any) { return super.__call(0, 'AddListener', uts.RET_TYPE.VOID, callback, uts.ARG_TYPE.CALLBACK, 0); } } export class Button extends Component { static ToType(o: UObject): Button { return __DynBind.__as(o, 'UnityEngine.UI.Button,UnityEngine.UI', UnityEngine.UI.Button); } get onClick(): ButtonClickedEvent { return super.__get('onClick', uts.RET_TYPE.CLASSOBJECT, ButtonClickedEvent); } } } } // GameEngine can move to c# namespace GameEngine { export namespace UI { export class Panel { private _object: UnityEngine.GameObject = null; constructor(object: UnityEngine.GameObject) { this._object = object; } show() { } hide() { } } export class Api { static loadPanel(path: string): Panel { let panel = UnityEngine.Resources.Load(path); return new Panel(UnityEngine.GameObject.Instantiate(panel)); } static addListener(path: string, etype: string, callback: () => void) { if (etype == 'button.click') { let btnObj = UnityEngine.GameObject.Find(path); let btnc = btnObj.GetComponent('Button'); let btn = UnityEngine.UI.Button.ToType(btnc); btn.onClick.AddListener(callback); } } } } } // sample ui framework namespace UI { export class BaseDialog { private _panel: GameEngine.UI.Panel = null; constructor() { Manager.regDialog(this.dialogName, this); } public open() { if (this._panel == null) { this._panel = GameEngine.UI.Api.loadPanel(this.getResPath()); this.bindListeners(); } Manager.showDialog(this); this._panel.show(); } public close() { this._panel.hide(); } protected getResPath(): string { return ''; } protected get dialogName(): string { return ''; } protected initElements() { } protected bindListeners() { } } export class Manager { static getDialog(name:string): BaseDialog{ return null; } static regDialog(name: string, dlg: BaseDialog) { } static showDialog(dlg: BaseDialog) { } } } class LoginDialog extends UI.BaseDialog { protected getResPath(): string { return 'ui/login'; } protected get dialogName(): string { return 'login'; } protected bindListeners() { GameEngine.UI.Api.addListener('login(Clone)/loginButton', 'button.click', this.onClickLoginButton); } private onClickLoginButton() { uts.log('click login button !'); } } export function test() { uts.log('----------- test_dynamic_load_ui ------------'); let dlg = new LoginDialog(); dlg.open(); uts.log(" test ok"); }
mit
Quallcode/forkes
application/controllers/Compiler/Import.php
678
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Import extends CI_Controller { function __construct() { // Construct the parent class parent::__construct(); $this->load->helper('cURL_helper'); $this->load->model('users_model'); $this->load->library(array('PHPExcel','PHPExcel/IOFactory')); } public function index() { if($this->session->userdata('nama')==NULL) { redirect('users'); } else { //$data['merchant']=$this->admin_model->merchant(); //print_r($data['merchant']); exit; $this->load->view('import'); } } public function insert_file() { } }
mit
licaomeng/Android-PullToRefresh-SwipeMenuListView-Sample
Eclipse/Library_PullToRefreshSwipeMenuListView/src/edu/swu/pulltorefreshswipemenulistview/library/swipemenu/view/SwipeMenuView.java
3195
package edu.swu.pulltorefreshswipemenulistview.library.swipemenu.view; import java.util.List; import android.text.TextUtils; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import edu.swu.pulltorefreshswipemenulistview.library.PullToRefreshSwipeMenuListView; import edu.swu.pulltorefreshswipemenulistview.library.swipemenu.bean.SwipeMenu; import edu.swu.pulltorefreshswipemenulistview.library.swipemenu.bean.SwipeMenuItem; import edu.swu.pulltorefreshswipemenulistview.library.swipemenu.interfaces.OnSwipeItemClickListener; public class SwipeMenuView extends LinearLayout implements OnClickListener { private PullToRefreshSwipeMenuListView mListView; private SwipeMenuLayout mLayout; private SwipeMenu mMenu; private OnSwipeItemClickListener onItemClickListener; private int position; public int getPosition() { return position; } public void setPosition(int position) { this.position = position; } public SwipeMenuView(SwipeMenu menu, PullToRefreshSwipeMenuListView listView) { super(menu.getContext()); mListView = listView; mMenu = menu; List<SwipeMenuItem> items = menu.getMenuItems(); int id = 0; for (SwipeMenuItem item : items) { addItem(item, id++); } } private void addItem(SwipeMenuItem item, int id) { LayoutParams params = new LayoutParams(item.getWidth(), LayoutParams.MATCH_PARENT); LinearLayout parent = new LinearLayout(getContext()); parent.setId(id); parent.setGravity(Gravity.CENTER); parent.setOrientation(LinearLayout.VERTICAL); parent.setLayoutParams(params); parent.setBackgroundDrawable(item.getBackground()); parent.setOnClickListener(this); addView(parent); if (item.getIcon() != null) { parent.addView(createIcon(item)); } if (!TextUtils.isEmpty(item.getTitle())) { parent.addView(createTitle(item)); } } private ImageView createIcon(SwipeMenuItem item) { ImageView iv = new ImageView(getContext()); iv.setImageDrawable(item.getIcon()); return iv; } private TextView createTitle(SwipeMenuItem item) { TextView tv = new TextView(getContext()); tv.setText(item.getTitle()); tv.setGravity(Gravity.CENTER); tv.setTextSize(item.getTitleSize()); tv.setTextColor(item.getTitleColor()); return tv; } @Override public void onClick(View v) { if (onItemClickListener != null && mLayout.isOpen()) { onItemClickListener.onItemClick(this, mMenu, v.getId()); } } public OnSwipeItemClickListener getOnSwipeItemClickListener() { return onItemClickListener; } public void setOnSwipeItemClickListener(OnSwipeItemClickListener onItemClickListener) { this.onItemClickListener = onItemClickListener; } public void setLayout(SwipeMenuLayout mLayout) { this.mLayout = mLayout; } }
mit
nathantreid/shattered
rljs/typings/rot-js.d.ts
15438
declare module "rot-js" { /** Declaration file generated by dts-gen */ export class Display { constructor(options: any); DEBUG(x: any, y: any, what: any): void; clear(): void; computeFontSize(availWidth: any, availHeight: any): any; computeSize(availWidth: any, availHeight: any): any; draw(x: any, y: any, ch: any, fg: any, bg: any, ov: any): void; drawText(x: any, y: any, text: any, maxWidth: any): any; eventToPosition(e: any): any; getContainer(): any; getOptions(): any; setOptions(options: any): any; } export class Engine { constructor(scheduler: any); lock(): any; start(): any; unlock(): any; } export class EventQueue { constructor(); add(event: any, time: any): void; clear(): any; get(): any; getEventTime(event: any): any; getTime(): any; remove(event: any): any; } export class FOV { constructor(lightPassesCallback: any, options: any); compute(x: any, y: any, R: any, callback: any): void; } export class Lighting { constructor(reflectivityCallback: any, options: any); clearLights(): void; compute(lightingCallback: any): any; reset(): any; setFOV(fov: any): any; setLight(x: any, y: any, color: any): any; setOptions(options: any): any; } export class Map { constructor(width: any, height: any); create(callback: any): void; } export class Noise { constructor(); get(x: any, y: any): void; } export class Path { constructor(toX: any, toY: any, passableCallback: any, options: any); compute(fromX: any, fromY: any, callback: any): void; } export class Scheduler { constructor(); add(item: any, repeat: any): any; clear(): any; getTime(): any; getTimeOf(item: any): any; next(): any; remove(item: any): any; } export class StringGenerator { constructor(options: any); clear(): void; generate(): any; getStats(): any; observe(string: any): void; } export const DEFAULT_HEIGHT: number; export const DEFAULT_WIDTH: number; export const DIRS: { "4": (number[])[]; "6": (number[])[]; "8": (number[])[]; }; export const VK_0: number; export const VK_1: number; export const VK_2: number; export const VK_3: number; export const VK_4: number; export const VK_5: number; export const VK_6: number; export const VK_7: number; export const VK_8: number; export const VK_9: number; export const VK_A: number; export const VK_ACCEPT: number; export const VK_ADD: number; export const VK_ALT: number; export const VK_ALTGR: number; export const VK_AMPERSAND: number; export const VK_ASTERISK: number; export const VK_AT: number; export const VK_B: number; export const VK_BACK_QUOTE: number; export const VK_BACK_SLASH: number; export const VK_BACK_SPACE: number; export const VK_C: number; export const VK_CANCEL: number; export const VK_CAPS_LOCK: number; export const VK_CIRCUMFLEX: number; export const VK_CLEAR: number; export const VK_CLOSE_BRACKET: number; export const VK_CLOSE_CURLY_BRACKET: number; export const VK_CLOSE_PAREN: number; export const VK_COLON: number; export const VK_COMMA: number; export const VK_CONTEXT_MENU: number; export const VK_CONTROL: number; export const VK_CONVERT: number; export const VK_D: number; export const VK_DECIMAL: number; export const VK_DELETE: number; export const VK_DIVIDE: number; export const VK_DOLLAR: number; export const VK_DOUBLE_QUOTE: number; export const VK_DOWN: number; export const VK_E: number; export const VK_EISU: number; export const VK_END: number; export const VK_ENTER: number; export const VK_EQUALS: number; export const VK_ESCAPE: number; export const VK_EXCLAMATION: number; export const VK_EXECUTE: number; export const VK_F: number; export const VK_F1: number; export const VK_F10: number; export const VK_F11: number; export const VK_F12: number; export const VK_F13: number; export const VK_F14: number; export const VK_F15: number; export const VK_F16: number; export const VK_F17: number; export const VK_F18: number; export const VK_F19: number; export const VK_F2: number; export const VK_F20: number; export const VK_F21: number; export const VK_F22: number; export const VK_F23: number; export const VK_F24: number; export const VK_F3: number; export const VK_F4: number; export const VK_F5: number; export const VK_F6: number; export const VK_F7: number; export const VK_F8: number; export const VK_F9: number; export const VK_FINAL: number; export const VK_G: number; export const VK_GREATER_THAN: number; export const VK_H: number; export const VK_HANGUL: number; export const VK_HANJA: number; export const VK_HASH: number; export const VK_HELP: number; export const VK_HOME: number; export const VK_HYPHEN_MINUS: number; export const VK_I: number; export const VK_INSERT: number; export const VK_J: number; export const VK_JUNJA: number; export const VK_K: number; export const VK_KANA: number; export const VK_KANJI: number; export const VK_L: number; export const VK_LEFT: number; export const VK_LESS_THAN: number; export const VK_M: number; export const VK_META: number; export const VK_MODECHANGE: number; export const VK_MULTIPLY: number; export const VK_N: number; export const VK_NONCONVERT: number; export const VK_NUMPAD0: number; export const VK_NUMPAD1: number; export const VK_NUMPAD2: number; export const VK_NUMPAD3: number; export const VK_NUMPAD4: number; export const VK_NUMPAD5: number; export const VK_NUMPAD6: number; export const VK_NUMPAD7: number; export const VK_NUMPAD8: number; export const VK_NUMPAD9: number; export const VK_NUM_LOCK: number; export const VK_O: number; export const VK_OPEN_BRACKET: number; export const VK_OPEN_CURLY_BRACKET: number; export const VK_OPEN_PAREN: number; export const VK_P: number; export const VK_PAGE_DOWN: number; export const VK_PAGE_UP: number; export const VK_PAUSE: number; export const VK_PERCENT: number; export const VK_PERIOD: number; export const VK_PIPE: number; export const VK_PLUS: number; export const VK_PRINT: number; export const VK_PRINTSCREEN: number; export const VK_Q: number; export const VK_QUESTION_MARK: number; export const VK_QUOTE: number; export const VK_R: number; export const VK_RETURN: number; export const VK_RIGHT: number; export const VK_S: number; export const VK_SCROLL_LOCK: number; export const VK_SELECT: number; export const VK_SEMICOLON: number; export const VK_SEPARATOR: number; export const VK_SHIFT: number; export const VK_SLASH: number; export const VK_SLEEP: number; export const VK_SPACE: number; export const VK_SUBTRACT: number; export const VK_T: number; export const VK_TAB: number; export const VK_TILDE: number; export const VK_U: number; export const VK_UNDERSCORE: number; export const VK_UP: number; export const VK_V: number; export const VK_W: number; export const VK_WIN: number; export const VK_X: number; export const VK_Y: number; export const VK_Z: number; export function isSupported(): any; export namespace Color { function add(color1: any, color2: any, ...args: any[]): any; function add_(color1: any, color2: any, ...args: any[]): any; function fromString(str: any): any; function hsl2rgb(color: any): any; function interpolate(color1: any, color2: any, factor: any, ...args: any[]): any; function interpolateHSL(color1: any, color2: any, factor: any, ...args: any[]): any; function multiply(color1: any, color2: any, ...args: any[]): any; function multiply_(color1: any, color2: any, ...args: any[]): any; function randomize(color: any, diff: any): any; function rgb2hsl(color: any): any; function toHex(color: any): any; function toRGB(color: any): any; } export namespace Display { class Backend { constructor(context: any); compute(options: any): void; computeFontSize(availWidth: any, availHeight: any): void; computeSize(availWidth: any, availHeight: any): void; draw(data: any, clearBefore: any): void; eventToPosition(x: any, y: any): void; } class Hex { constructor(context: any); compute(options: any): void; computeFontSize(availWidth: any, availHeight: any): any; computeSize(availWidth: any, availHeight: any): any; draw(data: any, clearBefore: any): void; eventToPosition(x: any, y: any): any; } class Rect { constructor(context: any); compute(options: any): void; computeFontSize(availWidth: any, availHeight: any): any; computeSize(availWidth: any, availHeight: any): any; draw(data: any, clearBefore: any): void; eventToPosition(x: any, y: any): any; static cache: boolean; } class Term { constructor(context: any); compute(options: any): void; computeFontSize(availWidth: any, availHeight: any): any; computeSize(availWidth: any, availHeight: any): any; draw(data: any, clearBefore: any): void; eventToPosition(x: any, y: any): any; } class Tile { constructor(context: any); compute(options: any): void; computeFontSize(availWidth: any, availHeight: any): any; computeSize(availWidth: any, availHeight: any): any; draw(data: any, clearBefore: any): void; eventToPosition(x: any, y: any): any; } namespace Term { class Color { constructor(context: any); clearToAnsi(bg: any): void; colorToAnsi(fg: any, bg: any): void; positionToAnsi(x: any, y: any): void; } class Xterm { constructor(context: any); clearToAnsi(bg: any): any; colorToAnsi(fg: any, bg: any): any; positionToAnsi(x: any, y: any): any; } } } export namespace FOV { class DiscreteShadowcasting { constructor(lightPassesCallback: any, options: any); compute(x: any, y: any, R: any, callback: any): void; } class PreciseShadowcasting { constructor(lightPassesCallback: any, options: any); compute(x: any, y: any, R: any, callback: any): void; } class RecursiveShadowcasting { constructor(lightPassesCallback: any, options: any); compute(x: any, y: any, R: any, callback: any): void; compute180(x: any, y: any, R: any, dir: any, callback: any): void; compute90(x: any, y: any, R: any, dir: any, callback: any): void; static OCTANTS: (number[])[]; } } export namespace Map { class Arena { constructor(width: any, height: any); create(callback: any): any; } class Cellular { constructor(width: any, height: any, options: any); connect(callback: any, value: any, connectionCallback: any): void; create(callback: any): void; randomize(probability: any): any; serviceCallback(callback: any): void; set(x: any, y: any, value: any): void; setOptions(options: any): void; } class Digger { constructor(width: any, height: any, options: any); create(callback: any): any; } class DividedMaze { constructor(width: any, height: any); create(callback: any): any; } class Dungeon { constructor(width: any, height: any); getCorridors(): any; getRooms(): any; } class EllerMaze { constructor(width: any, height: any); create(callback: any): any; } class Feature { constructor(); create(digCallback: any): void; debug(): void; isValid(canBeDugCallback: any): void; static createRandomAt(x: any, y: any, dx: any, dy: any, options: any): void; } class IceyMaze { constructor(width: any, height: any, regularity: any); create(callback: any): any; } class Rogue { constructor(width: any, height: any, options: any); create(callback: any): any; } class Uniform { constructor(width: any, height: any, options: any); create(callback: any): any; } namespace Feature { class Corridor { constructor(startX: any, startY: any, endX: any, endY: any); create(digCallback: any): any; createPriorityWalls(priorityWallCallback: any): void; debug(): void; isValid(isWallCallback: any, canBeDugCallback: any): any; static createRandomAt(x: any, y: any, dx: any, dy: any, options: any): any; } class Room { constructor(x1: any, y1: any, x2: any, y2: any, doorX: any, doorY: any, ...args: any[]); addDoor(x: any, y: any): any; addDoors(isWallCallback: any): any; clearDoors(): any; create(digCallback: any): void; debug(): void; getBottom(): any; getCenter(): any; getDoors(callback: any): any; getLeft(): any; getRight(): any; getTop(): any; isValid(isWallCallback: any, canBeDugCallback: any): any; static createRandom(availWidth: any, availHeight: any, options: any): any; static createRandomAt(x: any, y: any, dx: any, dy: any, options: any): any; static createRandomCenter(cx: any, cy: any, options: any): any; } } } export namespace Noise { class Simplex { constructor(gradients: any); get(xin: any, yin: any): any; } } export namespace Path { class AStar { constructor(toX: any, toY: any, passableCallback: any, options: any); compute(fromX: any, fromY: any, callback: any): void; } class Dijkstra { constructor(toX: any, toY: any, passableCallback: any, options: any); compute(fromX: any, fromY: any, callback: any): void; } } export namespace RNG { function clone(): any; function getNormal(mean: any, stddev: any): any; function getPercentage(): any; function getSeed(): any; function getState(): any; function getUniform(): any; function getUniformInt(lowerBound: any, upperBound: any): number; function getWeightedValue(data: any): any; function setSeed(seed: any): any; function setState(state: any): any; } export namespace Scheduler { class Action { constructor(); add(item: any, repeat: any, time: any): any; clear(): any; next(): any; remove(item: any): any; setDuration(time: any): any; } class Simple { constructor(); add(item: any, repeat: any): any; next(): any; } class Speed { constructor(); add(item: any, repeat: any, time: any): any; next(): any; } } export namespace Text { const RE_COLORS: RegExp; const TYPE_BG: number; const TYPE_FG: number; const TYPE_NEWLINE: number; const TYPE_TEXT: number; function measure(str: any, maxWidth: any): any; function tokenize(str: any, maxWidth: any): any; } }
mit
janko33bd/bitcoinjs-lib
test/ecpair.js
7216
/* global describe, it, beforeEach */ /* eslint-disable no-new */ var assert = require('assert') var ecdsa = require('../src/ecdsa') var ecurve = require('ecurve') var proxyquire = require('proxyquire') var sinon = require('sinon') var BigInteger = require('bigi') var ECPair = require('../src/ecpair') var fixtures = require('./fixtures/ecpair.json') var curve = ecdsa.__curve var NETWORKS = require('../src/networks') var NETWORKS_LIST = [] // Object.values(NETWORKS) for (var networkName in NETWORKS) { NETWORKS_LIST.push(NETWORKS[networkName]) } describe('ECPair', function () { describe('constructor', function () { it('defaults to compressed', function () { var keyPair = new ECPair(BigInteger.ONE) assert.strictEqual(keyPair.compressed, true) }) it('supports the uncompressed option', function () { var keyPair = new ECPair(BigInteger.ONE, null, { compressed: false }) assert.strictEqual(keyPair.compressed, false) }) it('supports the network option', function () { var keyPair = new ECPair(BigInteger.ONE, null, { compressed: false, network: NETWORKS.testnet }) assert.strictEqual(keyPair.network, NETWORKS.testnet) }) fixtures.valid.forEach(function (f) { it('calculates the public point for ' + f.WIF, function () { var d = new BigInteger(f.d) var keyPair = new ECPair(d, null, { compressed: f.compressed }) assert.strictEqual(keyPair.getPublicKeyBuffer().toString('hex'), f.Q) }) }) fixtures.invalid.constructor.forEach(function (f) { it('throws ' + f.exception, function () { var d = f.d && new BigInteger(f.d) var Q = f.Q && ecurve.Point.decodeFrom(curve, new Buffer(f.Q, 'hex')) assert.throws(function () { new ECPair(d, Q, f.options) }, new RegExp(f.exception)) }) }) }) describe('getPublicKeyBuffer', function () { var keyPair beforeEach(function () { keyPair = new ECPair(BigInteger.ONE) }) it('wraps Q.getEncoded', sinon.test(function () { this.mock(keyPair.Q).expects('getEncoded') .once().withArgs(keyPair.compressed) keyPair.getPublicKeyBuffer() })) }) describe('fromWIF', function () { fixtures.valid.forEach(function (f) { it('imports ' + f.WIF + ' (' + f.network + ')', function () { var network = NETWORKS[f.network] var keyPair = ECPair.fromWIF(f.WIF, network) assert.strictEqual(keyPair.d.toString(), f.d) assert.strictEqual(keyPair.compressed, f.compressed) assert.strictEqual(keyPair.network, network) }) }) fixtures.valid.forEach(function (f) { it('imports ' + f.WIF + ' (via list of networks)', function () { var keyPair = ECPair.fromWIF(f.WIF, NETWORKS_LIST) assert.strictEqual(keyPair.d.toString(), f.d) assert.strictEqual(keyPair.compressed, f.compressed) assert.strictEqual(keyPair.network, NETWORKS[f.network]) }) }) fixtures.invalid.fromWIF.forEach(function (f) { it('throws on ' + f.WIF, function () { assert.throws(function () { var networks = f.network ? NETWORKS[f.network] : NETWORKS_LIST ECPair.fromWIF(f.WIF, networks) }, new RegExp(f.exception)) }) }) }) describe('toWIF', function () { fixtures.valid.forEach(function (f) { it('exports ' + f.WIF, function () { var keyPair = ECPair.fromWIF(f.WIF, NETWORKS_LIST) var result = keyPair.toWIF() assert.strictEqual(result, f.WIF) }) }) }) describe('makeRandom', function () { var d = new Buffer('0404040404040404040404040404040404040404040404040404040404040404', 'hex') var exWIF = 'KwMWvwRJeFqxYyhZgNwYuYjbQENDAPAudQx5VEmKJrUZcq6aL2pv' describe('uses randombytes RNG', function () { it('generates a ECPair', function () { var stub = { randombytes: function () { return d } } var ProxiedECPair = proxyquire('../src/ecpair', stub) var keyPair = ProxiedECPair.makeRandom() assert.strictEqual(keyPair.toWIF(), exWIF) }) }) it('allows a custom RNG to be used', function () { var keyPair = ECPair.makeRandom({ rng: function (size) { return d.slice(0, size) } }) assert.strictEqual(keyPair.toWIF(), exWIF) }) it('retains the same defaults as ECPair constructor', function () { var keyPair = ECPair.makeRandom() assert.strictEqual(keyPair.compressed, true) assert.strictEqual(keyPair.network, NETWORKS.bitcoin) }) it('supports the options parameter', function () { var keyPair = ECPair.makeRandom({ compressed: false, network: NETWORKS.testnet }) assert.strictEqual(keyPair.compressed, false) assert.strictEqual(keyPair.network, NETWORKS.testnet) }) it('loops until d is within interval [1, n - 1] : 1', sinon.test(function () { var rng = this.mock() rng.exactly(2) rng.onCall(0).returns(BigInteger.ZERO.toBuffer(32)) // invalid length rng.onCall(1).returns(BigInteger.ONE.toBuffer(32)) // === 1 ECPair.makeRandom({ rng: rng }) })) it('loops until d is within interval [1, n - 1] : n - 1', sinon.test(function () { var rng = this.mock() rng.exactly(3) rng.onCall(0).returns(BigInteger.ZERO.toBuffer(32)) // < 1 rng.onCall(1).returns(curve.n.toBuffer(32)) // > n-1 rng.onCall(2).returns(curve.n.subtract(BigInteger.ONE).toBuffer(32)) // === n-1 ECPair.makeRandom({ rng: rng }) })) }) describe('getAddress', function () { fixtures.valid.forEach(function (f) { it('returns ' + f.address + ' for ' + f.WIF, function () { var keyPair = ECPair.fromWIF(f.WIF, NETWORKS_LIST) assert.strictEqual(keyPair.getAddress(), f.address) }) }) }) describe('getNetwork', function () { fixtures.valid.forEach(function (f) { it('returns ' + f.network + ' for ' + f.WIF, function () { var network = NETWORKS[f.network] var keyPair = ECPair.fromWIF(f.WIF, NETWORKS_LIST) assert.strictEqual(keyPair.getNetwork(), network) }) }) }) describe('ecdsa wrappers', function () { var keyPair, hash beforeEach(function () { keyPair = ECPair.makeRandom() hash = new Buffer(32) }) describe('signing', function () { it('wraps ecdsa.sign', sinon.test(function () { this.mock(ecdsa).expects('sign') .once().withArgs(hash, keyPair.d) keyPair.sign(hash) })) it('throws if no private key is found', function () { keyPair.d = null assert.throws(function () { keyPair.sign(hash) }, /Missing private key/) }) }) describe('verify', function () { var signature beforeEach(function () { signature = keyPair.sign(hash) }) it('wraps ecdsa.verify', sinon.test(function () { this.mock(ecdsa).expects('verify') .once().withArgs(hash, signature, keyPair.Q) keyPair.verify(hash, signature) })) }) }) })
mit
eapearson/kbase-ui-plugin-vis-widgets
src/plugin/modules/GeneDistribution.js
7796
define('GeneDistribution', [ 'jquery', 'd3', 'kb_vis_visWidget', ], function ( $, d3) { $.KBWidget({ name: 'GeneDistribution', parent: 'kbaseVisWidget', version: '1.0.0', options: { xScaleType: 'ordinal', overColor: 'yellow', strokeWidth: '2', xGutter: 0, yGutter: 0, xPadding: 0, yPadding: 0, debug: false, colorScale: function (idx) { var c1 = d3.scale.category20(); var c2 = d3.scale.category20b(); var c3 = d3.scale.category20c(); return function (idx) { if (idx < 20 || idx >= 60) { var color = c1(idx % 20) return color; } else if (idx < 40) { return c2(idx % 20) } else if (idx < 60) { return c3(idx % 20) } } }, inset: 5, colorDomain: [0, 100], transitionTime: 200, }, _accessors: [ ], binColorScale: function (data, maxColor) { var max = 0; data.forEach( function (bin, idx) { if (bin.results) { if (bin.results.count > max) { max = bin.results.count; } } } ); return d3.scale.linear() .domain([0, max]) .range(['#FFFFFF', maxColor]); }, renderXAxis: function () {}, renderYAxis: function () {}, domain: function (data) { var start = 1000000; var end = -1000000; for (var i = 0; i < data.length; i++) { if (data[i].end > end) { end = data[i].end; } if (data[i].start < start) { start = data[i].start; } } return [start, end]; }, regionDomain: function (data) { var length = 0; var lastVal = { end: 0 } data.forEach( function (val, idx) { length += val.size; val.start = lastVal.end; val.end = val.start + val.size; lastVal = val; } ); return [0, length]; }, renderChart: function () { if (this.dataset() == undefined) { return; } var bounds = this.chartBounds(); var regionDomain = this.regionDomain(this.dataset()); var scale = d3.scale.linear() .domain(regionDomain) .range([0, bounds.size.width]); var $gd = this; var mouseAction = function (d, i) { this.on('mouseover', function (b, j) { if ($gd.options.tooltip) { $gd.options.tooltip(b); } else if (b.start && b.regionObj.name) { var score = b.results ? b.results.count : 0; if (score) { $gd.showToolTip({ label: 'bin starting at : ' + b.start + ' for ' + b.regionObj.name + ' score is ' + score }) } } }) .on('mouseout', function (b, j) { $gd.hideToolTip(); }); return this; } var bins = []; this.dataset().forEach( function (region, idx) { region._bins.forEach( function (bin, idx) { bin.regionObj = region; bins.push(bin); } ); } ); var transitionTime = this.initialized ? this.options.transitionTime : 0; var regionsSelection = this.D3svg().select(this.region('chart')).selectAll('.regions').data([0]); regionsSelection.enter().append('g').attr('class', 'regions'); var regionSelection = regionsSelection.selectAll('.region').data(this.dataset(), function (d) { return d.name; }); regionSelection .enter() .append('rect') .attr('class', 'region') .attr('opacity', 0) // .attr('transform', function (d) {return "translate(" + scale(d.start) + ",0)"}) .attr('x', bounds.size.width) .attr('y', 0) .attr('width', 0) .attr('height', bounds.size.height); regionSelection .call(function (d) { return mouseAction.call(this, d); }) .transition() .duration(transitionTime) .attr('opacity', 1) .attr('x', function (d) { return scale(d.start); }) .attr('width', function (d) { return scale((d.size)); }) .attr('fill', function (d, i) { var colorScale = d3.scale.linear().domain([0, 1]).range(['#FFFFFF', $gd.colorForRegion(d.name)]) return colorScale(0.25); }); regionSelection .exit() .transition() .duration(transitionTime) .attr('opacity', 0) .attr('x', bounds.size.width + 1) .attr('width', 0) .each('end', function (d) { d3.select(this).remove(); }); var binsSelection = this.D3svg().select(this.region('chart')).selectAll('.bins').data([0]); binsSelection.enter().append('g').attr('class', 'bins'); var binSelection = binsSelection.selectAll('.bin').data(bins); binSelection .enter() .append('rect') .attr('class', 'bin') .attr('opacity', 0) .attr('x', bounds.size.width) .attr('y', 0) .attr('width', 0) .attr('height', bounds.size.height); binSelection .call(function (d) { return mouseAction.call(this, d); }) .transition() .duration(transitionTime) .attr('opacity', function (d) { return d.results ? 1 : 0; }) .attr('x', function (d) { return scale(d.start + d.regionObj.start); }) .attr('width', function (d) { return scale((d.end - d.start)); }) .attr('fill', function (d, i) { return $gd.colorForRegion(d.region); }); binSelection .exit() .transition() .duration(transitionTime) .attr('opacity', 0) .attr('x', bounds.size.width + 1) .attr('width', 0) .each('end', function (d) { d3.select(this).remove(); }); this.initialized = true; }, colorForRegion: function (region, colorScale) { var map = this.regionColors; if (map == undefined) { map = this.regionColors = { colorScale: this.options.colorScale() }; } if (map[region] == undefined) { map[region] = map.colorScale(d3.keys(map).length); } return map[region]; }, }); });
mit
science09/SpringBootDemo
src/main/java/com/example/service/UserService.java
1240
package com.example.service; import com.example.dao.UserMapper; import com.example.entity.User; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; /** * Created by hadoop on 16-12-21. * UserService 实现 UserDetailsService 接口 */ @Service public class UserService implements UserDetailsService { private Logger logger = Logger.getLogger(UserService.class); @Autowired private UserMapper userMapper; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { logger.info("loadUserByUserName"); User user = userMapper.selectByUsername(username); if (user == null ) { logger.error("user is null"); throw new UsernameNotFoundException(String.format("User with username=%s was not found", username)); } logger.info(user.getUsername() + "---->" + user.getPassword()); return user; } }
mit
thl/mms_engine
db/migrate/20081001180931_add_exif_tag_to_capture_device_maker_and_model.rb
338
class AddExifTagToCaptureDeviceMakerAndModel < ActiveRecord::Migration def self.up add_column :capture_device_makers, :exif_tag, :string add_column :capture_device_models, :exif_tag, :string end def self.down remove_column :capture_device_makers, :exif_tag remove_column :capture_device_models, :exif_tag end end
mit
sebradloff/movie-surfer
src/index.js
691
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; import App from './App'; import DiscoverContainer from './discover/DiscoverContainer'; import DetailedMovieCardContainer from './movie/DetailedMovieCardContainer'; import PageNotFound from './common/pageNotFound/PageNotFound'; ReactDOM.render(( <Router history={browserHistory}> <Route path="/" component={App}> <IndexRoute component={DiscoverContainer} /> <Route path="/movies/:id" component={DetailedMovieCardContainer} /> <Route path="*" component={PageNotFound} /> </Route> </Router> ), document.getElementById('App'));
mit
ebookr/ebookr-status
test/when-supplying-url.js
438
var expect = require('chai').expect; describe('When supplying url', function () { var ebookr; beforeEach(function () { ebookr = require('ebookr').new(); require('../lib/status')(ebookr); ebookr.metadata.set('status', { 1: 'foo', url: 'http://test.com/#' }); }); it('should return rendered text', function () { expect(ebookr.parse('<status state="1" />').render()).to.equal('[foo (1)](http://test.com/#1)'); }); });
mit
ruippeixotog/functional-brodal-queues
src/main/scala/net/ruippeixotog/structs/Benchmark.scala
3055
package net.ruippeixotog.structs import compat.Platform._ import scala.math._ import util.Random import Complexity._ object Complexity { val const = { _: Int => 1.0 } val logN = { n: Int => log(n) } val linear = { n: Int => n } val nLogN = { n: Int => n * log(n) } def complexityTest(durations: Map[Int, Long], T: Int => Double): Seq[Double] = durations.toSeq.sortBy(_._1).map { case(n, dur) => dur / T(n) } } object Benchmark extends App { val factory = QueueBootstrap.Factory[SkewBinomialQueue] val outerSample = 100 val innerSample = 100000 def withBenchmark[T](text: => String)(f: => T): Long = { val start = currentTime f val duration = currentTime - start println(text + ": " + duration + " ms") duration } val results = (1 to outerSample).foldLeft(Map[Int, Map[Symbol, Seq[Long]]]()) { (acc, run) => (1 to 7).foldLeft(acc) { (acc, order) => val nElems = pow(10, order).toInt println("Starting run %d, %d elements".format(run, nElems)) collectGarbage() val elems = (1 to nElems).map { _ => Random.nextInt() } val queue = factory.create[Int](elems: _*) val newElems = (1 to innerSample).map { _ => Random.nextInt() } val insertRes = withBenchmark("insert") { newElems.map { x => queue.insert(x) } } val minRes = withBenchmark("min") { (1 to innerSample).foreach { _ => queue.min } } val deleteRes = withBenchmark("deleteMin") { (1 to innerSample).foreach { _ => queue.withoutMin } } val bq2 = factory.create(elems: _*) val meldRes = withBenchmark("meld") { (1 to innerSample).foreach { _ => queue.meld(bq2) } } val orderRes = acc.getOrElse(nElems, Map()) val newOrderRes = orderRes + ('insert -> (orderRes.getOrElse('insert, Seq[Long]()) :+ insertRes)) + ('min -> (orderRes.getOrElse('min, Seq[Long]()) :+ minRes)) + ('delete -> (orderRes.getOrElse('delete, Seq[Long]()) :+ deleteRes)) + ('meld -> (orderRes.getOrElse('meld, Seq[Long]()) :+ meldRes)) acc + (nElems -> newOrderRes) } } val avgResults = results.mapValues { _.mapValues{ _.sum / outerSample }} println() println("----- Results -----") println("Note: the values shown here are for each %d operations".format(innerSample)) for { (nElems, m) <- avgResults (op, res) <- m } println("Queue with %d elements, %s: %d ms".format(nElems, op, res)) println() println("----- Complexity tests -----") val resultsByOp = (for { (nElems, m) <- avgResults (op, res) <- m } yield (op, nElems, res)).groupBy(_._1).mapValues(_.map(p => (p._2, p._3)).toMap) println("Ratios for insert: " + complexityTest(resultsByOp('insert), const).mkString(",")) println("Ratios for min: " + complexityTest(resultsByOp('min), const).mkString(",")) println("Ratios for delete: " + complexityTest(resultsByOp('delete), logN).mkString(",")) println("Ratios for meld: " + complexityTest(resultsByOp('meld), const).mkString(",")) }
mit
zulip/zulip-js
test/resources/events.js
1076
const chai = require('chai'); const events = require('../../lib/resources/events'); const common = require('../common'); chai.should(); describe('Events', () => { it('should fetch events', async () => { const params = { last_event_id: -1, dont_block: true, }; const validator = (url, options) => { url.should.contain(`${common.config.apiURL}/events`); options.method.should.be.equal('GET'); options.should.not.have.property('body'); [...new URL(url).searchParams].should.have.deep.members([ ['last_event_id', `${params.last_event_id}`], ['dont_block', `${params.dont_block}`], ]); }; const output = { events: [ { id: 0, message: [Object], type: 'message', flags: [Object], }, ], result: 'success', msg: '', queue_id: '1511901550:3', }; common.stubNetwork(validator, output); const data = await events(common.config).retrieve(params); data.should.have.property('result', 'success'); }); });
mit
EscherLabs/Graphene
public/assets/js/vendor/vs/basic-languages/solidity/solidity.contribution.js
991
define(["require", "exports", "../_.contribution"], function (require, exports, __contribution_1) { /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // Allow for running under nodejs/requirejs in tests var _monaco = (typeof monaco === 'undefined' ? self.monaco : monaco); __contribution_1.registerLanguage({ id: 'sol', extensions: ['.sol'], aliases: ['sol', 'solidity', 'Solidity'], loader: function () { return _monaco.Promise.wrap(new Promise(function (resolve_1, reject_1) { require(['./solidity'], resolve_1, reject_1); })); } }); });
mit
var-bin/reactjs-training
es2015/get-users-avatars.js
248
"use strict"; function getUsersAvatars(userNames, cb) { let url = "/userAvatars"; for (let index in userNames) { _fetchAvatar(url + userNames[index], function (avatarUrl) { _displayAvatar(userNames[index], avatarUrl); }) } }
mit
lokielse/omnipay-global-alipay
src/Message/WebPurchaseRequest.php
8926
<?php namespace Omnipay\GlobalAlipay\Message; use Omnipay\Common\Exception\InvalidRequestException; use Omnipay\Common\Message\AbstractRequest; use Omnipay\Common\Message\ResponseInterface; use Omnipay\GlobalAlipay\Common\Signer; use Omnipay\GlobalAlipay\Helper; class WebPurchaseRequest extends AbstractRequest { /** * Get the raw data array for this message. The format of this varies from gateway to * gateway, but will usually be either an associative array, or a SimpleXMLElement. * @return mixed * @throws InvalidRequestException */ public function getData() { $this->validate( 'key', 'partner', 'notify_url', 'subject', 'out_trade_no' ); if ($this->getTotalFee() && $this->getRmbFee()) { throw new InvalidRequestException("The 'total_fee' and 'rmb_fee' parameter can not be provide together"); } if (! $this->getTotalFee() && ! $this->getRmbFee()) { throw new InvalidRequestException("The 'total_fee' and 'rmb_fee' must be provide one of them"); } $data = array( 'service' => 'create_forex_trade', 'partner' => $this->getPartner(), 'notify_url' => $this->getNotifyUrl(), 'return_url' => $this->getReturnUrl(),//<> 'sign_type' => $this->getSignType() ?: 'MD5', 'subject' => $this->getSubject(), '_input_charset' => $this->getInputCharset() ?: 'utf-8',//<> 'body' => $this->getBody(),//<> 'out_trade_no' => $this->getOutTradeNo(), 'currency' => $this->getCurrency() ?: 'USD', 'total_fee' => $this->getTotalFee(), 'rmb_fee' => $this->getRmbFee(),//<> 'supplier' => $this->getSupplier(),//<> 'order_gmt_create' => $this->getOrderGmtCreate(),//<> 'order_valid_time' => $this->getOrderValidTime(),//<> 'timeout_rule' => $this->getTimeoutRule(),//<> 'specified_pay_channel' => $this->getSpecifiedPayChannel(),//<> 'seller_id' => $this->getSellerId(),//<> 'seller_name' => $this->getSellerIndustry(),//<> 'split_fund_info' => $this->getSplitFundInfo(), 'product_code' => $this->getProductCode() ?: 'NEW_OVERSEAS_SELLER', ); $data = array_filter($data); $data['sign'] = $this->sign($data, $data['sign_type']); return $data; } /** * Send the request with specified data * * @param mixed $data The data to send * * @return ResponseInterface */ public function sendData($data) { $responseData = array(); return $this->response = new WebPurchaseResponse($this, $responseData); } public function getKey() { return $this->getParameter('key'); } public function setKey($value) { return $this->setParameter('key', $value); } public function getPrivateKey() { return $this->getParameter('private_key'); } public function setPrivateKey($value) { return $this->setParameter('private_key', $value); } public function getPartner() { return $this->getParameter('partner'); } public function setPartner($value) { return $this->setParameter('partner', $value); } public function getNotifyUrl() { return $this->getParameter('notify_url'); } public function setNotifyUrl($value) { return $this->setParameter('notify_url', $value); } public function getReturnUrl() { return $this->getParameter('return_url'); } public function setReturnUrl($value) { return $this->setParameter('return_url', $value); } public function getSignType() { return $this->getParameter('sign_type'); } public function setSignType($value) { return $this->setParameter('sign_type', $value); } public function getSubject() { return $this->getParameter('subject'); } public function setSubject($value) { return $this->setParameter('subject', $value); } public function getInputCharset() { return $this->getParameter('input_charset'); } public function setInputCharset($value) { return $this->setParameter('input_charset', $value); } public function getBody() { return $this->getParameter('body'); } public function setBody($value) { return $this->setParameter('body', $value); } public function getOutTradeNo() { return $this->getParameter('out_trade_no'); } public function setOutTradeNo($value) { return $this->setParameter('out_trade_no', $value); } public function getTotalFee() { return $this->getParameter('total_fee'); } public function setTotalFee($value) { return $this->setParameter('total_fee', $value); } public function getRmbFee() { return $this->getParameter('rmb_fee'); } public function setRmbFee($value) { return $this->setParameter('rmb_fee', $value); } public function getSupplier() { return $this->getParameter('supplier'); } public function setSupplier($value) { return $this->setParameter('supplier', $value); } public function getOrderGmtCreate() { return $this->getParameter('order_gmt_create'); } /** * @param string $value YYYY-MM-DD HH:MM:SS * * @return AbstractRequest */ public function setOrderGmtCreate($value) { return $this->setParameter('order_gmt_create', $value); } public function getOrderValidTime() { return $this->getParameter('order_valid_time'); } /** * @param int $value second (max=21600) * * @return AbstractRequest */ public function setOrderValidTime($value) { return $this->setParameter('order_valid_time', $value); } public function getTimeoutRule() { return $this->getParameter('timeout_rule'); } /** * @param $value 5m 10m 15m 30m 1h 2h 3h 5h 10h 12h(default) * * @return AbstractRequest */ public function setTimeoutRule($value) { return $this->setParameter('timeout_rule', $value); } public function getSpecifiedPayChannel() { return $this->getParameter('specified_pay_channel'); } public function setSpecifiedPayChannel($value) { return $this->setParameter('specified_pay_channel', $value); } public function getSellerId() { return $this->getParameter('seller_id'); } public function setSellerId($value) { return $this->setParameter('seller_id', $value); } public function getSellerName() { return $this->getParameter('seller_name'); } public function setSellerName($value) { return $this->setParameter('seller_name', $value); } public function getSellerIndustry() { return $this->getParameter('seller_industry'); } public function setSellerIndustry($value) { return $this->setParameter('seller_industry', $value); } public function getEnvironment() { return $this->getParameter('environment'); } public function setEnvironment($value) { return $this->setParameter('environment', $value); } public function getSplitFundInfo() { return $this->getParameter('split_fund_info'); } public function setSplitFundInfo(array $value = array()) { return $this->setParameter('split_fund_info', json_encode($value)); } public function getProductCode() { return $this->getParameter('product_code'); } public function setProductCode($value) { return $this->setParameter('product_code', $value); } protected function sign($params, $signType) { $signer = new Signer($params); $signType = strtoupper($signType); if ($signType == 'RSA') { $sign = $signer->signWithRSA($this->getPrivateKey()); } elseif ($signType == 'RSA2') { $sign = $signer->signWithRSA($this->getPrivateKey(), OPENSSL_ALGO_SHA256); } elseif ($signType == 'MD5') { $sign = $signer->signWithMD5($this->getKey()); } else { throw new InvalidRequestException('The signType is invalid'); } return $sign; } }
mit
jrochkind/blacklight_facet_browse
lib/blacklight_facet_browse/version.rb
53
module BlacklightFacetBrowse VERSION = "0.0.1" end
mit
overblog/recurly-client-php
lib/Recurly/Invoice.php
1947
<?php namespace Recurly; class Invoice extends Resource { protected static $_writeableAttributes; protected static $_nestedAttributes; public static function init() { Invoice::$_writeableAttributes = array(); Invoice::$_nestedAttributes = array('account','line_items','transactions'); } /** * Lookup an invoice by its ID * @param string Invoice number or UUID * @return Invoice invoice */ public static function get($invoiceNumber, $client = null) { $uri = Client::PATH_INVOICES . '/' . rawurlencode($invoiceNumber); return self::_get($uri, $client); } /** * Retrieve the PDF version of this invoice */ public function getPdf($locale = null) { return Invoice::getInvoicePdf($this->invoice_number, $locale, $this->_client); } /** * Retrieve the PDF version of an invoice */ public static function getInvoicePdf($invoiceNumber, $locale = null, $client = null) { $uri = Client::PATH_INVOICES . '/' . rawurlencode($invoiceNumber); if (is_null($client)) $client = new Client(); return $client->getPdf($uri, $locale); } /** * Creates an invoice for an account using its pending charges * @param string Unique account code * @return Invoice invoice on success */ public static function invoicePendingCharges($accountCode, $client = null) { $uri = Client::PATH_ACCOUNTS . '/' . rawurlencode($accountCode) . Client::PATH_INVOICES; return self::_post($uri, null, $client); } public function markSuccessful() { $this->_save(Client::PUT, $this->uri() . '/mark_successful'); } public function markFailed() { $this->_save(Client::PUT, $this->uri() . '/mark_failed'); } protected function getNodeName() { return 'invoice'; } protected function getWriteableAttributes() { return Invoice::$_writeableAttributes; } protected function getRequiredAttributes() { return array(); } } Invoice::init();
mit
BigEggTools/ConsoleExtension
ConsoleExtension/Parameters/Errors/ErrorType.cs
2202
namespace BigEgg.Tools.ConsoleExtension.Parameters.Errors { /// <summary> /// The enumeration of error types /// </summary> internal enum ErrorType { /// <summary> /// User request the help. /// </summary> HelpRequest, /// <summary> /// User request the help on command. /// </summary> CommandHelpRequest, /// <summary> /// User request the version info. /// </summary> VersionRequest, /// <summary> /// User input duplicate property /// </summary> DuplicateArgument, /// <summary> /// User input nothing /// </summary> EmptyInput, /// <summary> /// User input unknown command /// </summary> UnknownCommand, /// <summary> /// User not input the specific command /// </summary> MissingCommand, /// <summary> /// User not input the request property /// </summary> MissingRequestProperty, /// <summary> /// Developer used a type as command which don't have command attribute /// </summary> Develop_MissingCommand, /// <summary> /// Developer used a type as command which have invalid command attribute /// </summary> Develop_InvalidCommand, /// <summary> /// Developer mark 2 command as same name /// </summary> Develop_DuplicateCommand, /// <summary> /// Developer used a type as command which have invalid property attribute /// </summary> Develop_InvalidProperty, /// <summary> /// Developer used a type as command which have property attribute mismatch with the property type /// </summary> Develop_PropertyTypeMismatch, /// <summary> /// Developer used a type as command which have property attribute cannot write /// </summary> Develop_PropertyTypeCannotWrite, /// <summary> /// Developer used a type as command which have duplicate property name /// </summary> Develop_DuplicateProperty } }
mit
cwgem/Random-Ruby-Code
singleton_method.rb
92
myobject = "test" def myobject.mymethod puts "Hello World" end myobject.send(:mymethod)
mit
Undev/libftdi-ruby
lib/ftdi.rb
15555
require 'ffi' require "ftdi/version" # Represents libftdi ruby bindings. # End-user API represented by {Ftdi::Context} class. module Ftdi extend FFI::Library ffi_lib ["libftdi", "libftdi.so.1"] # FTDI chip type. ChipType = enum(:type_am, :type_bm, :type_2232c, :type_r, :type_2232h, :type_4232h, :type_232h) # Automatic loading / unloading of kernel modules. ModuleDetachMode = enum(:auto_detach_sio_module, :dont_detach_sio_module) # Number of bits for {Ftdi::Context#set_line_property}. BitsType = enum( :bits_7, 7, :bits_8, 8 ) # Number of stop bits for {Ftdi::Context#set_line_property}. StopbitsType = enum( :stop_bit_1, 0, :stop_bit_15, 1, :stop_bit_2, 2 ) # Parity mode for {Ftdi::Context#set_line_property}. ParityType = enum(:none, :odd, :even, :mark, :space) # Break type for {Ftdi::Context#set_line_property2}. BreakType = enum(:break_off, :break_on) # Port interface for chips with multiple interfaces. # @see Ftdi::Context#interface= Interface = enum(:interface_any, :interface_a, :interface_b, :interface_c, :interface_d) # Bitbang mode for {Ftdi::Context#set_bitmode}. BitbangMode = enum(:reset, :bitbang, :mpsse, :syncbb, :mcu, :opto, :cbus, :syncff) # Flow control: disable # @see Ftdi::Context#flowctrl= SIO_DISABLE_FLOW_CTRL = 0x0 # @see Ftdi::Context#flowctrl= SIO_RTS_CTS_HS = (0x1 << 8) # @see Ftdi::Context#flowctrl= SIO_DTR_DSR_HS = (0x2 << 8) # @see Ftdi::Context#flowctrl= SIO_XON_XOFF_HS = (0x4 << 8) # Base error of libftdi. class Error < RuntimeError; end # Represents initialization error of libftdi. class CannotInitializeContextError < Error; end # Represents error of libftdi with its status code. class StatusCodeError < Error # Gets status code. # @return [Fixnum] Status code. attr_reader :status_code def initialize(status_code, message) super(message) @status_code = status_code end # Gets string representation of the error. # @return [String] Representation of the error. def to_s "#{status_code}: #{super}" end end # Represents libftdi context and end-user API. # @example Open USB device # ctx = Ftdi::Context.new # begin # ctx.usb_open(0x0403, 0x6001) # begin # ctx.baudrate = 250000 # ensure # ctx.usb_close # end # rescue Ftdi::Error => e # $stderr.puts e.to_s # end class Context < FFI::ManagedStruct layout( # libusb's usb_dev_handle :usb_dev, :pointer, # usb read timeout :usb_read_timeout, :int, # usb write timeout :usb_write_timeout, :int, # FTDI specific # FTDI chip type :type, Ftdi::ChipType, # baudrate :baudrate, :int, # bitbang mode state :bitbang_enabled, :uint8, # pointer to read buffer for ftdi_read_data :readbuffer, :pointer, # read buffer offset :readbuffer_offset, :uint, # number of remaining data in internal read buffer :readbuffer_remaining, :uint, # read buffer chunk size :readbuffer_chunksize, :uint, # write buffer chunk size :writebuffer_chunksize, :uint, # maximum packet size. Needed for filtering modem status bytes every n packets. :max_packet_size, :uint, # FTDI FT2232C requirements # FT2232C interface number: 0 or 1 :interface, :int, # 0 or 1 # FT2232C index number: 1 or 2 :index, :int, # 1 or 2 # Endpoints # FT2232C end points: 1 or 2 :in_ep, :int, :out_ep, :int, # 1 or 2 # Bitbang mode. 1: (default) Normal bitbang mode, 2: FT2232C SPI bitbang mode :bitbang_mode, :uint8, # Decoded eeprom structure :eeprom, :int, # String representation of last error :error_str, :string, # Buffer needed for async communication :async_usb_buffer, :pointer, # Number of URB-structures we can buffer :async_usb_buffer_size, :uint, # Defines behavior in case a kernel module is already attached to the device :module_detach_mode, Ftdi::ModuleDetachMode ) # Initializes new libftdi context. # @raise [CannotInitializeContextError] libftdi cannot be initialized. def initialize ptr = Ftdi.ftdi_new raise CannotInitializeContextError.new if ptr.nil? super(ptr) end # Deinitialize and free an ftdi context. # @return [NilClass] nil def self.release(p) Ftdi.ftdi_free(p) nil end # Gets error text. # @return [String] Error text. def error_string self[:error_str] end # Opens the first device with a given vendor and product ids. # @param [Fixnum] vendor Vendor id. # @param [Fixnum] product Product id. # @return [NilClass] nil # @raise [StatusCodeError] libftdi reports error. # @raise [ArgumentError] Bad arguments. def usb_open(vendor, product) raise ArgumentError.new('vendor should be Fixnum') unless vendor.kind_of?(Fixnum) raise ArgumentError.new('product should be Fixnum') unless product.kind_of?(Fixnum) check_result(Ftdi.ftdi_usb_open(ctx, vendor, product)) end # Opens the first device with a given vendor and product ids, description and serial. # @param [Fixnum] vendor Vendor id. # @param [Fixnum] product Product id. # @param [String] description Description to search for. Use nil if not needed. # @param [String] serial Serial to search for. Use nil if not needed. # @return [NilClass] nil # @raise [StatusCodeError] libftdi reports error. # @raise [ArgumentError] Bad arguments. def usb_open_desc(vendor, product, description, serial) raise ArgumentError.new('vendor should be Fixnum') unless vendor.kind_of?(Fixnum) raise ArgumentError.new('product should be Fixnum') unless product.kind_of?(Fixnum) check_result(Ftdi.ftdi_usb_open_desc(ctx, vendor, product, description, serial)) end # Opens the index-th device with a given vendor and product ids, description and serial. # @param [Fixnum] vendor Vendor id. # @param [Fixnum] product Product id. # @param [String] description Description to search for. Use nil if not needed. # @param [String] serial Serial to search for. Use nil if not needed. # @param [Fixnum] index Number of matching device to open if there are more than one, starts with 0. # @return [NilClass] nil # @raise [StatusCodeError] libftdi reports error. # @raise [ArgumentError] Bad arguments. def usb_open_desc_index(vendor, product, description, serial, index) raise ArgumentError.new('vendor should be Fixnum') unless vendor.kind_of?(Fixnum) raise ArgumentError.new('product should be Fixnum') unless product.kind_of?(Fixnum) raise ArgumentError.new('index should be Fixnum') unless index.kind_of?(Fixnum) raise ArgumentError.new('index should be greater than or equal to zero') if index < 0 check_result(Ftdi.ftdi_usb_open_desc_index(ctx, vendor, product, description, serial, index)) end # Resets the ftdi device. # @raise [StatusCodeError] libftdi reports error. # @return [NilClass] nil def usb_reset check_result(Ftdi.ftdi_usb_reset(ctx)) end # Closes the ftdi device. # @return [NilClass] nil def usb_close Ftdi.ftdi_usb_close(ctx) nil end # Gets the chip baud rate. # @return [Fixnum] Baud rate. def baudrate self[:baudrate] end # Sets the chip baud rate. # @raise [StatusCodeError] libftdi reports error. # @raise [ArgumentError] Bad arguments. # @return [NilClass] nil def baudrate=(new_baudrate) raise ArgumentError.new('baudrate should be Fixnum') unless new_baudrate.kind_of?(Fixnum) check_result(Ftdi.ftdi_set_baudrate(ctx, new_baudrate)) end # Set (RS232) line characteristics. # The break type can only be set via {#set_line_property2} and defaults to "off". # @param [BitsType] bits # @param [StopbitsType] stopbits # @param [ParityType] parity # @raise [StatusCodeError] libftdi reports error. # @return [NilClass] nil def set_line_property(bits, stopbits, parity) check_result(Ftdi.ftdi_set_line_property(ctx, bits, stopbits, parity)) end # Set (RS232) line characteristics. # @param [BitsType] bits # @param [StopbitsType] stopbits # @param [ParityType] parity # @param [BreakType] _break # @raise [StatusCodeError] libftdi reports error. # @return [NilClass] nil def set_line_property2(bits, stopbits, parity, _break) check_result(Ftdi.ftdi_set_line_property2(ctx, bits, stopbits, parity, _break)) end # Set flow control setting for ftdi chip. # @param [Fixnum] new_flowctrl New flow control setting. # @raise [StatusCodeError] libftdi reports error. # @return [Fixnum] New flow control setting. # @see SIO_DISABLE_FLOW_CTRL # @see SIO_RTS_CTS_HS # @see SIO_DTR_DSR_HS # @see SIO_XON_XOFF_HS def flowctrl=(new_flowctrl) check_result(Ftdi.ftdi_setflowctrl(ctx, new_flowctrl)) new_flowctrl end # Set Bitbang mode for ftdi chip. # @param [Fixnum] bitmask to configure lines. HIGH/ON value configures a line as output. # @param [BitbangMode] mode Bitbang mode: use the values defined in {Ftdi::Context#BitbangMode} # @return [NilClass] nil # @see BitbangMode def set_bitmode(bitmask, mode) check_result(Ftdi.ftdi_set_bitmode(ctx, bitmask, mode)) end # Gets write buffer chunk size. # @return [Fixnum] Write buffer chunk size. # @raise [StatusCodeError] libftdi reports error. # @see #write_data_chunksize= def write_data_chunksize p = FFI::MemoryPointer.new(:uint, 1) check_result(Ftdi.ftdi_write_data_get_chunksize(ctx, p)) p.read_uint end # Configure write buffer chunk size. # Automatically reallocates the buffer. # @note Default is 4096. # @param [Fixnum] new_chunksize Write buffer chunk size. # @return [Fixnum] New write buffer chunk size. # @raise [StatusCodeError] libftdi reports error. def write_data_chunksize=(new_chunksize) check_result(Ftdi.ftdi_write_data_set_chunksize(ctx, new_chunksize)) new_chunksize end # Writes data. # @param [String, Array] bytes String or array of integers that will be interpreted as bytes using pack('c*'). # @return [Fixnum] Number of written bytes. # @raise [StatusCodeError] libftdi reports error. def write_data(bytes) bytes = bytes.pack('c*') if bytes.respond_to?(:pack) size = bytes.respond_to?(:bytesize) ? bytes.bytesize : bytes.size mem_buf = FFI::MemoryPointer.new(:char, size) mem_buf.put_bytes(0, bytes) bytes_written = Ftdi.ftdi_write_data(ctx, mem_buf, size) check_result(bytes_written) bytes_written end # Gets read buffer chunk size. # @return [Fixnum] Read buffer chunk size. # @raise [StatusCodeError] libftdi reports error. # @see #read_data_chunksize= def read_data_chunksize p = FFI::MemoryPointer.new(:uint, 1) check_result(Ftdi.ftdi_read_data_get_chunksize(ctx, p)) p.read_uint end # Configure read buffer chunk size. # Automatically reallocates the buffer. # @note Default is 4096. # @param [Fixnum] new_chunksize Read buffer chunk size. # @return [Fixnum] New read buffer chunk size. # @raise [StatusCodeError] libftdi reports error. def read_data_chunksize=(new_chunksize) check_result(Ftdi.ftdi_read_data_set_chunksize(ctx, new_chunksize)) new_chunksize end # Reads data in chunks from the chip. # Returns when at least one byte is available or when the latency timer has elapsed. # Automatically strips the two modem status bytes transfered during every read. # @return [String] Bytes read; Empty string if no bytes read. # @see #read_data_chunksize # @raise [StatusCodeError] libftdi reports error. def read_data chunksize = read_data_chunksize p = FFI::MemoryPointer.new(:char, chunksize) bytes_read = Ftdi.ftdi_read_data(ctx, p, chunksize) check_result(bytes_read) r = p.read_bytes(bytes_read) r.force_encoding("ASCII-8BIT") if r.respond_to?(:force_encoding) r end # Directly read pin state, circumventing the read buffer. Useful for bitbang mode. # @return [Fixnum] Pins state # @raise [StatusCodeError] libftdi reports error. # @see #set_bitmode def read_pins p = FFI::MemoryPointer.new(:uchar, 1) check_result(Ftdi.ftdi_read_pins(ctx, p)) p.read_uchar end # Gets used interface of the device. # @return [Interface] Used interface of the device. def interface Interface[self[:interface]] end # Open selected channels on a chip, otherwise use first channel. # @param [Interface] new_interface Interface to use for FT2232C/2232H/4232H chips. # @raise [StatusCodeError] libftdi reports error. # @return [Interface] New interface. def interface=(new_interface) check_result(Ftdi.ftdi_set_interface(ctx, new_interface)) new_interface end # Set the DTR control line value. # @param [Fixnum] value Either 0 or 1 # @raise [StatusCodeError] libftdi reports error. # @return [Fixnum] The value def dtr=(value) check_result(Ftdi.ftdi_setdtr(ctx, value)) value end # Set the RTS control line value. # @param [Fixnum] value Either 0 or 1 # @raise [StatusCodeError] libftdi reports error. # @return [Fixnum] The value def rts=(value) check_result(Ftdi.ftdi_setrts(ctx, value)) value end private def ctx self.to_ptr end def check_result(status_code) if status_code < 0 raise StatusCodeError.new(status_code, error_string) end nil end end attach_function :ftdi_new, [ ], :pointer attach_function :ftdi_free, [ :pointer ], :void attach_function :ftdi_usb_open, [ :pointer, :int, :int ], :int attach_function :ftdi_usb_open_desc, [ :pointer, :int, :int, :string, :string ], :int attach_function :ftdi_usb_open_desc_index, [ :pointer, :int, :int, :string, :string, :uint ], :int attach_function :ftdi_usb_reset, [ :pointer ], :int attach_function :ftdi_usb_close, [ :pointer ], :void attach_function :ftdi_set_baudrate, [ :pointer, :int ], :int attach_function :ftdi_set_line_property, [ :pointer, BitsType, StopbitsType, ParityType ], :int attach_function :ftdi_set_line_property2, [ :pointer, BitsType, StopbitsType, ParityType, BreakType ], :int attach_function :ftdi_setflowctrl, [ :pointer, :int ], :int attach_function :ftdi_write_data, [ :pointer, :pointer, :int ], :int attach_function :ftdi_write_data_set_chunksize, [ :pointer, :uint ], :int attach_function :ftdi_write_data_get_chunksize, [ :pointer, :pointer ], :int attach_function :ftdi_read_data, [ :pointer, :pointer, :int ], :int attach_function :ftdi_read_data_set_chunksize, [ :pointer, :uint ], :int attach_function :ftdi_read_data_get_chunksize, [ :pointer, :pointer ], :int attach_function :ftdi_set_interface, [ :pointer, Interface ], :int attach_function :ftdi_set_bitmode, [ :pointer, :int, :int ], :int attach_function :ftdi_read_pins, [ :pointer, :pointer ], :int attach_function :ftdi_setdtr, [ :pointer, :int ], :int attach_function :ftdi_setrts, [ :pointer, :int ], :int end
mit
Azure/azure-sdk-for-ruby
management/azure_mgmt_network/lib/2017-10-01/generated/azure_mgmt_network/models/network_interface_association.rb
1914
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Network::Mgmt::V2017_10_01 module Models # # Network interface and its custom security rules. # class NetworkInterfaceAssociation include MsRestAzure # @return [String] Network interface ID. attr_accessor :id # @return [Array<SecurityRule>] Collection of custom security rules. attr_accessor :security_rules # # Mapper for NetworkInterfaceAssociation class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'NetworkInterfaceAssociation', type: { name: 'Composite', class_name: 'NetworkInterfaceAssociation', model_properties: { id: { client_side_validation: true, required: false, read_only: true, serialized_name: 'id', type: { name: 'String' } }, security_rules: { client_side_validation: true, required: false, serialized_name: 'securityRules', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'SecurityRuleElementType', type: { name: 'Composite', class_name: 'SecurityRule' } } } } } } } end end end end
mit
Microsoft/vso-httpclient-java
Rest/alm-tfs-client/src/main/generated/com/microsoft/alm/teamfoundation/testmanagement/webapi/TestFailuresAnalysis.java
1711
// @formatter:off /* * --------------------------------------------------------- * Copyright(C) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. See License.txt in the project root. * --------------------------------------------------------- * * --------------------------------------------------------- * Generated file, DO NOT EDIT * --------------------------------------------------------- * * See following wiki page for instructions on how to regenerate: * https://vsowiki.com/index.php?title=Rest_Client_Generation */ package com.microsoft.alm.teamfoundation.testmanagement.webapi; /** */ public class TestFailuresAnalysis { private TestFailureDetails existingFailures; private TestFailureDetails fixedTests; private TestFailureDetails newFailures; private TestResultsContext previousContext; public TestFailureDetails getExistingFailures() { return existingFailures; } public void setExistingFailures(final TestFailureDetails existingFailures) { this.existingFailures = existingFailures; } public TestFailureDetails getFixedTests() { return fixedTests; } public void setFixedTests(final TestFailureDetails fixedTests) { this.fixedTests = fixedTests; } public TestFailureDetails getNewFailures() { return newFailures; } public void setNewFailures(final TestFailureDetails newFailures) { this.newFailures = newFailures; } public TestResultsContext getPreviousContext() { return previousContext; } public void setPreviousContext(final TestResultsContext previousContext) { this.previousContext = previousContext; } }
mit
link78954/NaolisTest
src/Formation/CatBundle/Controller/CatController.php
2171
<?php namespace Formation\CatBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Formation\ModelBundle\Form\CatType; class CatController extends Controller { /** * @Route("/hello/{name}") * @Template() */ public function indexAction($name) { return array('name' => $name); } /** * @Route("/cat/list/{limit}/{offset}/{cat}", defaults={"limit"=5,"offset"=0,"cat"="1"}) * @Template() */ public function listAction($limit, $offset, $cat) { $manager = $this->getDoctrine()->getManager(); $catRepo = $manager->getRepository('FormationModelBundle:Cat'); $listCat = $catRepo->activeCat(); return $this->render('FormationCatBundle:Cat:list.html.twig',array('listCat'=>$listCat)); } /** * @Route("/cat/create") * @Template() */ public function createAction() { $manager = $this->getDoctrine()->getManager(); $catRepo = $manager->getRepository("FormationModelBundle:Cat"); $what = $catRepo->sayHello(); var_dump($what);die; $cat = new \Formation\ModelBundle\Entity\Cat(); $cForm = $this->createForm(new CatType, $cat); if($this->getRequest()->getMethod()=="POST"){ $cForm->bind($this->getRequest()); if($cForm->isValid()){ $manager->persist($cat); foreach ($cat->getArticles() as $article) { $article->addCat($cat); $manager->persist($article); } $manager->flush(); //$this->get('session')->getFlashBag()->add('infos','Enregistrement correctement effectué'); return $this->redirect($this->generateUrl('formation_article_list')); } } return $this->render('FormationCatBundle:Cat:create.html.twig', array('cForm'=>$cForm->createView())); } }
mit
bjornaa/ladim
examples/killer/killer_ibm.py
464
# Minimal IBM to kill old particles DAY = 24 * 60 * 60 # Number of seconds in a day class IBM: def __init__(self, config): print("Initializing killer feature") self.lifetime = config["ibm"]["lifetime"] def update_ibm(self, grid, state, forcing): # Update the particle age state.age += state.dt # Update the age # Mark particles older than 2 days as dead state.alive = state.age < self.lifetime * DAY
mit
phpcr/phpcr-shell
src/PHPCR/Shell/Console/Command/Phpcr/RetentionHoldListCommand.php
1643
<?php /* * This file is part of the PHPCR Shell package * * (c) Daniel Leech <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * */ namespace PHPCR\Shell\Console\Command\Phpcr; use PHPCR\RepositoryInterface; use PHPCR\Shell\Console\Helper\Table; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class RetentionHoldListCommand extends BasePhpcrCommand { protected function configure() { $this->setName('retention:hold:list'); $this->setDescription('List retention holds at given absolute path UNSUPPORTED'); $this->addArgument('absPath', InputArgument::REQUIRED, 'Absolute path to node to which we want to add a hold'); $this->setHelp(<<<'HERE' Lists all hold object names that have been added to the existing node at <info>absPath</info>. HERE ); $this->requiresDescriptor(RepositoryInterface::OPTION_RETENTION_SUPPORTED, true); } public function execute(InputInterface $input, OutputInterface $output) { $session = $this->get('phpcr.session'); $retentionManager = $session->getRetentionManager(); $absPath = $input->getArgument('absPath'); $holds = $retentionManager->getHolds($absPath); $table = new Table($output); $table->setHeaders(['Name']); foreach ($holds as $hold) { $table->addRow([$hold->getName()]); } $table->render($output); return 0; } }
mit
haricm/authserver
config/passport.js
5665
/** * Module dependencies. */ var passport = require('passport') , LocalStrategy = require('passport-local').Strategy , BasicStrategy = require('passport-http').BasicStrategy , ClientPasswordStrategy = require('passport-oauth2-client-password').Strategy , BearerStrategy = require('passport-http-bearer').Strategy , env = process.env.NODE_ENV || 'development' , config = require('./config')[env] , db = require('../app/models'); /** * LocalStrategy * * This strategy is used to authenticate users based on a username and password. * Anytime a request is made to authorize an application, we must ensure that * a user is logged in before asking them to approve the request. */ passport.use(new LocalStrategy( function (username, password, done) { db.user.findOne( {username : username}, function (err, user) { console.log(user); if (err) { return done(err); } if (!user) { return done(null, false); } if (!user.authenticate(password)) { return done(null, false); } return done(null, user); }); } )); passport.serializeUser(function (user, done) { done(null, user.id); }); passport.deserializeUser(function (id, done) { db.user.findOne( {_id : id}, function (err, user) { done(err, user); }); }); /** * * BasicStrategy & ClientPasswordStrategy * * These strategies are used to authenticate registered OAuth clients. They are * employed to protect the `token` endpoint, which consumers use to obtain * access tokens. The OAuth 2.0 specification suggests that clients use the * HTTP Basic scheme to authenticate. Use of the client password strategy * allows clients to send the same credentials in the request body (as opposed * to the `Authorization` header). While this approach is not recommended by * the specification, in practice it is quite common. */ passport.use(new BasicStrategy( function (username, password, done) { console.log("Checking whether its a registered client or not #!"); db.clients.findByClientId(username, function (err, client) { if (err) { return done(err); } if (!client) { return done(null, false); } if (client.clientSecret != password) { return done(null, false); } return done(null, client); }); } )); /** * Client Password strategy * * The OAuth 2.0 client password authentication strategy authenticates clients * using a client ID and client secret. The strategy requires a verify callback, * which accepts those credentials and calls done providing a client. */ passport.use(new ClientPasswordStrategy( function (clientId, clientSecret, done) { console.log("Checking whether its a registered client or not #2"); db.clients.findByClientId(clientId, function (err, client) { if (err) { return done(err); } if (!client) { return done(null, false); } if (client.clientSecret != clientSecret) { return done(null, false); } return done(null, client); }); } )); /** * BearerStrategy * * This strategy is used to authenticate either users or clients based on an access token * (aka a bearer token). If a user, they must have previously authorized a client * application, which is issued an access token to make requests on behalf of * the authorizing user. */ passport.use(new BearerStrategy( function (accessToken, done) { console.log("BearerStrategy"); db.accessTokens.find(accessToken, function (err, token) { if (err) { return done(err); } if (!token) { return done(null, false); } if(new Date() > token.expirationDate) { db.accessTokens.delete(accessToken, function(err) { return done(err); }); } else { if (token.userID != null) { db.user.findOne( {_id : token.userID}, function (err, user) { if (err) { return done(err); } if (!user) { return done(null, false); } // to keep this example simple, restricted scopes are not implemented, // and this is just for illustrative purposes var info = { scope: '*' }; return done(null, user, info); }); } else { //The request came from a client only since userID is null //therefore the client is passed back instead of a user db.clients.find(token.clientID, function (err, client) { if (err) { return done(err); } if (!client) { return done(null, false); } // to keep this example simple, restricted scopes are not implemented, // and this is just for illustrative purposes var info = { scope: '*' }; return done(null, client, info); }); } } }); } ));
mit
JacksonTian/ali-oss
lib/client.js
7606
/**! * ali-oss - lib/client.js * * Copyright(c) ali-sdk and other contributors. * MIT Licensed * * Authors: * dead_horse <[email protected]> * fengmk2 <[email protected]> (http://fengmk2.com) */ 'use strict'; /** * Module dependencies. */ var debug = require('debug')('ali-oss'); var crypto = require('crypto'); var path = require('path'); var querystring = require('querystring'); var copy = require('copy-to'); var mime = require('mime'); var urllib = require('urllib'); var xml = require('xml2js'); var ms = require('humanize-ms'); var AgentKeepalive = require('agentkeepalive'); var merge = require('merge-descriptors'); /** * Expose `Client` */ module.exports = Client; function Client(options) { if (!(this instanceof Client)) { return new Client(options); } if (!options || !options.accessKeyId || !options.accessKeySecret) { throw new Error('require accessKeyId, accessKeySecret'); } var DEFAULT_OPTIONS = { region: 'oss-cn-hangzhou', internal: false, timeout: '60s', bucket: null }; this.options = {}; copy(options).and(DEFAULT_OPTIONS).to(this.options); this.setRegion(this.options.region); this.options.timeout = ms(this.options.timeout); this.agent = this.options.agent || new AgentKeepalive(); } /** * prototype */ var proto = Client.prototype; /** * Object operations */ merge(proto, require('./object')); /** * Bucket operations */ merge(proto, require('./bucket')); /** * ImageClient class */ Client.ImageClient = require('./image')(Client); proto.setRegion = function (region) { if (!this.options.host || region !== this.options.region) { this.options.region = region; this.options.host = this._getRegionHost(region); } return this; }; /** * get author header * * "Authorization: OSS " + Access Key Id + ":" + Signature * * Signature = base64(hmac-sha1(Access Key Secret + "\n" * + VERB + "\n" * + CONTENT-MD5 + "\n" * + CONTENT-TYPE + "\n" * + DATE + "\n" * + CanonicalizedOSSHeaders * + CanonicalizedResource)) * * @param {String} method * @param {String} resource * @param {Object} header * @return {String} * * @api private */ proto.authorization = function (method, resource, headers) { var auth = 'OSS ' + this.options.accessKeyId + ':'; var params = [ method.toUpperCase(), headers['Content-Md5'] || '', headers['Content-Type'], headers.Date || new Date().toString() ]; var ossHeaders = {}; for (var key in headers) { var lkey = key.toLowerCase().trim(); if (lkey.indexOf('x-oss-') === 0) { ossHeaders[lkey] = ossHeaders[lkey] || []; ossHeaders[lkey].push(String(headers[key]).trim()); } } var ossHeadersList = []; Object.keys(ossHeaders).sort().forEach(function (key) { ossHeadersList.push(key + ':' + ossHeaders[key].join(',')); }); params = params.concat(ossHeadersList); // TODO: support sub resource params.push(resource); var stringToSign = params.join('\n'); debug('authorization stringToSign: %s', stringToSign); var signature = crypto.createHmac('sha1', this.options.accessKeySecret); signature = signature.update(stringToSign).digest('base64'); return auth + signature; }; /** * request oss server * @param {Object} params * - {String} name * - {String} method * - {String} [resource] * - {String} [region] * - {Object} [headers] * - {Object} [query] * - {Number} [timeout] * - {Buffer} [content] * - {Stream} [writeStream] * - {String} [mime] * - {Boolean} [customResponse] * * @api private */ proto.request = function* (params) { var host = params.host || this.options.host; if (params.region) { host = this._getRegionHost(params.region); } var headers = { Date: new Date().toGMTString() }; if (params.content || params.stream) { if (params.mime && params.mime.indexOf('/') > 0) { headers['Content-Type'] = params.mime; } else { headers['Content-Type'] = mime.lookup(params.mime || path.extname(params.name)); } if (params.content) { headers['Content-Md5'] = crypto .createHash('md5') .update(params.content) .digest('base64'); if (!headers['Content-Length']) { headers['Content-Length'] = params.content.length; } } } copy(params.headers).to(headers); var resource = params.resource; var authResource = params.authResource || resource; headers.authorization = this.authorization(params.method, authResource, headers); var url = 'http://' + host + resource; if (params.query) { url += '?' + querystring.stringify(params.query); } debug('request %s %s, with headers %j, !!stream: %s', params.method, url, headers, params.stream); var timeout = params.timeout || this.options.timeout; var reqParams = { agent: this.agent, method: params.method, content: params.content, stream: params.stream, headers: headers, timeout: timeout, writeStream: params.writeStream, customResponse: params.customResponse, }; var result = yield urllib.requestThunk(url, reqParams); debug('response %s %s, got %s, headers: %j', params.method, url, result.status, result.headers); if (params.successStatuses && params.successStatuses.indexOf(result.status) === -1) { throw yield* this.requestError(result); } if (params.xmlResponse) { result.data = yield this.parseXML(result.data); } return result; }; proto._getRegionHost = function (region) { if (this.options.internal) { return region + '-internal.aliyuncs.com'; } else { return region + '.aliyuncs.com'; } }; /** * thunkify xml.parseString * @param {String|Buffer} str * * @api private */ proto.parseXML = function (str) { return function (done) { if (Buffer.isBuffer(str)) { str = str.toString(); } xml.parseString(str, { explicitRoot: false, explicitArray: false }, done); }; }; /** * generater a request error with request response * @param {Object} result * * @api private */ proto.requestError = function* (result) { var err; if (!result.data || !result.data.length) { // HEAD not exists resource if (result.status === 404) { err = new Error('Object not exists'); err.name = 'NoSuchKeyError'; err.status = 404; err.code = 'NoSuchKey'; } else if (result.status === 412) { err = new Error('Pre condition failed'); err.name = 'PreconditionFailedError'; err.status = 412; err.code = 'PreconditionFailed'; } else { err = new Error('Unknow error, status: ' + result.status); err.name = 'UnknowError'; err.status = result.status; } err.requestId = result.headers['x-oss-request-id']; err.host = ''; } else { var message = String(result.data); debug('request response error data: %s', message); var info; try { info = yield this.parseXML(message) || {}; } catch (err) { debug(message); err.message += '\nraw xml: ' + message; err.status = result.status; err.requestId = result.headers['x-oss-request-id']; return err; } var message = info.Message || ('unknow request error, status: ' + result.status); if (info.Condition) { message += ' (condition: ' + info.Condition + ')'; } var err = new Error(message); err.name = info.Code ? info.Code + 'Error' : 'UnknowError'; err.status = result.status; err.code = info.Code; err.requestId = info.RequestId; err.hostId = info.HostId; } debug('generate error %j', err); return err; };
mit
libgraviton/graviton
src/Graviton/AnalyticsBundle/DependencyInjection/GravitonAnalyticsExtension.php
996
<?php /** * Extension config and loader */ namespace Graviton\AnalyticsBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * Basic functional test for Analytics * * @author List of contributors <https://github.com/libgraviton/graviton/graphs/contributors> * @license https://opensource.org/licenses/MIT MIT License * @link http://swisscom.ch */ class GravitonAnalyticsExtension extends Extension { /** * @param array $configs Optional configuration * @param ContainerBuilder $container Sf Container * @return void */ public function load(array $configs, ContainerBuilder $container) { $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); } }
mit
dshorthouse/SimpleMappr
public/javascript/jquery.download.js
953
/* * jQuery Download */ /*global $, jQuery, unescape */ (function() { "use strict"; $.fn.download = function(url, data, method) { var clean_string = function(str) { return unescape(str.replace(/\+/g, ' ')).replace(/\"/g, '&quot;'); }; return this.each(function() { var form = '', id = '', pair = []; if(url && data){ data = (typeof data === 'string') ? data : $.param(data); form = $('<form id="jquery-download-extension" action="' + url + '" method="' + (method||'post') + '"></form>'); $.each(data.split('&'), function(){ pair = this.split('='); id = 'jquery-download-' + unescape(pair[0]); form.append('<input type="hidden" name="' + unescape(pair[0]) + '" id="' + id + '" value="' + clean_string(pair[1]) + '" />'); }); form.appendTo($('body')); $('#jquery-download-extension').submit().remove(); } }); }; }(jQuery));
mit
SlicesOfPi/Steam-Account-Creator
accountGen/src/signup/MakeAcc.java
4065
package signup; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.Map; import java.util.Random; import java.util.Scanner; import org.jsoup.Connection; import org.jsoup.Connection.Method; import org.jsoup.Connection.Response; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; public class MakeAcc { //public static CloseableHttpClient httpclient = HttpClients.createDefault(); public static Scanner scanner = new Scanner(System.in); public static String word = ""; public static Random generator = new Random(); public static String[] genAccount() throws Exception { // TODO Auto-generated method stub Document doc = Jsoup.connect("https://store.steampowered.com/join") .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36") .get(); Element capatcha = doc.getElementById("captchaImg"); String capURL = capatcha.attr("src"); String capGID = capURL.replace("https://store.steampowered.com/public/captcha.php?gid=", ""); BufferedWriter out = new BufferedWriter(new FileWriter("link.html")); String pageData = "<html>\r\n" + "<head>\r\n" + " <meta http-equiv=\"Cache-Control\" content=\"no-cache, no-store, must-revalidate\"/>\r\n" + " <meta http-equiv=\"Pragma\" content=\"no-cache\"/>\r\n" + " <meta http-equiv=\"Expires\" content=\"0\"/>\r\n" + " <title></title>\r\n" + "</head>\r\n" + "<body>\r\n" + " \r\n" + "\r\n" + "\r\n" + "<div id=\"diggg\"></div>\r\n" + "<img id=\"pigly\" src=\"https://store.steampowered.com/public/captcha.php?gid="+capGID+"&e\"><br>\r\n" + "<img id=\"pigly\" src=\"https://store.steampowered.com/public/captcha.php?gid="+capGID+"&ee\"><br>\r\n" + "<img id=\"pigly\" src=\"https://store.steampowered.com/public/captcha.php?gid="+capGID+"&eee\">\r\n" + "\r\n" + "\r\n" + "</body>\r\n" + "</html>"; out.write(pageData); out.close(); System.out.println("Capatcha Link>\n"+capURL); String capTXT = scanner.nextLine(); String[] letters = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}; int letterLength = generator.nextInt(5)+5; for(int i=0;i<=letterLength;i++) { int randNum = generator.nextInt(26); word = word+letters[randNum]; } int stuffAfter = generator.nextInt(9000)+1000; int randPwd = generator.nextInt(10); String[] pwds = {"The small cat123", "The large cat123", "I love dead animals123", "I hate dead animals123", "Broken Bottle321", "Amazing Fluffball 123", "G502 Master Race", "Glorius Must I say", "The ninety ninth nine", "Then ten ten ben 123"}; String pswd = pwds[randPwd]; String accName = word+stuffAfter; String emailURL = "@dispostable.com"; String createURL = "https://store.steampowered.com/join/createaccount/"; Response res = Jsoup.connect(createURL) .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36") .data("accountname", accName) .data("password", pswd) .data("email", accName+emailURL) .data("captchagid", capGID) .data("captcha_text", capTXT) .data("i_agree", "1") .data("ticket", "") .data("count", "6") .data("lt", "0") .header("x-requested-with", "XMLHttpRequest") .ignoreContentType(true) .header("content-type", "application/x-www-form-urlencoded; charset=UTF-8") .method(Method.POST) .execute(); Map<String, String> theCookies = res.cookies(); main.Main.theCookies = theCookies; System.out.println(res.statusCode()); if(res.body().contains("\"bSuccess\":true")) { System.out.println("Success!"); } else { System.out.println("Something went wrong!"); } //Document createPost = res.parse(); System.out.println(accName+":"+pswd); String[] returnStatement = {accName, pswd}; return returnStatement; } }
mit
huoyaoyuan/osu
osu.Game/Graphics/Containers/OsuClickableContainer.cs
1487
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Cursor; using osu.Framework.Localisation; using osu.Game.Graphics.UserInterface; namespace osu.Game.Graphics.Containers { public class OsuClickableContainer : ClickableContainer, IHasTooltip { private readonly HoverSampleSet sampleSet; private readonly Container content = new Container { RelativeSizeAxes = Axes.Both }; protected override Container<Drawable> Content => content; protected virtual HoverClickSounds CreateHoverClickSounds(HoverSampleSet sampleSet) => new HoverClickSounds(sampleSet); public OsuClickableContainer(HoverSampleSet sampleSet = HoverSampleSet.Default) { this.sampleSet = sampleSet; } public virtual LocalisableString TooltipText { get; set; } [BackgroundDependencyLoader] private void load() { if (AutoSizeAxes != Axes.None) { content.RelativeSizeAxes = (Axes.Both & ~AutoSizeAxes); content.AutoSizeAxes = AutoSizeAxes; } InternalChildren = new Drawable[] { content, CreateHoverClickSounds(sampleSet) }; } } }
mit
Azure/azure-sdk-for-ruby
management/azure_mgmt_event_grid/lib/2020-04-01-preview/generated/azure_mgmt_event_grid/models/string_contains_advanced_filter.rb
2068
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::EventGrid::Mgmt::V2020_04_01_preview module Models # # StringContains Advanced Filter. # class StringContainsAdvancedFilter < AdvancedFilter include MsRestAzure def initialize @operatorType = "StringContains" end attr_accessor :operatorType # @return [Array<String>] The set of filter values. attr_accessor :values # # Mapper for StringContainsAdvancedFilter class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'StringContains', type: { name: 'Composite', class_name: 'StringContainsAdvancedFilter', model_properties: { key: { client_side_validation: true, required: false, serialized_name: 'key', type: { name: 'String' } }, operatorType: { client_side_validation: true, required: true, serialized_name: 'operatorType', type: { name: 'String' } }, values: { client_side_validation: true, required: false, serialized_name: 'values', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'StringElementType', type: { name: 'String' } } } } } } } end end end end
mit
chrisntr/FindTheMonkey-GoogleGlass
MonkeyGlass/Properties/AssemblyInfo.cs
1009
using System.Reflection; using System.Runtime.CompilerServices; using Android.App; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle ("MonkeyGlass")] [assembly: AssemblyDescription ("")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright ("chrisntr")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion ("1.0.0")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
mit
xabbuh/PandaBundle
Tests/Command/UploadVideoCommandTest.php
3426
<?php /* * This file is part of the XabbuhPandaBundle package. * * (c) Christian Flothmann <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Xabbuh\PandaBundle\Tests\Command; use Symfony\Bridge\PhpUnit\SetUpTearDownTrait; use Symfony\Component\Console\Command\Command; use Xabbuh\PandaBundle\Command\UploadVideoCommand; /** * @author Christian Flothmann <[email protected]> */ class UploadVideoCommandTest extends CloudCommandTest { use SetUpTearDownTrait; private function doSetUp() { parent::setUp(); $this->apiMethod = 'encodeVideoFile'; } public function testCommand() { $this->defaultCloud ->expects($this->once()) ->method('encodeVideoFile') ->with('foo'); $this->runCommand('panda:video:upload', array('filename' => 'foo')); $this->assertRegExp('/File uploaded successfully./', $this->commandTester->getDisplay()); } public function testCommandWithOneProfileOption() { $this->defaultCloud ->expects($this->once()) ->method('encodeVideoFile') ->with('foo', array('profile1')); $this->runCommand('panda:video:upload', array( '--profile' => array('profile1'), 'filename' => 'foo', )); $this->assertRegExp('/File uploaded successfully./', $this->commandTester->getDisplay()); } public function testCommandWithMultipleProfileOptions() { $this->defaultCloud ->expects($this->once()) ->method('encodeVideoFile') ->with('foo', array('profile1', 'profile2')); $this->runCommand('panda:video:upload', array( '--profile' => array('profile1', 'profile2'), 'filename' => 'foo', )); $this->assertRegExp('/File uploaded successfully./', $this->commandTester->getDisplay()); } public function testCommandWithCustomPathFormatOption() { $this->defaultCloud ->expects($this->once()) ->method('encodeVideoFile') ->with('foo', array(), 'bar/:id', null); $this->runCommand('panda:video:upload', array( '--path-format' => 'bar/:id', 'filename' => 'foo', )); $this->assertRegExp('/File uploaded successfully./', $this->commandTester->getDisplay()); } public function testCommandWithPayloadOption() { $this->defaultCloud ->expects($this->once()) ->method('encodeVideoFile') ->with('foo', array(), null, 'baz'); $this->runCommand('panda:video:upload', array( '--payload' => 'baz', 'filename' => 'foo', )); $this->assertRegExp('/File uploaded successfully./', $this->commandTester->getDisplay()); } public function testCommandWithoutArguments() { self::expectException(\RuntimeException::class); self::expectExceptionMessage('Not enough arguments'); $this->runCommand('panda:video:upload'); } protected function createCommand(): Command { return new UploadVideoCommand($this->cloudManager); } protected function getDefaultCommandArguments() { return array('filename' => 'video-file.mp4'); } }
mit
Chanaka1215/Angular2DashBoard
app/components/dashBoard/driverForm/newDriver.component.ts
817
/** * Created by Chanaka Fernando on 2/4/2017. */ /** * Created by Chanaka Fernando on 2/4/2017. */ import {Component} from '@angular/core'; import {ServiceCalls} from "../../../services/serviceCalls.service"; @Component({ moduleId :module.id, selector: 'driver', templateUrl: 'newDriver.component.html', }) export class newDriverComponent{ profileObject =Array(); constructor(private _serviceCalls:ServiceCalls){ this.onInit(); console.log(this.profileObject); } onInit(){ var url ='http://localhost:8000/profile'; this._serviceCalls.getData(url) .subscribe( data => this.profileObject = data, error => alert(error), () => {console.log('data retreving part successfilly compleated'), console.log(this.profileObject)} ); } }
mit
hphilippe/TT-pontrambertois
src/TT/platformBundle/DependencyInjection/Configuration.php
842
<?php namespace TT\platformBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files. * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/configuration.html} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('t_tplatform'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
mit