code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "OD", "OT" ], "DAY": [ "Jumapil", "Wuok Tich", "Tich Ariyo", "Tich Adek", "Tich Ang\u2019wen", "Tich Abich", "Ngeso" ], "ERANAMES": [ "Kapok Kristo obiro", "Ka Kristo osebiro" ], "ERAS": [ "BC", "AD" ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "Dwe mar Achiel", "Dwe mar Ariyo", "Dwe mar Adek", "Dwe mar Ang\u2019wen", "Dwe mar Abich", "Dwe mar Auchiel", "Dwe mar Abiriyo", "Dwe mar Aboro", "Dwe mar Ochiko", "Dwe mar Apar", "Dwe mar gi achiel", "Dwe mar Apar gi ariyo" ], "SHORTDAY": [ "JMP", "WUT", "TAR", "TAD", "TAN", "TAB", "NGS" ], "SHORTMONTH": [ "DAC", "DAR", "DAD", "DAN", "DAH", "DAU", "DAO", "DAB", "DOC", "DAP", "DGI", "DAG" ], "STANDALONEMONTH": [ "Dwe mar Achiel", "Dwe mar Ariyo", "Dwe mar Adek", "Dwe mar Ang\u2019wen", "Dwe mar Abich", "Dwe mar Auchiel", "Dwe mar Abiriyo", "Dwe mar Aboro", "Dwe mar Ochiko", "Dwe mar Apar", "Dwe mar gi achiel", "Dwe mar Apar gi ariyo" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y h:mm:ss a", "mediumDate": "d MMM y", "mediumTime": "h:mm:ss a", "short": "dd/MM/y h:mm a", "shortDate": "dd/MM/y", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "Ksh", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-", "negSuf": "\u00a4", "posPre": "", "posSuf": "\u00a4" } ] }, "id": "luo", "localeID": "luo", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
okboy5555/demo
基于angular的图书管理/src/framework/angular-1.5.8/i18n/angular-locale_luo.js
JavaScript
apache-2.0
2,946
/* * Copyright (C) 2009,2010,2011,2012 Samuel Audet * * This file is part of JavaCV. * * JavaCV is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version (subject to the "Classpath" exception * as provided in the LICENSE.txt file that accompanied this code). * * JavaCV 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 JavaCV. If not, see <http://www.gnu.org/licenses/>. */ package com.googlecode.javacv; import static com.googlecode.javacv.cpp.cvkernels.*; import static com.googlecode.javacv.cpp.opencv_calib3d.*; import static com.googlecode.javacv.cpp.opencv_core.*; import static com.googlecode.javacv.cpp.opencv_imgproc.*; /** * * @author Samuel Audet */ public class ProCamTransformer implements ImageTransformer { public ProCamTransformer(double[] referencePoints, CameraDevice camera, ProjectorDevice projector) { this(referencePoints, camera, projector, null); } public ProCamTransformer(double[] referencePoints, CameraDevice camera, ProjectorDevice projector, CvMat n) { this.camera = camera; this.projector = projector; if (referencePoints != null) { this.surfaceTransformer = new ProjectiveColorTransformer( camera.cameraMatrix, camera.cameraMatrix, null, null, n, referencePoints, null, null, 3, 0); } double[] referencePoints1 = { 0, 0, camera.imageWidth/2, camera.imageHeight, camera.imageWidth, 0 }; double[] referencePoints2 = { 0, 0, projector.imageWidth/2, projector.imageHeight, projector.imageWidth, 0 }; if (n != null) { invCameraMatrix = CvMat.create(3, 3); cvInvert(camera.cameraMatrix, invCameraMatrix); JavaCV.perspectiveTransform(referencePoints2, referencePoints1, invCameraMatrix, projector.cameraMatrix, projector.R, projector.T, n, true); } this.projectorTransformer = new ProjectiveColorTransformer( camera.cameraMatrix, projector.cameraMatrix, projector.R, projector.T, null, referencePoints1, referencePoints2, projector.colorMixingMatrix, /*surfaceTransformer == null ? 3 : */1, 3); // CvMat n2 = createParameters().getN(); if (referencePoints != null && n != null) { frontoParallelH = camera.getFrontoParallelH(referencePoints, n, CvMat.create(3, 3)); invFrontoParallelH = frontoParallelH.clone(); cvInvert(frontoParallelH, invFrontoParallelH); } } protected CameraDevice camera = null; protected ProjectorDevice projector = null; protected ProjectiveColorTransformer surfaceTransformer = null; protected ProjectiveColorTransformer projectorTransformer = null; protected IplImage[] projectorImage = null, surfaceImage = null; protected CvScalar fillColor = cvScalar(0.0, 0.0, 0.0, 1.0); protected CvRect roi = new CvRect(); protected CvMat frontoParallelH = null, invFrontoParallelH = null; protected CvMat invCameraMatrix = null; protected KernelData kernelData = null; protected CvMat[] H1 = null; protected CvMat[] H2 = null; protected CvMat[] X = null; public int getNumGains() { return projectorTransformer.getNumGains(); } public int getNumBiases() { return projectorTransformer.getNumBiases(); } public CvScalar getFillColor() { return fillColor; } public void setFillColor(CvScalar fillColor) { this.fillColor = fillColor; } public ProjectiveColorTransformer getSurfaceTransformer() { return surfaceTransformer; } public ProjectiveColorTransformer getProjectorTransformer() { return projectorTransformer; } public IplImage getProjectorImage(int pyramidLevel) { return projectorImage[pyramidLevel]; } public void setProjectorImage(IplImage projectorImage0, int minLevel, int maxLevel) { setProjectorImage(projectorImage0, minLevel, maxLevel, true); } public void setProjectorImage(IplImage projectorImage0, int minLevel, int maxLevel, boolean convertToFloat) { if (projectorImage == null || projectorImage.length != maxLevel+1) { projectorImage = new IplImage[maxLevel+1]; } if (projectorImage0.depth() == IPL_DEPTH_32F || !convertToFloat) { projectorImage[minLevel] = projectorImage0; } else { if (projectorImage[minLevel] == null) { projectorImage[minLevel] = IplImage.create(projectorImage0.width(), projectorImage0.height(), IPL_DEPTH_32F, projectorImage0.nChannels(), projectorImage0.origin()); } IplROI ir = projectorImage0.roi(); if (ir != null) { int align = 1<<(maxLevel+1); roi.x(Math.max(0, (int)Math.floor((double)ir.xOffset()/align)*align)); roi.y(Math.max(0, (int)Math.floor((double)ir.yOffset()/align)*align)); roi.width (Math.min(projectorImage0.width(), (int)Math.ceil((double)ir.width() /align)*align)); roi.height(Math.min(projectorImage0.height(), (int)Math.ceil((double)ir.height()/align)*align)); cvSetImageROI(projectorImage0, roi); cvSetImageROI(projectorImage[minLevel], roi); } else { cvResetImageROI(projectorImage0); cvResetImageROI(projectorImage[minLevel]); } cvConvertScale(projectorImage0, projectorImage[minLevel], 1.0/255.0, 0); } // CvScalar.ByValue average = cvAvg(projectorImage[0], null); // cvSubS(projectorImage[0], average, projectorImage[0], null); for (int i = minLevel+1; i <= maxLevel; i++) { int w = projectorImage[i-1].width()/2; int h = projectorImage[i-1].height()/2; int d = projectorImage[i-1].depth(); int c = projectorImage[i-1].nChannels(); int o = projectorImage[i-1].origin(); if (projectorImage[i] == null) { projectorImage[i] = IplImage.create(w, h, d, c, o); } IplROI ir = projectorImage[i-1].roi(); if (ir != null) { roi.x(ir.xOffset()/2); roi.width (ir.width() /2); roi.y(ir.yOffset()/2); roi.height(ir.height()/2); cvSetImageROI(projectorImage[i], roi); } else { cvResetImageROI(projectorImage[i]); } cvPyrDown(projectorImage[i-1], projectorImage[i], CV_GAUSSIAN_5x5); cvResetImageROI(projectorImage[i-1]); } } public IplImage getSurfaceImage(int pyramidLevel) { return surfaceImage[pyramidLevel]; } public void setSurfaceImage(IplImage surfaceImage0, int pyramidLevels) { if (surfaceImage == null || surfaceImage.length != pyramidLevels) { surfaceImage = new IplImage[pyramidLevels]; } surfaceImage[0] = surfaceImage0; cvResetImageROI(surfaceImage0); for (int i = 1; i < pyramidLevels; i++) { int w = surfaceImage[i-1].width()/2; int h = surfaceImage[i-1].height()/2; int d = surfaceImage[i-1].depth(); int c = surfaceImage[i-1].nChannels(); int o = surfaceImage[i-1].origin(); if (surfaceImage[i] == null) { surfaceImage[i] = IplImage.create(w, h, d, c, o); } else { cvResetImageROI(surfaceImage[i]); } cvPyrDown(surfaceImage[i-1], surfaceImage[i], CV_GAUSSIAN_5x5); } } protected void prepareTransforms(CvMat H1, CvMat H2, CvMat X, int pyramidLevel, Parameters p) { ProjectiveColorTransformer.Parameters cameraParameters = p.getSurfaceParameters(); ProjectiveColorTransformer.Parameters projectorParameters = p.getProjectorParameters(); if (surfaceTransformer != null) { cvInvert(cameraParameters.getH(), H1); } cvInvert(projectorParameters.getH(), H2); // adjust the scale of the transformation based on the pyramid level if (pyramidLevel > 0) { int scale = 1<<pyramidLevel; if (surfaceTransformer != null) { H1.put(2, H1.get(2)/scale); H1.put(5, H1.get(5)/scale); H1.put(6, H1.get(6)*scale); H1.put(7, H1.get(7)*scale); } H2.put(2, H2.get(2)/scale); H2.put(5, H2.get(5)/scale); H2.put(6, H2.get(6)*scale); H2.put(7, H2.get(7)*scale); } double[] x = projector.colorMixingMatrix.get(); double[] a = projectorParameters.getColorParameters(); double a2 = a[0]; X.put(a2*x[0], a2*x[1], a2*x[2], a[1], a2*x[3], a2*x[4], a2*x[5], a[2], a2*x[6], a2*x[7], a2*x[8], a[3], 0, 0, 0, 1); } public void transform(final IplImage srcImage, final IplImage dstImage, final CvRect roi, final int pyramidLevel, final ImageTransformer.Parameters parameters, final boolean inverse) { if (inverse) { throw new UnsupportedOperationException("Inverse transform not supported."); } final Parameters p = ((Parameters)parameters); final ProjectiveTransformer.Parameters cameraParameters = p.getSurfaceParameters(); final ProjectiveTransformer.Parameters projectorParameters = p.getProjectorParameters(); if (p.tempImage == null || p.tempImage.length <= pyramidLevel) { p.tempImage = new IplImage[pyramidLevel+1]; } p.tempImage[pyramidLevel] = IplImage.createIfNotCompatible(p.tempImage[pyramidLevel], dstImage); if (roi == null) { cvResetImageROI(p.tempImage[pyramidLevel]); } else { cvSetImageROI(p.tempImage[pyramidLevel], roi); } // Parallel.run(new Runnable() { public void run() { // warp the template image if (surfaceTransformer != null) { surfaceTransformer.transform(srcImage, p.tempImage[pyramidLevel], roi, pyramidLevel, cameraParameters, false); } // }}, new Runnable() { public void run() { // warp the projector image projectorTransformer.transform(projectorImage[pyramidLevel], dstImage, roi, pyramidLevel, projectorParameters, false); // }}); // multiply projector image with template image if (surfaceTransformer != null) { cvMul(dstImage, p.tempImage[pyramidLevel], dstImage, 1/dstImage.highValue()); } else { cvCopy(p.tempImage[pyramidLevel], dstImage); } } public void transform(CvMat srcPts, CvMat dstPts, ImageTransformer.Parameters parameters, boolean inverse) { if (surfaceTransformer != null) { surfaceTransformer.transform(srcPts, dstPts, ((Parameters)parameters).surfaceParameters, inverse); } else if (dstPts != srcPts) { dstPts.put(srcPts); } } public void transform(Data[] data, CvRect roi, ImageTransformer.Parameters[] parameters, boolean[] inverses) { assert data.length == parameters.length; if (kernelData == null || kernelData.capacity() < data.length) { kernelData = new KernelData(data.length); } if ((H1 == null || H1.length < data.length) && surfaceTransformer != null) { H1 = new CvMat[data.length]; for (int i = 0; i < H1.length; i++) { H1[i] = CvMat.create(3, 3); } } if (H2 == null || H2.length < data.length) { H2 = new CvMat[data.length]; for (int i = 0; i < H2.length; i++) { H2[i] = CvMat.create(3, 3); } } if (X == null || X.length < data.length) { X = new CvMat[data.length]; for (int i = 0; i < X.length; i++) { X[i] = CvMat.create(4, 4); } } for (int i = 0; i < data.length; i++) { kernelData.position(i); kernelData.srcImg(projectorImage[data[i].pyramidLevel]); kernelData.srcImg2(surfaceTransformer == null ? null : data[i].srcImg); kernelData.subImg(data[i].subImg); kernelData.srcDotImg(data[i].srcDotImg); kernelData.mask(data[i].mask); kernelData.zeroThreshold(data[i].zeroThreshold); kernelData.outlierThreshold(data[i].outlierThreshold); if (inverses != null && inverses[i]) { throw new UnsupportedOperationException("Inverse transform not supported."); } prepareTransforms(surfaceTransformer == null ? null : H1[i], H2[i], X[i], data[i].pyramidLevel, (Parameters)parameters[i]); kernelData.H1(H2[i]); kernelData.H2(surfaceTransformer == null ? null : H1[i]); kernelData.X (X [i]); kernelData.transImg(data[i].transImg); kernelData.dstImg(data[i].dstImg); kernelData.dstDstDot(data[i].dstDstDot); } int fullCapacity = kernelData.capacity(); kernelData.capacity(data.length); multiWarpColorTransform(kernelData, roi, getFillColor()); kernelData.capacity(fullCapacity); for (int i = 0; i < data.length; i++) { kernelData.position(i); data[i].dstCount = kernelData.dstCount(); data[i].dstCountZero = kernelData.dstCountZero(); data[i].dstCountOutlier = kernelData.dstCountOutlier(); data[i].srcDstDot = kernelData.srcDstDot(); } // if (data[0].dstCountZero > 0) { // System.err.println(data[0].dstCountZero + " out of " + data[0].dstCount // + " are zero = " + 100*data[0].dstCountZero/data[0].dstCount + "%"); // } } public Parameters createParameters() { return new Parameters(); } public class Parameters implements ImageTransformer.Parameters { protected Parameters() { reset(false); } protected Parameters(ProjectiveColorTransformer.Parameters surfaceParameters, ProjectiveColorTransformer.Parameters projectorParameters) { reset(surfaceParameters, projectorParameters); } private ProjectiveColorTransformer.Parameters surfaceParameters = null; private ProjectiveColorTransformer.Parameters projectorParameters = null; private IplImage[] tempImage = null; private CvMat H = CvMat.create(3, 3), R = CvMat.create(3, 3), n = CvMat.create(3, 1), t = CvMat.create(3, 1); public ProjectiveColorTransformer.Parameters getSurfaceParameters() { return surfaceParameters; } public ProjectiveColorTransformer.Parameters getProjectorParameters() { return projectorParameters; } private int getSizeForSurface() { return surfaceTransformer == null ? 0 : surfaceParameters.size() - surfaceTransformer.getNumGains() - surfaceTransformer.getNumBiases(); } private int getSizeForProjector() { return projectorParameters.size(); } public int size() { return getSizeForSurface() + getSizeForProjector(); } public double[] get() { double[] p = new double[size()]; for (int i = 0; i < p.length; i++) { p[i] = get(i); } return p; } public double get(int i) { if (i < getSizeForSurface()) { return surfaceParameters.get(i); } else { return projectorParameters.get(i-getSizeForSurface()); } } public void set(double ... p) { for (int i = 0; i < p.length; i++) { set(i, p[i]); } } public void set(int i, double p) { if (i < getSizeForSurface()) { surfaceParameters.set(i, p); } else { projectorParameters.set(i-getSizeForSurface(), p); } } public void set(ImageTransformer.Parameters p) { Parameters pcp = (Parameters)p; if (surfaceTransformer != null) { surfaceParameters.set(pcp.getSurfaceParameters()); surfaceParameters.resetColor(false); } projectorParameters.set(pcp.getProjectorParameters()); } public void reset(boolean asIdentity) { reset(null, null); } public void reset(ProjectiveColorTransformer.Parameters surfaceParameters, ProjectiveColorTransformer.Parameters projectorParameters) { if (surfaceParameters == null && surfaceTransformer != null) { surfaceParameters = surfaceTransformer.createParameters(); } if (projectorParameters == null) { projectorParameters = projectorTransformer.createParameters(); } this.surfaceParameters = surfaceParameters; this.projectorParameters = projectorParameters; setSubspace(getSubspace()); } // public boolean addDelta(int i) { // return addDelta(i, 1); // } // public boolean addDelta(int i, double scale) { // // gradient varies linearly with intensity, so // // the increment value is not very important, but // // referenceCameraImage is good only for the value 1, // // so let's use that // if (i < getSizeForSurface()) { // surfaceParameters.addDelta(i, scale); // projectorParameters.setUpdateNeeded(true); // } else { // projectorParameters.addDelta(i-getSizeForSurface(), scale); // } // // return false; // } public double getConstraintError() { double error = surfaceTransformer == null ? 0 : surfaceParameters.getConstraintError(); projectorParameters.update(); return error; } public void compose(ImageTransformer.Parameters p1, boolean inverse1, ImageTransformer.Parameters p2, boolean inverse2) { throw new UnsupportedOperationException("Compose operation not supported."); } public boolean preoptimize() { double[] p = setSubspaceInternal(getSubspaceInternal()); if (p != null) { set(8, p[8]); set(9, p[9]); set(10, p[10]); return true; } return false; } public void setSubspace(double ... p) { double[] dst = setSubspaceInternal(p); if (dst != null) { set(dst); } } public double[] getSubspace() { return getSubspaceInternal(); } private double[] setSubspaceInternal(double ... p) { if (invFrontoParallelH == null) { return null; } double[] dst = new double[8+3]; t.put(p[0], p[1], p[2]); cvRodrigues2(t, R, null); t.put(p[3], p[4], p[5]); // compute new H H.put(R.get(0), R.get(1), t.get(0), R.get(3), R.get(4), t.get(1), R.get(6), R.get(7), t.get(2)); cvMatMul(H, invFrontoParallelH, H); cvMatMul(surfaceTransformer.getK2(), H, H); cvMatMul(H, surfaceTransformer.getInvK1(), H); // compute new n, rotation from the z-axis cvGEMM(R, t, 1, null, 0, t, CV_GEMM_A_T); double scale = 1/t.get(2); n.put(0.0, 0.0, 1.0); cvGEMM(R, n, scale, null, 0, n, 0); // compute and set new three points double[] src = projectorTransformer.getReferencePoints2(); JavaCV.perspectiveTransform(src, dst, projectorTransformer.getInvK1(),projectorTransformer.getK2(), projectorTransformer.getR(), projectorTransformer.getT(), n, true); dst[8] = dst[0]; dst[9] = dst[2]; dst[10] = dst[4]; // compute and set new four points JavaCV.perspectiveTransform(surfaceTransformer.getReferencePoints1(), dst, H); return dst; } private double[] getSubspaceInternal() { if (frontoParallelH == null) { return null; } cvMatMul(surfaceTransformer.getK1(), frontoParallelH, H); cvMatMul(surfaceParameters .getH(), H, H); cvMatMul(surfaceTransformer.getInvK2(), H, H); JavaCV.HtoRt(H, R, t); cvRodrigues2(R, n, null); double[] p = { n.get(0), n.get(1), n.get(2), t.get(0), t.get(1), t.get(2) }; return p; } public CvMat getN() { double[] src = projectorTransformer.getReferencePoints2(); double[] dst = projectorTransformer.getReferencePoints1().clone(); dst[0] = projectorParameters.get(0); dst[2] = projectorParameters.get(1); dst[4] = projectorParameters.get(2); // get plane parameters n, but since we model the target to be // the camera, we have to inverse everything before calling // getPlaneParameters() and reframe the n it returns cvTranspose(projectorTransformer.getR(), R); cvGEMM(R, projectorTransformer.getT(), -1, null, 0, t, 0); JavaCV.getPlaneParameters(src, dst, projectorTransformer.getInvK2(), projectorTransformer.getK1(), R, t, n); double d = 1 + cvDotProduct(n, projectorTransformer.getT()); cvGEMM(R, n, 1/d, null, 0, n, 0); return n; } public CvMat getN0() { n = getN(); if (surfaceTransformer == null) { return n; } // remove projective effect of the current n, // leaving only the effect of n0 camera.getFrontoParallelH(surfaceParameters.get(), n, R); cvInvert(surfaceParameters.getH(), H); cvMatMul(H, surfaceTransformer.getK2(), H); cvMatMul(H, R, H); cvMatMul(surfaceTransformer.getInvK1(), H, H); JavaCV.HtoRt(H, R, t); // compute n0, as a rotation from the z-axis cvGEMM(R, t, 1, null, 0, t, CV_GEMM_A_T); double scale = 1/t.get(2); n.put(0.0, 0.0, 1.0); cvGEMM(R, n, scale, null, 0, n, 0); return n; } @Override public Parameters clone() { Parameters p = new Parameters(); p.surfaceParameters = surfaceParameters == null ? null : surfaceParameters.clone(); p.projectorParameters = projectorParameters.clone(); return p; } @Override public String toString() { if (surfaceParameters != null) { return surfaceParameters.toString() + projectorParameters.toString(); } else { return projectorParameters.toString(); } } } }
JanesR/javacv
src/main/java/com/googlecode/javacv/ProCamTransformer.java
Java
gpl-2.0
23,990
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Service_Rackspace * @subpackage Files * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ require_once 'Zend/Service/Rackspace/Files.php'; class Zend_Service_Rackspace_Files_Object { /** * The service that has created the object * * @var Zend_Service_Rackspace_Files */ protected $service; /** * Name of the object * * @var string */ protected $name; /** * MD5 value of the object's content * * @var string */ protected $hash; /** * Size in bytes of the object's content * * @var integer */ protected $size; /** * Content type of the object's content * * @var string */ protected $contentType; /** * Date of the last modified of the object * * @var string */ protected $lastModified; /** * Object content * * @var string */ protected $content; /** * Name of the container where the object is stored * * @var string */ protected $container; /** * Constructor * * You must pass the Zend_Service_Rackspace_Files object of the caller and an associative * array with the keys "name", "container", "hash", "bytes", "content_type", * "last_modified", "file" where: * name= name of the object * container= name of the container where the object is stored * hash= the MD5 of the object's content * bytes= size in bytes of the object's content * content_type= content type of the object's content * last_modified= date of the last modified of the object * content= content of the object * * @param Zend_Service_Rackspace_Files $service * @param array $data */ public function __construct($service,$data) { if (!($service instanceof Zend_Service_Rackspace_Files) || !is_array($data)) { require_once 'Zend/Service/Rackspace/Files/Exception.php'; throw new Zend_Service_Rackspace_Files_Exception("You must pass a RackspaceFiles and an array"); } if (!array_key_exists('name', $data)) { require_once 'Zend/Service/Rackspace/Files/Exception.php'; throw new Zend_Service_Rackspace_Files_Exception("You must pass the name of the object in the array (name)"); } if (!array_key_exists('container', $data)) { require_once 'Zend/Service/Rackspace/Files/Exception.php'; throw new Zend_Service_Rackspace_Files_Exception("You must pass the container of the object in the array (container)"); } if (!array_key_exists('hash', $data)) { require_once 'Zend/Service/Rackspace/Files/Exception.php'; throw new Zend_Service_Rackspace_Files_Exception("You must pass the hash of the object in the array (hash)"); } if (!array_key_exists('bytes', $data)) { require_once 'Zend/Service/Rackspace/Files/Exception.php'; throw new Zend_Service_Rackspace_Files_Exception("You must pass the byte size of the object in the array (bytes)"); } if (!array_key_exists('content_type', $data)) { require_once 'Zend/Service/Rackspace/Files/Exception.php'; throw new Zend_Service_Rackspace_Files_Exception("You must pass the content type of the object in the array (content_type)"); } if (!array_key_exists('last_modified', $data)) { require_once 'Zend/Service/Rackspace/Files/Exception.php'; throw new Zend_Service_Rackspace_Files_Exception("You must pass the last modified data of the object in the array (last_modified)"); } $this->name= $data['name']; $this->container= $data['container']; $this->hash= $data['hash']; $this->size= $data['bytes']; $this->contentType= $data['content_type']; $this->lastModified= $data['last_modified']; if (!empty($data['content'])) { $this->content= $data['content']; } $this->service= $service; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Get the name of the container * * @return string */ public function getContainer() { return $this->container; } /** * Get the MD5 of the object's content * * @return string|boolean */ public function getHash() { return $this->hash; } /** * Get the size (in bytes) of the object's content * * @return integer|boolean */ public function getSize() { return $this->size; } /** * Get the content type of the object's content * * @return string */ public function getContentType() { return $this->contentType; } /** * Get the data of the last modified of the object * * @return string */ public function getLastModified() { return $this->lastModified; } /** * Get the content of the object * * @return string */ public function getContent() { return $this->content; } /** * Get the metadata of the object * If you don't pass the $key it returns the entire array of metadata value * * @param string $key * @return string|array|boolean */ public function getMetadata($key=null) { $result= $this->service->getMetadataObject($this->container,$this->name); if (!empty($result)) { if (empty($key)) { return $result['metadata']; } if (isset($result['metadata'][$key])) { return $result['metadata'][$key]; } } return false; } /** * Set the metadata value * The old metadata values are replaced with the new one * * @param array $metadata * @return boolean */ public function setMetadata($metadata) { return $this->service->setMetadataObject($this->container,$this->name,$metadata); } /** * Copy the object to another container * You can add metadata information to the destination object, change the * content_type and the name of the object * * @param string $container_dest * @param string $name_dest * @param array $metadata * @param string $content_type * @return boolean */ public function copyTo($container_dest,$name_dest,$metadata=array(),$content_type=null) { return $this->service->copyObject($this->container,$this->name,$container_dest,$name_dest,$metadata,$content_type); } /** * Get the CDN URL of the object * * @return string */ public function getCdnUrl() { $result= $this->service->getInfoCdnContainer($this->container); if ($result!==false) { if ($result['cdn_enabled']) { return $result['cdn_uri'].'/'.$this->name; } } return false; } /** * Get the CDN SSL URL of the object * * @return string */ public function getCdnUrlSsl() { $result= $this->service->getInfoCdnContainer($this->container); if ($result!==false) { if ($result['cdn_enabled']) { return $result['cdn_uri_ssl'].'/'.$this->name; } } return false; } }
mattsimpson/entrada-1x
www-root/core/library/Zend/Service/Rackspace/Files/Object.php
PHP
gpl-3.0
8,137
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.example; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Bar { @XmlAttribute private String name; @XmlAttribute private String value; public Bar() { } public void setName(String name) { this.name = name; } public void setValue(String value) { this.value = value; } public String getName() { return name; } public String getValue() { return value; } }
CandleCandle/camel
components/camel-jaxb/src/test/java/org/apache/camel/example/Bar.java
Java
apache-2.0
1,514
<?php /** * @file * Sample hooks demonstrating usage in Webform. */ /** * @defgroup webform_hooks Webform Module Hooks * @{ * Webform's hooks enable other modules to intercept events within Webform, such * as the completion of a submission or adding validation. Webform's hooks also * allow other modules to provide additional components for use within forms. */ /** * Define callbacks that can be used as select list options. * * When users create a select component, they may select a pre-built list of * certain options. Webform core provides a few of these lists such as the * United States, countries of the world, and days of the week. This hook * provides additional lists that may be utilized. * * @see webform_options_example() * @see hook_webform_select_options_info_alter() * * @return * An array of callbacks that can be used for select list options. This array * should be keyed by the "name" of the pre-defined list. The values should * be an array with the following additional keys: * - title: The translated title for this list. * - options callback: The name of the function that will return the list. * - options arguments: Any additional arguments to send to the callback. * - file: Optional. The file containing the options callback, relative to * the module root. */ function hook_webform_select_options_info() { $items = array(); $items['days'] = array( 'title' => t('Days of the week'), 'options callback' => 'webform_options_days', 'file' => 'includes/webform.options.inc', ); return $items; } /** * Alter the list of select list options provided by Webform and other modules. * * @see hook_webform_select_options_info(). */ function hook_webform_select_options_info_alter(&$items) { // Remove the days of the week options. unset($items['days']); } /** * This is an example function to demonstrate a webform options callback. * * This function returns a list of options that Webform may use in a select * component. In order to be called, the function name * ("webform_options_example" in this case), needs to be specified as a callback * in hook_webform_select_options_info(). * * @param $component * The Webform component array for the select component being displayed. * @param $flat * Boolean value indicating whether the returned list needs to be a flat array * of key => value pairs. Select components support up to one level of * nesting, but when results are displayed, the list needs to be returned * without the nesting. * @param $arguments * The "options arguments" specified in hook_webform_select_options_info(). * @return * An array of key => value pairs suitable for a select list's #options * FormAPI property. */ function webform_options_example($component, $flat, $arguments) { $options = array( 'one' => t('Pre-built option one'), 'two' => t('Pre-built option two'), 'three' => t('Pre-built option three'), ); return $options; } /** * Respond to the loading of Webform submissions. * * @param $submissions * An array of Webform submissions that are being loaded, keyed by the * submission ID. Modifications to the submissions are done by reference. */ function hook_webform_submission_load(&$submissions) { foreach ($submissions as $sid => $submission) { $submissions[$sid]->new_property = 'foo'; } } /** * Respond to the creation of a new submission from form values. * * This hook is called when a user has completed a submission to initialize the * submission object. After this object has its values populated, it will be * saved by webform_submission_insert(). Note that this hook is only called for * new submissions, not for submissions being edited. If responding to the * saving of all submissions, it's recommended to use * hook_webform_submission_presave(). * * @param $submission * The submission object that has been created. * @param $node * The Webform node for which this submission is being saved. * @param $account * The user account that is creating the submission. * @param $form_state * The contents of form state that is the basis for this submission. * * @see webform_submission_create() */ function hook_webform_submission_create($submission, $node, $account, $form_state) { $submission->new_property = TRUE; } /** * Modify a Webform submission, prior to saving it in the database. * * @param $node * The Webform node on which this submission was made. * @param $submission * The Webform submission that is about to be saved to the database. */ function hook_webform_submission_presave($node, &$submission) { // Update some component's value before it is saved. $component_id = 4; $submission->data[$component_id][0] = 'foo'; } /** * Respond to a Webform submission being inserted. * * Note that this hook is called after a submission has already been saved to * the database. If needing to modify the submission prior to insertion, use * hook_webform_submission_presave(). * * @param $node * The Webform node on which this submission was made. * @param $submission * The Webform submission that was just inserted into the database. */ function hook_webform_submission_insert($node, $submission) { // Insert a record into a 3rd-party module table when a submission is added. db_insert('mymodule_table') ->fields(array( 'nid' => $node->nid, 'sid' => $submission->sid, 'foo' => 'foo_data', )) ->execute(); } /** * Respond to a Webform submission being updated. * * Note that this hook is called after a submission has already been saved to * the database. If needing to modify the submission prior to updating, use * hook_webform_submission_presave(). * * @param $node * The Webform node on which this submission was made. * @param $submission * The Webform submission that was just updated in the database. */ function hook_webform_submission_update($node, $submission) { // Update a record in a 3rd-party module table when a submission is updated. db_update('mymodule_table') ->fields(array( 'foo' => 'foo_data', )) ->condition('nid', $node->nid) ->condition('sid', $submission->sid) ->execute(); } /** * Respond to a Webform submission being deleted. * * @param $node * The Webform node on which this submission was made. * @param $submission * The Webform submission that was just deleted from the database. */ function hook_webform_submission_delete($node, $submission) { // Delete a record from a 3rd-party module table when a submission is deleted. db_delete('mymodule_table') ->condition('nid', $node->nid) ->condition('sid', $submission->sid) ->execute(); } /** * Provide a list of actions that can be executed on a submission. * * Some actions are displayed in the list of submissions such as edit, view, and * delete. All other actions are displayed only when viewing the submission. * These additional actions may be specified in this hook. Examples included * directly in the Webform module include PDF, print, and resend e-mails. Other * modules may extend this list by using this hook. * * @param $node * The Webform node on which this submission was made. * @param $submission * The Webform submission on which the actions may be performed. */ function hook_webform_submission_actions($node, $submission) { $actions= array(); if (webform_results_access($node)) { $actions['myaction'] = array( 'title' => t('Do my action'), 'href' => 'node/' . $node->nid . '/submission/' . $submission->sid . '/myaction', 'query' => drupal_get_destination(), ); } return $actions; } /** * Modify the draft to be presented for editing. * * When drafts are enabled for the webform, by default, a pre-existig draft is * presented when the webform is displayed to that user. To allow multiple * drafts, implement this alter function to set the $sid to NULL, or use your * application's business logic to determine whether a new draft or which of * he pre-existing drafts should be presented. * * @param integer $sid * The id of the most recent submission to be presented for editing. Change * to a different draft's sid or set to NULL for a new draft. * @param array $context * Array of context with indices 'nid' and 'uid'. */ function hook_webform_draft_alter(&$sid, $context) { if ($_GET['newdraft']) { $sid = NULL; } } /** * Alter the display of a Webform submission. * * This function applies to both e-mails sent by Webform and normal display of * submissions when viewing through the adminsitrative interface. * * @param $renderable * The Webform submission in a renderable array, similar to FormAPI's * structure. This variable must be passed in by-reference. Important * properties of this array include #node, #submission, #email, and #format, * which can be used to find the context of the submission that is being * rendered. */ function hook_webform_submission_render_alter(&$renderable) { // Remove page breaks from sent e-mails. if (isset($renderable['#email'])) { foreach (element_children($renderable) as $key) { if ($renderable[$key]['#component']['type'] == 'pagebreak') { unset($renderable[$key]); } } } } /** * Modify a loaded Webform component. * * IMPORTANT: This hook does not actually exist because components are loaded * in bulk as part of webform_node_load(). Use hook_node_load() to modify loaded * components when the node is loaded. This example is provided merely to point * to hook_node_load(). * * @see hook_nodeapi() * @see webform_node_load() */ function hook_webform_component_load() { // This hook does not exist. Instead use hook_node_load(). } /** * Modify a Webform component before it is saved to the database. * * Note that most of the time this hook is not necessary, because Webform will * automatically add data to the component based on the component form. Using * hook_form_alter() will be sufficient in most cases. * * @see hook_form_alter() * @see webform_component_edit_form() * * @param $component * The Webform component being saved. */ function hook_webform_component_presave(&$component) { $component['extra']['new_option'] = 'foo'; } /** * Respond to a Webform component being inserted into the database. */ function hook_webform_component_insert($component) { // Insert a record into a 3rd-party module table when a component is inserted. db_insert('mymodule_table') ->fields(array( 'nid' => $component['nid'], 'cid' => $component['cid'], 'foo' => 'foo_data', )) ->execute(); } /** * Respond to a Webform component being updated in the database. */ function hook_webform_component_update($component) { // Update a record in a 3rd-party module table when a component is updated. db_update('mymodule_table') ->fields(array( 'foo' => 'foo_data', )) ->condition('nid', $component['nid']) ->condition('cid', $component['cid']) ->execute(); } /** * Respond to a Webform component being deleted. */ function hook_webform_component_delete($component) { // Delete a record in a 3rd-party module table when a component is deleted. db_delete('mymodule_table') ->condition('nid', $component['nid']) ->condition('cid', $component['cid']) ->execute(); } /** * Alter the entire analysis before rendering to the page on the Analysis tab. * * This alter hook allows modification of the entire analysis of a node's * Webform results. The resulting analysis is displayed on the Results -> * Analysis tab on the Webform. * * @param array $analysis * A Drupal renderable array, passed by reference, containing the entire * contents of the analysis page. This typically will contain the following * two major keys: * - form: The form for configuring the shown analysis. * - components: The list of analyses for each analysis-enabled component * for the node. Each keyed by its component ID. */ function hook_webform_analysis_alter(&$analysis) { $node = $analysis['#node']; // Add an additional piece of information to every component's analysis: foreach (element_children($analysis['components']) as $cid) { $component = $node->components[$cid]; $analysis['components'][$cid]['chart'] = array( '#markup' => t('Chart for the @name component', array('@name' => $component['name'])), ); } } /** * Alter data when displaying an analysis on that component. * * This hook modifies the data from an individual component's analysis results. * It can be used to add additional analysis, or to modify the existing results. * If needing to alter the entire set of analyses rather than an individual * component, hook_webform_analysis_alter() may be used instead. * * @param array $data * An array containing the result of a components analysis hook, passed by * reference. This is passed directly from a component's * _webform_analysis_component() function. See that hook for more information * on this value. * @param object $node * The node object that contains the component being analyzed. * @param array $component * The Webform component array whose analysis results are being displayed. * * @see _webform_analysis_component() * @see hook_webform_analysis_alter() */ function hook_webform_analysis_component_data_alter(&$data, $node, $component) { if ($component['type'] === 'textfield') { // Do not display rows that contain a zero value. foreach ($data as $row_number => $row_data) { if ($row_data[1] === 0) { unset($data[$row_number]); } } } } /** * Alter a Webform submission's header when exported. */ function hook_webform_csv_header_alter(&$header, $component) { // Use the machine name for component headers, but only for the webform // with node 5 and components that are text fields. if ($component['nid'] == 5 && $component['type'] == 'textfield') { $header[2] = $component['form_key']; } } /** * Alter a Webform submission's data when exported. */ function hook_webform_csv_data_alter(&$data, $component, $submission) { // If a value of a field was left blank, use the value from another // field. if ($component['cid'] == 1 && empty($data)) { $data = $submission->data[2]['value'][0]; } } /** * Define components to Webform. * * @return * An array of components, keyed by machine name. Required properties are * "label" and "description". The "features" array defines which capabilities * the component has, such as being displayed in e-mails or csv downloads. * A component like "markup" for example would not show in these locations. * The possible features of a component include: * * - csv * - email * - email_address * - email_name * - required * - conditional * - spam_analysis * - group * * Note that most of these features do not indicate the default state, but * determine if the component can have this property at all. Setting * "required" to TRUE does not mean that a component's fields will always be * required, but instead give the option to the administrator to choose the * requiredness. See the example implementation for details on how these * features may be set. * * An optional "file" may be specified to be loaded when the component is * needed. A set of callbacks will be established based on the name of the * component. All components follow the pattern: * * _webform_[callback]_[component] * * Where [component] is the name of the key of the component and [callback] is * any of the following: * * - defaults * - edit * - render * - display * - submit * - delete * - help * - theme * - analysis * - table * - csv_headers * - csv_data * * See the sample component implementation for details on each one of these * callbacks. * * @see webform_components() */ function hook_webform_component_info() { $components = array(); $components['textfield'] = array( 'label' => t('Textfield'), 'description' => t('Basic textfield type.'), 'features' => array( // This component includes an analysis callback. Defaults to TRUE. 'analysis' => TRUE, // Add content to CSV downloads. Defaults to TRUE. 'csv' => TRUE, // This component supports default values. Defaults to TRUE. 'default_value' => FALSE, // This component supports a description field. Defaults to TRUE. 'description' => FALSE, // Show this component in e-mailed submissions. Defaults to TRUE. 'email' => TRUE, // Allow this component to be used as an e-mail FROM or TO address. // Defaults to FALSE. 'email_address' => FALSE, // Allow this component to be used as an e-mail SUBJECT or FROM name. // Defaults to FALSE. 'email_name' => TRUE, // This component may be toggled as required or not. Defaults to TRUE. 'required' => TRUE, // This component supports a title attribute. Defaults to TRUE. 'title' => FALSE, // This component has a title that can be toggled as displayed or not. 'title_display' => TRUE, // This component has a title that can be displayed inline. 'title_inline' => TRUE, // If this component can be used as a conditional SOURCE. All components // may always be displayed conditionally, regardless of this setting. // Defaults to TRUE. 'conditional' => TRUE, // If this component allows other components to be grouped within it // (like a fieldset or tabs). Defaults to FALSE. 'group' => FALSE, // If this component can be used for SPAM analysis, usually with Mollom. 'spam_analysis' => FALSE, // If this component saves a file that can be used as an e-mail // attachment. Defaults to FALSE. 'attachment' => FALSE, // If this component reflects a time range and should use labels such as // "Before" and "After" when exposed as filters in Views module. 'views_range' => FALSE, ), // Specify the conditional behaviour of this component. // Examples are 'string', 'date', 'time', 'numeric', 'select'. // Defaults to 'string'. 'conditional_type' => 'string', 'file' => 'components/textfield.inc', ); return $components; } /** * Alter the list of available Webform components. * * @param $components * A list of existing components as defined by hook_webform_component_info(). * * @see hook_webform_component_info() */ function hook_webform_component_info_alter(&$components) { // Completely remove a component. unset($components['grid']); // Change the name of a component. $components['textarea']['label'] = t('Text box'); } /** * Alter the list of Webform component default values. * * @param $defaults * A list of component defaults as defined by _webform_defaults_COMPONENT(). * @param $type * The component type whose defaults are being provided. * * @see _webform_defaults_component() */ function hook_webform_component_defaults_alter(&$defaults, $type) { // Alter a default for all component types. $defaults['required'] = 1; // Add a default for a new field added via hook_form_alter() or // hook_form_FORM_ID_alter() for all component types. $defaults['extra']['added_field'] = t('Added default value'); // Add or alter defaults for specific component types: switch ($type) { case 'select': $defaults['extra']['optrand'] = 1; break; case 'textfield': case 'textarea': $defaults['extra']['another_added_field'] = t('Another added default value'); } } /** * Alter access to a Webform submission. * * @param $node * The Webform node on which this submission was made. * @param $submission * The Webform submission. * @param $op * The operation to be performed on the submission. Possible values are: * - "view" * - "edit" * - "delete" * - "list" * @param $account * A user account object. * @return * TRUE if the current user has access to submission, * or FALSE otherwise. */ function hook_webform_submission_access($node, $submission, $op = 'view', $account = NULL) { switch ($op) { case 'view': return TRUE; break; case 'edit': return FALSE; break; case 'delete': return TRUE; break; case 'list': return TRUE; break; } } /** * Determine if a user has access to see the results of a webform. * * Note in addition to the view access to the results granted here, the $account * must also have view access to the Webform node in order to see results. * Access via this hook is in addition (adds permission) to the standard * webform access. * * @see webform_results_access(). * * @param $node * The Webform node to check access on. * @param $account * The user account to check access on. * @return * TRUE or FALSE if the user can access the webform results. */ function hook_webform_results_access($node, $account) { // Let editors view results of unpublished webforms. if ($node->status == 0 && in_array('editor', $account->roles)) { return TRUE; } else { return FALSE; } } /** * Determine if a user has access to clear the results of a webform. * * Access via this hook is in addition (adds permission) to the standard * webform access (delete all webform submissions). * * @see webform_results_clear_access(). * * @param object $node * The Webform node to check access on. * @param object $account * The user account to check access on. * @return boolean * TRUE or FALSE if the user can access the webform results. */ function hook_webform_results_clear_access($node, $account) { return user_access('my additional access', $account); } /** * Overrides the node_access and user_access permission to access and edit * webform components, e-mails, conditions, and form settings. * * Return NULL to defer to other modules. If all implementations defer, then * access to the node's EDIT tab plus 'edit webform components' permission * determines access. To grant access, return TRUE; to deny access, return * FALSE. If more than one implementation return TRUE/FALSE, all must be TRUE * to grant access. * * In this way, access to the EDIT tab of the node may be decoupled from * access to the WEBFORM tab. When returning TRUE, consider all aspects of * access as this will be the only test. For example, 'return TRUE;' would grant * annonymous access to creating webform components, which seldom be desired. * * @see webform_node_update_access(). * * @param object $node * The Webform node to check access on. * @param object $account * The user account to check access on. * @return boolean|NULL * TRUE or FALSE if the user can access the webform results, or NULL if * access should be deferred to other implementations of this hook or * node_access('update') plus user_access('edit webform components'). */ function hook_webform_update_access($node, $account) { // Allow anyone who can see webform_editable_by_user nodes and who has // 'my webform component edit access' permission to see, edit, and delete the // webform components, e-mails, conditionals, and form settings. if ($node->type == 'webform_editable_by_user') { return node_access('view', $node, $account) && user_access('my webform component edit access', $account); } } /** * Return an array of files associated with the component. * * The output of this function will be used to attach files to e-mail messages. * * @param $component * A Webform component array. * @param $value * An array of information containing the submission result, directly * correlating to the webform_submitted_data database schema. * @return * An array of files, each file is an array with following keys: * - filepath: The relative path to the file. * - filename: The name of the file including the extension. * - filemime: The mimetype of the file. * This will result in an array looking something like this: * @code * array[0] => array( * 'filepath' => '/sites/default/files/attachment.txt', * 'filename' => 'attachment.txt', * 'filemime' => 'text/plain', * ); * @endcode */ function _webform_attachments_component($component, $value) { $files = array(); $files[] = (array) file_load($value[0]); return $files; } /** * Alter default settings for a newly created webform node. * * @param array $defaults * Default settings for a newly created webform node as defined by webform_node_defaults(). * * @see webform_node_defaults() */ function hook_webform_node_defaults_alter(&$defaults) { $defaults['allow_draft'] = '1'; } /** * Add additional fields to submission data downloads. * * @return * Keys and titles for default submission information. * * @see hook_webform_results_download_submission_information_data() */ function hook_webform_results_download_submission_information_info() { return array( 'field_key_1' => t('Field Title 1'), 'field_key_2' => t('Field Title 2'), ); } /** * Return values for submission data download fields. * * @param $token * The name of the token being replaced. * @param $submission * The data for an individual submission from webform_get_submissions(). * @param $options * A list of options that define the output format. These are generally passed * through from the GUI interface. * @param $serial_start * The starting position for the Serial column in the output. * @param $row_count * The number of the row being generated. * * @return * Value for requested submission information field. * * @see hook_webform_results_download_submission_information_info() */ function hook_webform_results_download_submission_information_data($token, $submission, array $options, $serial_start, $row_count) { switch ($token) { case 'field_key_1': return 'Field Value 1'; case 'field_key_2': return 'Field Value 2'; } } /** * @} */ /** * @defgroup webform_component Sample Webform Component * @{ * In each of these examples, the word "component" should be replaced with the, * name of the component type (such as textfield or select). These are not * actual hooks, but instead samples of how Webform integrates with its own * built-in components. */ /** * Specify the default properties of a component. * * @return * An array defining the default structure of a component. */ function _webform_defaults_component() { return array( 'name' => '', 'form_key' => NULL, 'required' => 0, 'pid' => 0, 'weight' => 0, 'extra' => array( 'options' => '', 'questions' => '', 'optrand' => 0, 'qrand' => 0, 'description' => '', 'private' => FALSE, 'analysis' => TRUE, ), ); } /** * Generate the form for editing a component. * * Create a set of form elements to be displayed on the form for editing this * component. Use care naming the form items, as this correlates directly to the * database schema. The component "Name" and "Description" fields are added to * every component type and are not necessary to specify here (although they * may be overridden if desired). * * @param $component * A Webform component array. * @return * An array of form items to be displayed on the edit component page */ function _webform_edit_component($component) { $form = array(); // Disabling the description if not wanted. $form['description'] = array(); // Most options are stored in the "extra" array, which stores any settings // unique to a particular component type. $form['extra']['options'] = array( '#type' => 'textarea', '#title' => t('Options'), '#default_value' => $component['extra']['options'], '#description' => t('Key-value pairs may be entered separated by pipes. i.e. safe_key|Some readable option') . ' ' . theme('webform_token_help'), '#cols' => 60, '#rows' => 5, '#weight' => -3, '#required' => TRUE, ); return $form; } /** * Render a Webform component to be part of a form. * * @param $component * A Webform component array. * @param $value * If editing an existing submission or resuming a draft, this will contain * an array of values to be shown instead of the default in the component * configuration. This value will always be an array, keyed numerically for * each value saved in this field. * @param $filter * Whether or not to filter the contents of descriptions and values when * rendering the component. Values need to be unfiltered to be editable by * Form Builder. * @param $submission * The submission from which this component is being rendered. Usually not * needed. Used by _webform_render_date() to validate using the submission's * completion date. * * @see _webform_client_form_add_component() */ function _webform_render_component($component, $value = NULL, $filter = TRUE, $submission = NULL) { $form_item = array( '#type' => 'textfield', '#title' => $filter ? webform_filter_xss($component['name']) : $component['name'], '#required' => $component['required'], '#weight' => $component['weight'], '#description' => $filter ? webform_filter_descriptions($component['extra']['description']) : $component['extra']['description'], '#default_value' => $filter ? webform_replace_tokens($component['value']) : $component['value'], '#prefix' => '<div class="webform-component-textfield" id="webform-component-' . $component['form_key'] . '">', '#suffix' => '</div>', ); if (isset($value)) { $form_item['#default_value'] = $value[0]; } return $form_item; } /** * Allow modules to modify a webform component that is going to be rendered in a form. * * @param array $element * The display element as returned by _webform_render_component(). * @param array $component * A Webform component array. * * @see _webform_render_component() */ function hook_webform_component_render_alter(&$element, &$component) { if ($component['cid'] == 10) { $element['#title'] = 'My custom title'; $element['#default_value'] = 42; } } /** * Display the result of a submission for a component. * * The output of this function will be displayed under the "Results" tab then * "Submissions". This should output the saved data in some reasonable manner. * * @param $component * A Webform component array. * @param $value * An array of information containing the submission result, directly * correlating to the webform_submitted_data database table schema. * @param $format * Either 'html' or 'text'. Defines the format that the content should be * returned as. Make sure that returned content is run through check_plain() * or other filtering functions when returning HTML. * @return * A renderable element containing at the very least these properties: * - #title * - #weight * - #component * - #format * - #value * Webform also uses #theme_wrappers to output the end result to the user, * which will properly format the label and content for use within an e-mail * (such as wrapping the text) or as HTML (ensuring consistent output). */ function _webform_display_component($component, $value, $format = 'html') { return array( '#title' => $component['name'], '#weight' => $component['weight'], '#theme' => 'webform_display_textfield', '#theme_wrappers' => $format == 'html' ? array('webform_element') : array('webform_element_text'), '#post_render' => array('webform_element_wrapper'), '#field_prefix' => $component['extra']['field_prefix'], '#field_suffix' => $component['extra']['field_suffix'], '#component' => $component, '#format' => $format, '#value' => isset($value[0]) ? $value[0] : '', ); } /** * Allow modules to modify a "display only" webform component. * * @param array $element * The display element as returned by _webform_display_component(). * @param array $component * A Webform component array. * * @see _webform_display_component() */ function hook_webform_component_display_alter(&$element, &$component) { if ($component['cid'] == 10) { $element['#title'] = 'My custom title'; $element['#default_value'] = 42; } } /** * A hook for changing the input values before saving to the database. * * Webform expects a component to consist of a single field, or a single array * of fields. If you have a component that requires a deeper form tree * you must flatten the data into a single array using this callback * or by setting #parents on each field to avoid data loss and/or unexpected * behavior. * * Note that Webform will save the result of this function directly into the * database. * * @param $component * A Webform component array. * @param $value * The POST data associated with the user input. * @return * An array of values to be saved into the database. Note that this should be * a numerically keyed array. */ function _webform_submit_component($component, $value) { // Clean up a phone number into 123-456-7890 format. if ($component['extra']['phone_number']) { $number = preg_replace('/[^0-9]/', '', $value[0]); if (strlen($number) == 7) { $number = substr($number, 0, 3) . '-' . substr($number, 3, 4); } else { $number = substr($number, 0, 3) . '-' . substr($number, 3, 3) . '-' . substr($number, 6, 4); } } $value[0] = $number; return $value; } /** * Delete operation for a component or submission. * * @param $component * A Webform component array. * @param $value * An array of information containing the submission result, directly * correlating to the webform_submitted_data database schema. */ function _webform_delete_component($component, $value) { // Delete corresponding files when a submission is deleted. if (!empty($value[0]) && ($file = webform_get_file($value[0]))) { file_usage_delete($file, 'webform'); file_delete($file); } } /** * Module specific instance of hook_help(). * * This allows each Webform component to add information into hook_help(). */ function _webform_help_component($section) { switch ($section) { case 'admin/config/content/webform#grid_description': return t('Allows creation of grid questions, denoted by radio buttons.'); } } /** * Module specific instance of hook_theme(). * * This allows each Webform component to add information into hook_theme(). If * you specify a file to include, you must define the path to the module that * this file belongs to. */ function _webform_theme_component() { return array( 'webform_grid' => array( 'render element' => 'element', 'file' => 'components/grid.inc', 'path' => drupal_get_path('module', 'webform'), ), 'webform_display_grid' => array( 'render element' => 'element', 'file' => 'components/grid.inc', 'path' => drupal_get_path('module', 'webform'), ), ); } /** * Calculate and returns statistics about results for this component. * * This takes into account all submissions to this webform. The output of this * function will be displayed under the "Results" tab then "Analysis". * * @param $component * An array of information describing the component, directly correlating to * the webform_component database schema. * @param $sids * An optional array of submission IDs (sid). If supplied, the analysis will * be limited to these sids. * @param $single * Boolean flag determining if the details about a single component are being * shown. May be used to provided detailed information about a single * component's analysis, such as showing "Other" options within a select list. * @param $join * An optional SelectQuery object to be used to join with the submissions * table to restrict the submissions being analyzed. * @return * An array containing one or more of the following keys: * - table_rows: If this component has numeric data that can be represented in * a grid, return the values here. This array assumes a 2-dimensional * structure, with the first value being a label and subsequent values * containing a decimal or integer. * - table_header: If this component has more than a single set of values, * include a table header so each column can be labeled. * - other_data: If your component has non-numeric data to include, such as * a description or link, include that in the other_data array. Each item * may be a string or an array of values that matches the number of columns * in the table_header property. * At the very least, either table_rows or other_data should be provided. * Note that if you want your component's analysis to be available by default * without the user specifically enabling it, you must set * $component['extra']['analysis'] = TRUE in your * _webform_defaults_component() callback. * * @see _webform_defaults_component() */ function _webform_analysis_component($component, $sids = array(), $single = FALSE, $join = NULL) { // Generate the list of options and questions. $options = _webform_select_options_from_text($component['extra']['options'], TRUE); $questions = _webform_select_options_from_text($component['extra']['questions'], TRUE); // Generate a lookup table of results. $query = db_select('webform_submitted_data', 'wsd') ->fields('wsd', array('no', 'data')) ->condition('nid', $component['nid']) ->condition('cid', $component['cid']) ->condition('data', '', '<>') ->groupBy('no') ->groupBy('data'); $query->addExpression('COUNT(sid)', 'datacount'); if (count($sids)) { $query->condition('sid', $sids, 'IN'); } if ($join) { $query->innerJoin($join, 'ws2_', 'wsd.sid = ws2_.sid'); } $result = $query->execute(); $counts = array(); foreach ($result as $data) { $counts[$data->no][$data->data] = $data->datacount; } // Create an entire table to be put into the returned row. $rows = array(); $header = array(''); // Add options as a header row. foreach ($options as $option) { $header[] = $option; } // Add questions as each row. foreach ($questions as $qkey => $question) { $row = array($question); foreach ($options as $okey => $option) { $row[] = !empty($counts[$qkey][$okey]) ? $counts[$qkey][$okey] : 0; } $rows[] = $row; } $other = array(); $other[] = l(t('More information'), 'node/' . $component['nid'] . '/webform-results/analysis/' . $component['cid']); return array( 'table_header' => $header, 'table_rows' => $rows, 'other_data' => $other, ); } /** * Return the result of a component value for display in a table. * * The output of this function will be displayed under the "Results" tab then * "Table". * * @param $component * A Webform component array. * @param $value * An array of information containing the submission result, directly * correlating to the webform_submitted_data database schema. * @return * Textual output formatted for human reading. */ function _webform_table_component($component, $value) { $questions = array_values(_webform_component_options($component['extra']['questions'])); $output = ''; // Set the value as a single string. if (is_array($value)) { foreach ($value as $item => $value) { if ($value !== '') { $output .= $questions[$item] . ': ' . check_plain($value) . '<br />'; } } } else { $output = check_plain(!isset($value['0']) ? '' : $value['0']); } return $output; } /** * Return the header for this component to be displayed in a CSV file. * * The output of this function will be displayed under the "Results" tab then * "Download". * * @param $component * A Webform component array. * @param $export_options * An array of options that may configure export of this field. * @return * An array of data to be displayed in the first three rows of a CSV file, not * including either prefixed or trailing commas. */ function _webform_csv_headers_component($component, $export_options) { $header = array(); $header[0] = array(''); $header[1] = array($export_options['header_keys'] ? $component['form_key'] : $component['name']); $items = _webform_component_options($component['extra']['questions']); $count = 0; foreach ($items as $key => $item) { // Empty column per sub-field in main header. if ($count != 0) { $header[0][] = ''; $header[1][] = ''; } // The value for this option. $header[2][] = $item; $count++; } return $header; } /** * Format the submitted data of a component for CSV downloading. * * The output of this function will be displayed under the "Results" tab then * "Download". * * @param $component * A Webform component array. * @param $export_options * An array of options that may configure export of this field. * @param $value * An array of information containing the submission result, directly * correlating to the webform_submitted_data database schema. * @return * An array of items to be added to the CSV file. Each value within the array * will be another column within the file. This function is called once for * every row of data. */ function _webform_csv_data_component($component, $export_options, $value) { $questions = array_keys(_webform_select_options($component['extra']['questions'])); $return = array(); foreach ($questions as $key => $question) { $return[] = isset($value[$key]) ? $value[$key] : ''; } return $return; } /** * Adjusts the view field(s) that are automatically generated for number * components. * * Provides each component the opportunity to adjust how this component is * displayed in a view as a field in a view table. For example, a component may * modify how it responds to click-sorting. Or it may add additional fields, * such as a grid component having a column for each question. * * @param array $component * A Webform component array * @param array $fields * An array of field-definition arrays. Will be passed one field definition, * which may be modified. Additional fields may be added to the array. * @return array * The modified $fields array. */ function _webform_view_field_component($component, $fields) { foreach ($fields as &$field) { $field['webform_datatype'] = 'number'; } return $fields; } /** * Modify the how a view was expanded to show all the components. * * This alter function is only called when the view is actually modified. It * provides modules an opportunity to alter the changes that webform made to * the view. * * This hook is called from webform_views_pre_view. If another module also * changes views by implementing this same views hook, the relative order of * execution of the two implementations will depend upon the module weights of * the two modules. Using hook_webform_view_alter instead guarantees an * opportuinty to modify the view AFTER webform. * * @param object $view * The view object. * @param string $display_id * The display_id that was expanded by webform. * @param array $args * The argumentst that were passed to the view. */ function hook_webform_view_alter($view, $display_id, $args) { // Don't show component with cid == 4 $fields = $view->get_items('field', $display_id); foreach ($fields as $id => $field) { if (isset($field['webform_cid']) && $field['webform_cid'] == 4) { unset($fields[$id]); } } $view->display[$display_id]->handler->set_option('fields', $fields); } /** * Modify the list of mail systems that are capable of sending HTML email. * * @param array &$systems * An array of mail system class names. */ function hook_webform_html_capable_mail_systems_alter(&$systems) { if (module_exists('my_module')) { $systems[] = 'MyModuleMailSystem'; } } /** * @} */
nandoalvarado022/colombianime
sitios/inmobiliaria/sites/all/modules/webform/webform.api.php
PHP
gpl-2.0
44,278
<?php /** * Social Login * * @version 1.0 * @author SmokerMan, Arkadiy, Joomline * @copyright © 2012. All rights reserved. * @license GNU/GPL v.3 or later. */ // защита от прямого доступа defined('_JEXEC') or die('@-_-@'); jimport('joomla.form.formfield'); class JFormFieldCallbackUrl extends JFormField { /** * The form field type. * * @var string * @since 1.6 */ public $type = 'CallbackUrl'; /** * Method to get the field input markup. * * @return string The field input markup. * @since 1.6 */ protected function getInput() { $task = !empty($this->element['value']) ? '?option=com_slogin&task=check&plugin=' . (string) $this->element['value'] : ''; $readonly = ((string) $this->element['readonly'] == 'true') ? ' readonly="readonly"' : ''; $class = $this->element['class'] ? ' class="' . (string) $this->element['class'] . '"' : ''; $CallbackUrl = JURI::root().$task; if(substr($CallbackUrl, -1, 1) == '/'){ $CallbackUrl = substr($CallbackUrl, 0, -1); } $html = '<input type="text" name="' . $this->name . '" id="' . $this->id . '"' . ' value="'.$CallbackUrl.'" size="70%" '. $class . $readonly .' />'; return $html; } }
IYEO/Sweettaste
tmp/install_5680f69da1732/install_5680f6ad8ef2b/element/callbackurl.php
PHP
gpl-2.0
1,284
# $Id: admonitions.py 7681 2013-07-12 07:52:27Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Admonition directives. """ __docformat__ = 'reStructuredText' from docutils.parsers.rst import Directive from docutils.parsers.rst import states, directives from docutils.parsers.rst.roles import set_classes from docutils import nodes class BaseAdmonition(Directive): final_argument_whitespace = True option_spec = {'class': directives.class_option, 'name': directives.unchanged} has_content = True node_class = None """Subclasses must set this to the appropriate admonition node class.""" def run(self): set_classes(self.options) self.assert_has_content() text = '\n'.join(self.content) admonition_node = self.node_class(text, **self.options) self.add_name(admonition_node) if self.node_class is nodes.admonition: title_text = self.arguments[0] textnodes, messages = self.state.inline_text(title_text, self.lineno) title = nodes.title(title_text, '', *textnodes) title.source, title.line = ( self.state_machine.get_source_and_line(self.lineno)) admonition_node += title admonition_node += messages if not 'classes' in self.options: admonition_node['classes'] += ['admonition-' + nodes.make_id(title_text)] self.state.nested_parse(self.content, self.content_offset, admonition_node) return [admonition_node] class Admonition(BaseAdmonition): required_arguments = 1 node_class = nodes.admonition class Attention(BaseAdmonition): node_class = nodes.attention class Caution(BaseAdmonition): node_class = nodes.caution class Danger(BaseAdmonition): node_class = nodes.danger class Error(BaseAdmonition): node_class = nodes.error class Hint(BaseAdmonition): node_class = nodes.hint class Important(BaseAdmonition): node_class = nodes.important class Note(BaseAdmonition): node_class = nodes.note class Tip(BaseAdmonition): node_class = nodes.tip class Warning(BaseAdmonition): node_class = nodes.warning
JulienMcJay/eclock
windows/Python27/Lib/site-packages/docutils/parsers/rst/directives/admonitions.py
Python
gpl-2.0
2,413
class Blazeblogger < Formula desc "CMS for the command-line" homepage "http://blaze.blackened.cz/" url "https://blazeblogger.googlecode.com/files/blazeblogger-1.2.0.tar.gz" sha1 "280894fca6594d0c0df925aa0a16b9116ee19f17" bottle do cellar :any sha1 "2576ceff864dd2059bcd73af26f735725dd7274c" => :yosemite sha1 "068b94d384d5820938c4561df7357ae116bf23c4" => :mavericks sha1 "da491de4ea179354dcb8345b244d36fec30c0c6a" => :mountain_lion end def install # https://code.google.com/p/blazeblogger/issues/detail?id=51 ENV.deparallelize system "make", "prefix=#{prefix}", "compdir=#{prefix}", "install" end test do system bin/"blaze", "init" system bin/"blaze", "config", "blog.title", "Homebrew!" system bin/"blaze", "make" assert File.exist? "default.css" assert File.read(".blaze/config").include?("Homebrew!") end end
kyanny/homebrew
Library/Formula/blazeblogger.rb
Ruby
bsd-2-clause
883
require 'formula' class Mad < Formula desc "MPEG audio decoder" homepage 'http://www.underbit.com/products/mad/' url 'https://downloads.sourceforge.net/project/mad/libmad/0.15.1b/libmad-0.15.1b.tar.gz' sha1 'cac19cd00e1a907f3150cc040ccc077783496d76' bottle do cellar :any revision 1 sha1 "ec696978cd2bbd43ed11b6b1d3b78156d2b97c71" => :yosemite sha1 "b8ea86acc3a5aab051e7df3d6e1b00ac1acac346" => :mavericks sha1 "7164d878d4467cda6bbed49fd46129a4ae3169ec" => :mountain_lion end def install fpm = MacOS.prefer_64_bit? ? '64bit': 'intel' system "./configure", "--disable-debugging", "--enable-fpm=#{fpm}", "--prefix=#{prefix}" system "make", "CFLAGS=#{ENV.cflags}", "LDFLAGS=#{ENV.ldflags}", "install" (lib+'pkgconfig/mad.pc').write pc_file end def pc_file; <<-EOS.undent prefix=#{opt_prefix} exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include Name: mad Description: MPEG Audio Decoder Version: #{version} Requires: Conflicts: Libs: -L${libdir} -lmad -lm Cflags: -I${includedir} EOS end end
karlhigley/homebrew
Library/Formula/mad.rb
Ruby
bsd-2-clause
1,122
import { constant } from "../fp"; export = constant;
BigBoss424/portfolio
v8/development/node_modules/@types/lodash/ts3.1/fp/constant.d.ts
TypeScript
apache-2.0
53
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package java.nio; import com.google.gwt.typedarrays.shared.ArrayBufferView; import com.google.gwt.typedarrays.shared.Float32Array; import com.google.gwt.typedarrays.shared.TypedArrays; /** This class wraps a byte buffer to be a float buffer. * <p> * Implementation notice: * <ul> * <li>After a byte buffer instance is wrapped, it becomes privately owned by the adapter. It must NOT be accessed outside the * adapter any more.</li> * <li>The byte buffer's position and limit are NOT linked with the adapter. The adapter extends Buffer, thus has its own position * and limit.</li> * </ul> * </p> */ final class DirectReadWriteFloatBufferAdapter extends FloatBuffer implements HasArrayBufferView { // implements DirectBuffer { static FloatBuffer wrap (DirectReadWriteByteBuffer byteBuffer) { return new DirectReadWriteFloatBufferAdapter((DirectReadWriteByteBuffer)byteBuffer.slice()); } private final DirectReadWriteByteBuffer byteBuffer; private final Float32Array floatArray; DirectReadWriteFloatBufferAdapter (DirectReadWriteByteBuffer byteBuffer) { super((byteBuffer.capacity() >> 2)); this.byteBuffer = byteBuffer; this.byteBuffer.clear(); this.floatArray = TypedArrays.createFloat32Array(byteBuffer.byteArray.buffer(), byteBuffer.byteArray.byteOffset(), capacity); } // TODO(haustein) This will be slow @Override public FloatBuffer asReadOnlyBuffer () { DirectReadOnlyFloatBufferAdapter buf = new DirectReadOnlyFloatBufferAdapter(byteBuffer); buf.limit = limit; buf.position = position; buf.mark = mark; return buf; } @Override public FloatBuffer compact () { byteBuffer.limit(limit << 2); byteBuffer.position(position << 2); byteBuffer.compact(); byteBuffer.clear(); position = limit - position; limit = capacity; mark = UNSET_MARK; return this; } @Override public FloatBuffer duplicate () { DirectReadWriteFloatBufferAdapter buf = new DirectReadWriteFloatBufferAdapter( (DirectReadWriteByteBuffer)byteBuffer.duplicate()); buf.limit = limit; buf.position = position; buf.mark = mark; return buf; } @Override public float get () { // if (position == limit) { // throw new BufferUnderflowException(); // } return floatArray.get(position++); } @Override public float get (int index) { // if (index < 0 || index >= limit) { // throw new IndexOutOfBoundsException(); // } return floatArray.get(index); } @Override public boolean isDirect () { return true; } @Override public boolean isReadOnly () { return false; } @Override public ByteOrder order () { return byteBuffer.order(); } @Override protected float[] protectedArray () { throw new UnsupportedOperationException(); } @Override protected int protectedArrayOffset () { throw new UnsupportedOperationException(); } @Override protected boolean protectedHasArray () { return false; } @Override public FloatBuffer put (float c) { // if (position == limit) { // throw new BufferOverflowException(); // } floatArray.set(position++, c); return this; } @Override public FloatBuffer put (int index, float c) { // if (index < 0 || index >= limit) { // throw new IndexOutOfBoundsException(); // } floatArray.set(index, c); return this; } @Override public FloatBuffer slice () { byteBuffer.limit(limit << 2); byteBuffer.position(position << 2); FloatBuffer result = new DirectReadWriteFloatBufferAdapter((DirectReadWriteByteBuffer)byteBuffer.slice()); byteBuffer.clear(); return result; } public ArrayBufferView getTypedArray () { return floatArray; } public int getElementSize () { return 4; } }
nelsonsilva/libgdx
backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadWriteFloatBufferAdapter.java
Java
apache-2.0
4,412
/** * @module Ink.UI.DatePicker_1 * @version 1 * Date selector */ Ink.createModule('Ink.UI.DatePicker', '1', ['Ink.UI.Common_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1','Ink.Util.Array_1','Ink.Util.Date_1', 'Ink.Dom.Browser_1'], function(Common, Event, Css, InkElement, Selector, InkArray, InkDate ) { 'use strict'; // Repeat a string. Long version of (new Array(n)).join(str); function strRepeat(n, str) { var ret = ''; for (var i = 0; i < n; i++) { ret += str; } return ret; } // Clamp a number into a min/max limit function clamp(n, min, max) { if (n > max) { n = max; } if (n < min) { n = min; } return n; } function dateishFromYMDString(YMD) { var split = YMD.split('-'); return dateishFromYMD(+split[0], +split[1] - 1, +split[2]); } function dateishFromYMD(year, month, day) { return {_year: year, _month: month, _day: day}; } function dateishFromDate(date) { return {_year: date.getFullYear(), _month: date.getMonth(), _day: date.getDate()}; } /** * @class Ink.UI.DatePicker * @constructor * @version 1 * * @param {String|DOMElement} selector * @param {Object} [options] Options * @param {Boolean} [options.autoOpen] Flag to automatically open the datepicker. * @param {String} [options.cleanText] Text for the clean button. Defaults to 'Limpar'. * @param {String} [options.closeText] Text for the close button. Defaults to 'Fechar'. * @param {String} [options.cssClass] CSS class to be applied on the datepicker * @param {String} [options.dateRange] Enforce limits to year, month and day for the Date, ex: '1990-08-25:2020-11' * @param {Boolean} [options.displayInSelect] Flag to display the component in a select element. * @param {String|DOMElement} [options.dayField] (if using options.displayInSelect) `select` field with days. * @param {String|DOMElement} [options.monthField] (if using options.displayInSelect) `select` field with months. * @param {String|DOMElement} [options.yearField] (if using options.displayInSelect) `select` field with years. * @param {String} [options.format] Date format string * @param {String} [options.instance] Unique id for the datepicker * @param {Object} [options.month] Hash of month names. Defaults to portuguese month names. January is 1. * @param {String} [options.nextLinkText] Text for the previous button. Defaults to '«'. * @param {String} [options.ofText] Text to show between month and year. Defaults to ' of '. * @param {Boolean} [options.onFocus] If the datepicker should open when the target element is focused. Defaults to true. * @param {Function} [options.onMonthSelected] Callback to execute when the month is selected. * @param {Function} [options.onSetDate] Callback to execute when the date is set. * @param {Function} [options.onYearSelected] Callback to execute when the year is selected. * @param {String} [options.position] Position for the datepicker. Either 'right' or 'bottom'. Defaults to 'right'. * @param {String} [options.prevLinkText] Text for the previous button. Defaults to '«'. * @param {Boolean} [options.showClean] If the clean button should be visible. Defaults to true. * @param {Boolean} [options.showClose] If the close button should be visible. Defaults to true. * @param {Boolean} [options.shy] If the datepicker should start automatically. Defaults to true. * @param {String} [options.startDate] Date to define initial month. Must be in yyyy-mm-dd format. * @param {Number} [options.startWeekDay] First day of the week. Sunday is zero. Defaults to 1 (Monday). * @param {Function} [options.validYearFn] Callback to execute when 'rendering' the month (in the month view) * @param {Function} [options.validMonthFn] Callback to execute when 'rendering' the month (in the month view) * @param {Function} [options.validDayFn] Callback to execute when 'rendering' the day (in the month view) * @param {Function} [options.nextValidDateFn] Function to calculate the next valid date, given the current. Useful when there's invalid dates or time frames. * @param {Function} [options.prevValidDateFn] Function to calculate the previous valid date, given the current. Useful when there's invalid dates or time frames. * @param {Object} [options.wDay] Hash of weekdays. Defaults to portuguese names. Sunday is 0. * @param {String} [options.yearRange] Enforce limits to year for the Date, ex: '1990:2020' (deprecated) * * @sample Ink_UI_DatePicker_1.html */ var DatePicker = function(selector, options) { this._element = selector && Common.elOrSelector(selector, '[Ink.UI.DatePicker_1]: selector argument'); this._options = Common.options('Ink.UI.DatePicker_1', { autoOpen: ['Boolean', false], cleanText: ['String', 'Clear'], closeText: ['String', 'Close'], containerElement:['Element', null], cssClass: ['String', 'ink-calendar bottom'], dateRange: ['String', null], // use this in a <select> displayInSelect: ['Boolean', false], dayField: ['Element', null], monthField: ['Element', null], yearField: ['Element', null], format: ['String', 'yyyy-mm-dd'], instance: ['String', 'scdp_' + Math.round(99999 * Math.random())], nextLinkText: ['String', '»'], ofText: ['String', ' de '], onFocus: ['Boolean', true], onMonthSelected: ['Function', null], onSetDate: ['Function', null], onYearSelected: ['Function', null], position: ['String', 'right'], prevLinkText: ['String', '«'], showClean: ['Boolean', true], showClose: ['Boolean', true], shy: ['Boolean', true], startDate: ['String', null], // format yyyy-mm-dd, startWeekDay: ['Number', 1], // Validation validDayFn: ['Function', null], validMonthFn: ['Function', null], validYearFn: ['Function', null], nextValidDateFn: ['Function', null], prevValidDateFn: ['Function', null], yearRange: ['String', null], // Text month: ['Object', { 1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June', 7:'July', 8:'August', 9:'September', 10:'October', 11:'November', 12:'December' }], wDay: ['Object', { 0:'Sunday', 1:'Monday', 2:'Tuesday', 3:'Wednesday', 4:'Thursday', 5:'Friday', 6:'Saturday' }] }, options || {}, this._element); this._options.format = this._dateParsers[ this._options.format ] || this._options.format; this._hoverPicker = false; this._picker = this._options.pickerField && Common.elOrSelector(this._options.pickerField, 'pickerField'); this._setMinMax( this._options.dateRange || this._options.yearRange ); if(this._options.startDate) { this.setDate( this._options.startDate ); } else if (this._element && this._element.value) { this.setDate( this._element.value ); } else { var today = new Date(); this._day = today.getDate( ); this._month = today.getMonth( ); this._year = today.getFullYear( ); } if (this._options.startWeekDay < 0 || this._options.startWeekDay > 6) { Ink.warn('Ink.UI.DatePicker_1: option "startWeekDay" must be between 0 (sunday) and 6 (saturday)'); this._options.startWeekDay = clamp(this._options.startWeekDay, 0, 6); } if(this._options.displayInSelect && !(this._options.dayField && this._options.monthField && this._options.yearField)){ throw new Error( 'Ink.UI.DatePicker: displayInSelect option enabled.'+ 'Please specify dayField, monthField and yearField selectors.'); } this._init(); }; DatePicker.prototype = { version: '0.1', /** * Initialization function. Called by the constructor and receives the same parameters. * * @method _init * @private */ _init: function(){ Ink.extendObj(this._options,this._lang || {}); this._render(); this._listenToContainerObjectEvents(); Common.registerInstance(this, this._containerObject, 'datePicker'); }, /** * Renders the DatePicker's markup. * * @method _render * @private */ _render: function() { this._containerObject = document.createElement('div'); this._containerObject.id = this._options.instance; this._containerObject.className = this._options.cssClass + ' ink-datepicker-calendar hide-all'; this._renderSuperTopBar(); var calendarTop = document.createElement("div"); calendarTop.className = 'ink-calendar-top'; this._monthDescContainer = document.createElement("div"); this._monthDescContainer.className = 'ink-calendar-month_desc'; this._monthPrev = document.createElement('div'); this._monthPrev.className = 'ink-calendar-prev'; this._monthPrev.innerHTML ='<a href="#prev" class="change_month_prev">' + this._options.prevLinkText + '</a>'; this._monthNext = document.createElement('div'); this._monthNext.className = 'ink-calendar-next'; this._monthNext.innerHTML ='<a href="#next" class="change_month_next">' + this._options.nextLinkText + '</a>'; calendarTop.appendChild(this._monthPrev); calendarTop.appendChild(this._monthDescContainer); calendarTop.appendChild(this._monthNext); this._monthContainer = document.createElement("div"); this._monthContainer.className = 'ink-calendar-month'; this._containerObject.appendChild(calendarTop); this._containerObject.appendChild(this._monthContainer); this._monthSelector = this._renderMonthSelector(); this._containerObject.appendChild(this._monthSelector); this._yearSelector = document.createElement('ul'); this._yearSelector.className = 'ink-calendar-year-selector'; this._containerObject.appendChild(this._yearSelector); if(!this._options.onFocus || this._options.displayInSelect){ if(!this._options.pickerField){ this._picker = document.createElement('a'); this._picker.href = '#open_cal'; this._picker.innerHTML = 'open'; this._element.parentNode.appendChild(this._picker); this._picker.className = 'ink-datepicker-picker-field'; } else { this._picker = Common.elOrSelector(this._options.pickerField, 'pickerField'); } } this._appendDatePickerToDom(); this._renderMonth(); this._monthChanger = document.createElement('a'); this._monthChanger.href = '#monthchanger'; this._monthChanger.className = 'ink-calendar-link-month'; this._monthChanger.innerHTML = this._options.month[this._month + 1]; this._ofText = document.createElement('span'); this._ofText.innerHTML = this._options.ofText; this._yearChanger = document.createElement('a'); this._yearChanger.href = '#yearchanger'; this._yearChanger.className = 'ink-calendar-link-year'; this._yearChanger.innerHTML = this._year; this._monthDescContainer.innerHTML = ''; this._monthDescContainer.appendChild(this._monthChanger); this._monthDescContainer.appendChild(this._ofText); this._monthDescContainer.appendChild(this._yearChanger); if (!this._options.inline) { this._addOpenCloseEvents(); } else { this.show(); } this._addDateChangeHandlersToInputs(); }, _addDateChangeHandlersToInputs: function () { var fields = this._element; if (this._options.displayInSelect) { fields = [ this._options.dayField, this._options.monthField, this._options.yearField]; } Event.observeMulti(fields ,'change', Ink.bindEvent(function(){ this._updateDate( ); this._showDefaultView( ); this.setDate( ); if ( !this._inline && !this._hoverPicker ) { this._hide(true); } },this)); }, /** * Shows the calendar. * * @method show **/ show: function () { this._updateDate(); this._renderMonth(); Css.removeClassName(this._containerObject, 'hide-all'); }, _addOpenCloseEvents: function () { var opener = this._picker || this._element; Event.observe(opener, 'click', Ink.bindEvent(function(e){ Event.stop(e); this.show(); },this)); if (this._options.autoOpen) { this.show(); } if(!this._options.displayInSelect){ Event.observe(opener, 'blur', Ink.bindEvent(function() { if ( !this._hoverPicker ) { this._hide(true); } },this)); } if (this._options.shy) { // Close the picker when clicking elsewhere. Event.observe(document,'click',Ink.bindEvent(function(e){ var target = Event.element(e); // "elsewhere" is outside any of these elements: var cannotBe = [ this._options.dayField, this._options.monthField, this._options.yearField, this._picker, this._element ]; for (var i = 0, len = cannotBe.length; i < len; i++) { if (cannotBe[i] && InkElement.descendantOf(cannotBe[i], target)) { return; } } this._hide(true); },this)); } }, /** * Creates the markup of the view with months. * * @method _renderMonthSelector * @private */ _renderMonthSelector: function () { var selector = document.createElement('ul'); selector.className = 'ink-calendar-month-selector'; var ulSelector = document.createElement('ul'); for(var mon=1; mon<=12; mon++){ ulSelector.appendChild(this._renderMonthButton(mon)); if (mon % 4 === 0) { selector.appendChild(ulSelector); ulSelector = document.createElement('ul'); } } return selector; }, /** * Renders a single month button. */ _renderMonthButton: function (mon) { var liMonth = document.createElement('li'); var aMonth = document.createElement('a'); aMonth.setAttribute('data-cal-month', mon); aMonth.innerHTML = this._options.month[mon].substring(0,3); liMonth.appendChild(aMonth); return liMonth; }, _appendDatePickerToDom: function () { if(this._options.containerElement) { var appendTarget = Ink.i(this._options.containerElement) || // [2.3.0] maybe id; small backwards compatibility thing Common.elOrSelector(this._options.containerElement); appendTarget.appendChild(this._containerObject); } if (InkElement.findUpwardsBySelector(this._element, '.ink-form .control-group .control') === this._element.parentNode) { // [3.0.0] Check if the <input> must be a direct child of .control, and if not, remove this block. this._wrapper = this._element.parentNode; this._wrapperIsControl = true; } else { this._wrapper = InkElement.create('div', { className: 'ink-datepicker-wrapper' }); InkElement.wrap(this._element, this._wrapper); } InkElement.insertAfter(this._containerObject, this._element); }, /** * Render the topmost bar with the "close" and "clear" buttons. */ _renderSuperTopBar: function () { if((!this._options.showClose) || (!this._options.showClean)){ return; } this._superTopBar = document.createElement("div"); this._superTopBar.className = 'ink-calendar-top-options'; if(this._options.showClean){ this._superTopBar.appendChild(InkElement.create('a', { className: 'clean', setHTML: this._options.cleanText })); } if(this._options.showClose){ this._superTopBar.appendChild(InkElement.create('a', { className: 'close', setHTML: this._options.closeText })); } this._containerObject.appendChild(this._superTopBar); }, _listenToContainerObjectEvents: function () { Event.observe(this._containerObject,'mouseover',Ink.bindEvent(function(e){ Event.stop( e ); this._hoverPicker = true; },this)); Event.observe(this._containerObject,'mouseout',Ink.bindEvent(function(e){ Event.stop( e ); this._hoverPicker = false; },this)); Event.observe(this._containerObject,'click',Ink.bindEvent(this._onClick, this)); }, _onClick: function(e){ var elem = Event.element(e); if (Css.hasClassName(elem, 'ink-calendar-off')) { Event.stopDefault(e); return null; } Event.stop(e); // Relative changers this._onRelativeChangerClick(elem); // Absolute changers this._onAbsoluteChangerClick(elem); // Mode changers if (Css.hasClassName(elem, 'ink-calendar-link-month')) { this._showMonthSelector(); } else if (Css.hasClassName(elem, 'ink-calendar-link-year')) { this._showYearSelector(); } else if(Css.hasClassName(elem, 'clean')){ this._clean(); } else if(Css.hasClassName(elem, 'close')){ this._hide(false); } this._updateDescription(); }, /** * Handles click events on a changer (« ») for next/prev year/month * @method _onChangerClick * @private **/ _onRelativeChangerClick: function (elem) { var changeYear = { change_year_next: 1, change_year_prev: -1 }; var changeMonth = { change_month_next: 1, change_month_prev: -1 }; if( elem.className in changeMonth ) { this._updateCal(changeMonth[elem.className]); } else if( elem.className in changeYear ) { this._showYearSelector(changeYear[elem.className]); } }, /** * Handles click events on an atom-changer (day button, month button, year button) * * @method _onAbsoluteChangerClick * @private */ _onAbsoluteChangerClick: function (elem) { var elemData = InkElement.data(elem); if( Number(elemData.calDay) ){ this.setDate( [this._year, this._month + 1, elemData.calDay].join('-') ); this._hide(); } else if( Number(elemData.calMonth) ) { this._month = Number(elemData.calMonth) - 1; this._showDefaultView(); this._updateCal(); } else if( Number(elemData.calYear) ){ this._changeYear(Number(elemData.calYear)); } }, _changeYear: function (year) { year = +year; if(year){ this._year = year; if( typeof this._options.onYearSelected === 'function' ){ this._options.onYearSelected(this, { 'year': this._year }); } this._showMonthSelector(); } }, _clean: function () { if(this._options.displayInSelect){ this._options.yearField.selectedIndex = 0; this._options.monthField.selectedIndex = 0; this._options.dayField.selectedIndex = 0; } else { this._element.value = ''; } }, /** * Hides the DatePicker. * If the component is shy (options.shy), behaves differently. * * @method _hide * @param {Boolean} [blur] If false, forces hiding even if the component is shy. */ _hide: function(blur) { blur = blur === undefined ? true : blur; if (blur === false || (blur && this._options.shy)) { Css.addClassName(this._containerObject, 'hide-all'); } }, /** * Sets the range of dates allowed to be selected in the Date Picker * * @method _setMinMax * @param {String} dateRange Two dates separated by a ':'. Example: 2013-01-01:2013-12-12 * @private */ _setMinMax: function( dateRange ) { var self = this; var noMinLimit = { _year: -Number.MAX_VALUE, _month: 0, _day: 1 }; var noMaxLimit = { _year: Number.MAX_VALUE, _month: 11, _day: 31 }; function noLimits() { self._min = noMinLimit; self._max = noMaxLimit; } if (!dateRange) { return noLimits(); } var dates = dateRange.split( ':' ); var rDate = /^(\d{4})((\-)(\d{1,2})((\-)(\d{1,2}))?)?$/; InkArray.each([ {name: '_min', date: dates[0], noLim: noMinLimit}, {name: '_max', date: dates[1], noLim: noMaxLimit} ], Ink.bind(function (data) { var lim = data.noLim; if ( data.date.toUpperCase() === 'NOW' ) { var now = new Date(); lim = dateishFromDate(now); } else if (data.date.toUpperCase() === 'EVER') { lim = data.noLim; } else if ( rDate.test( data.date ) ) { lim = dateishFromYMDString(data.date); lim._month = clamp(lim._month, 0, 11); lim._day = clamp(lim._day, 1, this._daysInMonth( lim._year, lim._month + 1 )); } this[data.name] = lim; }, this)); // Should be equal, or min should be smaller var valid = this._dateCmp(this._max, this._min) !== -1; if (!valid) { noLimits(); } }, /** * Checks if a date is between the valid range. * Starts by checking if the date passed is valid. If not, will fallback to the 'today' date. * Then checks if the all params are inside of the date range specified. If not, it will fallback to the nearest valid date (either Min or Max). * * @method _fitDateToRange * @param {Number} year Year with 4 digits (yyyy) * @param {Number} month Month * @param {Number} day Day * @return {Array} Array with the final processed date. * @private */ _fitDateToRange: function( date ) { if ( !this._isValidDate( date ) ) { date = dateishFromDate(new Date()); } if (this._dateCmp(date, this._min) === -1) { return Ink.extendObj({}, this._min); } else if (this._dateCmp(date, this._max) === 1) { return Ink.extendObj({}, this._max); } return Ink.extendObj({}, date); // date is okay already, just copy it. }, /** * Checks whether a date is within the valid date range * @method _dateWithinRange * @param year * @param month * @param day * @return {Boolean} * @private */ _dateWithinRange: function (date) { if (!arguments.length) { date = this; } return (!this._dateAboveMax(date) && (!this._dateBelowMin(date))); }, _dateAboveMax: function (date) { return this._dateCmp(date, this._max) === 1; }, _dateBelowMin: function (date) { return this._dateCmp(date, this._min) === -1; }, _dateCmp: function (self, oth) { return this._dateCmpUntil(self, oth, '_day'); }, /** * _dateCmp with varied precision. You can compare down to the day field, or, just to the month. * // the following two dates are considered equal because we asked * // _dateCmpUntil to just check up to the years. * * _dateCmpUntil({_year: 2000, _month: 10}, {_year: 2000, _month: 11}, '_year') === 0 */ _dateCmpUntil: function (self, oth, depth) { var props = ['_year', '_month', '_day']; var i = -1; do { i++; if (self[props[i]] > oth[props[i]]) { return 1; } else if (self[props[i]] < oth[props[i]]) { return -1; } } while (props[i] !== depth && self[props[i + 1]] !== undefined && oth[props[i + 1]] !== undefined); return 0; }, /** * Sets the markup in the default view mode (showing the days). * Also disables the previous and next buttons in case they don't meet the range requirements. * * @method _showDefaultView * @private */ _showDefaultView: function(){ this._yearSelector.style.display = 'none'; this._monthSelector.style.display = 'none'; this._monthPrev.childNodes[0].className = 'change_month_prev'; this._monthNext.childNodes[0].className = 'change_month_next'; if ( !this._getPrevMonth() ) { this._monthPrev.childNodes[0].className = 'action_inactive'; } if ( !this._getNextMonth() ) { this._monthNext.childNodes[0].className = 'action_inactive'; } this._monthContainer.style.display = 'block'; }, /** * Updates the date shown on the datepicker * * @method _updateDate * @private */ _updateDate: function(){ var dataParsed; if(!this._options.displayInSelect && this._element.value){ dataParsed = this._parseDate(this._element.value); } else if (this._options.displayInSelect) { dataParsed = { _year: this._options.yearField[this._options.yearField.selectedIndex].value, _month: this._options.monthField[this._options.monthField.selectedIndex].value - 1, _day: this._options.dayField[this._options.dayField.selectedIndex].value }; } if (dataParsed) { dataParsed = this._fitDateToRange(dataParsed); this._year = dataParsed._year; this._month = dataParsed._month; this._day = dataParsed._day; } this.setDate(); this._updateDescription(); this._renderMonth(); }, /** * Updates the date description shown at the top of the datepicker * * EG "12 de November" * * @method _updateDescription * @private */ _updateDescription: function(){ this._monthChanger.innerHTML = this._options.month[ this._month + 1 ]; this._ofText.innerHTML = this._options.ofText; this._yearChanger.innerHTML = this._year; }, /** * Renders the year selector view of the datepicker * * @method _showYearSelector * @private */ _showYearSelector: function(inc){ this._incrementViewingYear(inc); var firstYear = this._year - (this._year % 10); var thisYear = firstYear - 1; var str = "<li><ul>"; if (thisYear > this._min._year) { str += '<li><a href="#year_prev" class="change_year_prev">' + this._options.prevLinkText + '</a></li>'; } else { str += '<li>&nbsp;</li>'; } for (var i=1; i < 11; i++){ if (i % 4 === 0){ str+='</ul><ul>'; } thisYear = firstYear + i - 1; str += this._getYearButtonHtml(thisYear); } if( thisYear < this._max._year){ str += '<li><a href="#year_next" class="change_year_next">' + this._options.nextLinkText + '</a></li>'; } else { str += '<li>&nbsp;</li>'; } str += "</ul></li>"; this._yearSelector.innerHTML = str; this._monthPrev.childNodes[0].className = 'action_inactive'; this._monthNext.childNodes[0].className = 'action_inactive'; this._monthSelector.style.display = 'none'; this._monthContainer.style.display = 'none'; this._yearSelector.style.display = 'block'; }, /** * For the year selector. * * Update this._year, to find the next decade or use nextValidDateFn to find it. */ _incrementViewingYear: function (inc) { if (!inc) { return; } var year = +this._year + inc*10; year = year - year % 10; if ( year > this._max._year || year + 9 < this._min._year){ return; } this._year = +this._year + inc*10; }, _getYearButtonHtml: function (thisYear) { if ( this._acceptableYear({_year: thisYear}) ){ var className = (thisYear === this._year) ? ' class="ink-calendar-on"' : ''; return '<li><a href="#" data-cal-year="' + thisYear + '"' + className + '>' + thisYear +'</a></li>'; } else { return '<li><a href="#" class="ink-calendar-off">' + thisYear +'</a></li>'; } }, /** * Show the month selector (happens when you click a year, or the "month" link. * @method _showMonthSelector * @private */ _showMonthSelector: function () { this._yearSelector.style.display = 'none'; this._monthContainer.style.display = 'none'; this._monthPrev.childNodes[0].className = 'action_inactive'; this._monthNext.childNodes[0].className = 'action_inactive'; this._addMonthClassNames(); this._monthSelector.style.display = 'block'; }, /** * This function returns the given date in the dateish format * * @method _parseDate * @param {String} dateStr A date on a string. * @private */ _parseDate: function(dateStr){ var date = InkDate.set( this._options.format , dateStr ); if (date) { return dateishFromDate(date); } return null; }, /** * Checks if a date is valid * * @method _isValidDate * @param {Dateish} date * @private * @return {Boolean} True if the date is valid, false otherwise */ _isValidDate: function(date){ var yearRegExp = /^\d{4}$/; var validOneOrTwo = /^\d{1,2}$/; return ( yearRegExp.test(date._year) && validOneOrTwo.test(date._month) && validOneOrTwo.test(date._day) && +date._month + 1 >= 1 && +date._month + 1 <= 12 && +date._day >= 1 && +date._day <= this._daysInMonth(date._year, date._month + 1) ); }, /** * Checks if a given date is an valid format. * * @method _isDate * @param {String} format A date format. * @param {String} dateStr A date on a string. * @private * @return {Boolean} True if the given date is valid according to the given format */ _isDate: function(format, dateStr){ try { if (typeof format === 'undefined'){ return false; } var date = InkDate.set( format , dateStr ); if( date && this._isValidDate( dateishFromDate(date) )) { return true; } } catch (ex) {} return false; }, _acceptableDay: function (date) { return this._acceptableDateComponent(date, 'validDayFn'); }, _acceptableMonth: function (date) { return this._acceptableDateComponent(date, 'validMonthFn'); }, _acceptableYear: function (date) { return this._acceptableDateComponent(date, 'validYearFn'); }, /** DRY base for the above 2 functions */ _acceptableDateComponent: function (date, userCb) { if (this._options[userCb]) { return this._callUserCallbackBool(this._options[userCb], date); } else { return this._dateWithinRange(date); } }, /** * This method returns the date written with the format specified on the options * * @method _writeDateInFormat * @private * @return {String} Returns the current date of the object in the specified format */ _writeDateInFormat:function(){ return InkDate.get( this._options.format , this.getDate()); }, /** * This method allows the user to set the DatePicker's date on run-time. * * @method setDate * @param {String} dateString A date string in yyyy-mm-dd format. * @public */ setDate: function( dateString ) { if ( /\d{4}-\d{1,2}-\d{1,2}/.test( dateString ) ) { var auxDate = dateString.split( '-' ); this._year = +auxDate[ 0 ]; this._month = +auxDate[ 1 ] - 1; this._day = +auxDate[ 2 ]; } this._setDate( ); }, /** * Gets the current date as a JavaScript date. * * @method getDate */ getDate: function () { if (!this._day) { throw 'Ink.UI.DatePicker: Still picking a date. Cannot getDate now!'; } return new Date(this._year, this._month, this._day); }, /** * Sets the chosen date on the target input field * * @method _setDate * @param {DOMElement} objClicked Clicked object inside the DatePicker's calendar. * @private */ _setDate : function( objClicked ) { if (objClicked) { var data = InkElement.data(objClicked); this._day = (+data.calDay) || this._day; } var dt = this._fitDateToRange(this); this._year = dt._year; this._month = dt._month; this._day = dt._day; if(!this._options.displayInSelect){ this._element.value = this._writeDateInFormat(); } else { this._options.dayField.value = this._day; this._options.monthField.value = this._month + 1; this._options.yearField.value = this._year; } if(this._options.onSetDate) { this._options.onSetDate( this , { date : this.getDate() } ); } }, /** * Makes the necessary work to update the calendar * when choosing a different month * * @method _updateCal * @param {Number} inc Indicates previous or next month * @private */ _updateCal: function(inc){ if( typeof this._options.onMonthSelected === 'function' ){ this._options.onMonthSelected(this, { 'year': this._year, 'month' : this._month }); } if (inc && this._updateMonth(inc) === null) { return; } this._renderMonth(); }, /** * Function that returns the number of days on a given month on a given year * * @method _daysInMonth * @param {Number} _y - year * @param {Number} _m - month * @private * @return {Number} The number of days on a given month on a given year */ _daysInMonth: function(_y,_m){ var exceptions = { 2: ((_y % 400 === 0) || (_y % 4 === 0 && _y % 100 !== 0)) ? 29 : 28, 4: 30, 6: 30, 9: 30, 11: 30 }; return exceptions[_m] || 31; }, /** * Updates the calendar when a different month is chosen * * @method _updateMonth * @param {Number} incValue - indicates previous or next month * @private */ _updateMonth: function(incValue){ var date; if (incValue > 0) { date = this._getNextMonth(); } else if (incValue < 0) { date = this._getPrevMonth(); } if (!date) { return null; } this._year = date._year; this._month = date._month; this._day = date._day; }, /** * Get the next month we can show. */ _getNextMonth: function (date) { return this._tryLeap( date, 'Month', 'next', function (d) { d._month += 1; if (d._month > 11) { d._month = 0; d._year += 1; } return d; }); }, /** * Get the previous month we can show. */ _getPrevMonth: function (date) { return this._tryLeap( date, 'Month', 'prev', function (d) { d._month -= 1; if (d._month < 0) { d._month = 11; d._year -= 1; } return d; }); }, /** * Get the next year we can show. */ _getPrevYear: function (date) { return this._tryLeap( date, 'Year', 'prev', function (d) { d._year -= 1; return d; }); }, /** * Get the next year we can show. */ _getNextYear: function (date) { return this._tryLeap( date, 'Year', 'next', function (d) { d._year += 1; return d; }); }, /** * DRY base for a function which tries to get the next or previous valid year or month. * * It checks if we can go forward by using _dateCmp with atomic * precision (this means, {_year} for leaping years, and * {_year, month} for leaping months), then it tries to get the * result from the user-supplied callback (nextDateFn or prevDateFn), * and when this is not present, advance the date forward using the * `advancer` callback. */ _tryLeap: function (date, atomName, directionName, advancer) { date = date || { _year: this._year, _month: this._month, _day: this._day }; var maxOrMin = directionName === 'prev' ? '_min' : '_max'; var boundary = this[maxOrMin]; // Check if we're by the boundary of min/max year/month if (this._dateCmpUntil(date, boundary, atomName) === 0) { return null; // We're already at the boundary. Bail. } var leapUserCb = this._options[directionName + 'ValidDateFn']; if (leapUserCb) { return this._callUserCallbackDate(leapUserCb, date); } else { date = advancer(date); } date = this._fitDateToRange(date); return this['_acceptable' + atomName](date) ? date : null; }, _getNextDecade: function (date) { date = date || { _year: this._year, _month: this._month, _day: this._day }; var decade = this._getCurrentDecade(date); if (decade + 10 > this._max._year) { return null; } return decade + 10; }, _getPrevDecade: function (date) { date = date || { _year: this._year, _month: this._month, _day: this._day }; var decade = this._getCurrentDecade(date); if (decade - 10 < this._min._year) { return null; } return decade - 10; }, /** Returns the decade given a date or year*/ _getCurrentDecade: function (year) { year = year ? (year._year || year) : this._year; return Math.floor(year / 10) * 10; // Round to first place }, _callUserCallbackBase: function (cb, date) { return cb.call(this, date._year, date._month + 1, date._day); }, _callUserCallbackBool: function (cb, date) { return !!this._callUserCallbackBase(cb, date); }, _callUserCallbackDate: function (cb, date) { var ret = this._callUserCallbackBase(cb, date); return ret ? dateishFromDate(ret) : null; }, /** * Key-value object that (for a given key) points to the correct parsing format for the DatePicker * @property _dateParsers * @type {Object} * @readOnly */ _dateParsers: { 'yyyy-mm-dd' : 'Y-m-d' , 'yyyy/mm/dd' : 'Y/m/d' , 'yy-mm-dd' : 'y-m-d' , 'yy/mm/dd' : 'y/m/d' , 'dd-mm-yyyy' : 'd-m-Y' , 'dd/mm/yyyy' : 'd/m/Y' , 'dd-mm-yy' : 'd-m-y' , 'dd/mm/yy' : 'd/m/y' , 'mm/dd/yyyy' : 'm/d/Y' , 'mm-dd-yyyy' : 'm-d-Y' }, /** * Renders the current month * * @method _renderMonth * @private */ _renderMonth: function(){ var month = this._month; var year = this._year; this._showDefaultView(); var html = ''; html += this._getMonthCalendarHeaderHtml(this._options.startWeekDay); var counter = 0; html+='<ul>'; var emptyHtml = '<li class="ink-calendar-empty">&nbsp;</li>'; var firstDayIndex = this._getFirstDayIndex(year, month); // Add padding if the first day of the month is not monday. if(firstDayIndex > 0) { counter += firstDayIndex; html += strRepeat(firstDayIndex, emptyHtml); } html += this._getDayButtonsHtml(year, month); html += '</ul>'; this._monthContainer.innerHTML = html; }, /** * Figure out where the first day of a month lies * in the first row of the calendar. * * having options.startWeekDay === 0 * * Su Mo Tu We Th Fr Sa * 1 <- The "1" is in the 7th day. return 6. * 2 3 4 5 6 7 8 * 9 10 11 12 13 14 15 * 16 17 18 19 20 21 22 * 23 24 25 26 27 28 29 * 30 31 * * This obviously changes according to the user option "startWeekDay" **/ _getFirstDayIndex: function (year, month) { var wDayFirst = (new Date( year , month , 1 )).getDay(); // Sunday=0 var startWeekDay = this._options.startWeekDay || 0; // Sunday=0 var result = wDayFirst - startWeekDay; result %= 7; if (result < 0) { result += 6; } return result; }, _getDayButtonsHtml: function (year, month) { var counter = this._getFirstDayIndex(year, month); var daysInMonth = this._daysInMonth(year, month + 1); var ret = ''; for (var day = 1; day <= daysInMonth; day++) { if (counter === 7){ // new week counter=0; ret += '<ul>'; } ret += this._getDayButtonHtml(year, month, day); counter++; if(counter === 7){ ret += '</ul>'; } } return ret; }, /** * Get the HTML markup for a single day in month view, given year, month, day. * * @method _getDayButtonHtml * @private */ _getDayButtonHtml: function (year, month, day) { var attrs = ' '; var date = dateishFromYMD(year, month, day); if (!this._acceptableDay(date)) { attrs += 'class="ink-calendar-off"'; } else { attrs += 'data-cal-day="' + day + '"'; } if (this._day && this._dateCmp(date, this) === 0) { attrs += 'class="ink-calendar-on" data-cal-day="' + day + '"'; } return '<li><a href="#" ' + attrs + '>' + day + '</a></li>'; }, /** Write the top bar of the calendar (M T W T F S S) */ _getMonthCalendarHeaderHtml: function (startWeekDay) { var ret = '<ul class="ink-calendar-header">'; var wDay; for(var i=0; i<7; i++){ wDay = (startWeekDay + i) % 7; ret += '<li>' + this._options.wDay[wDay].substring(0,1) + '</li>'; } return ret + '</ul>'; }, /** * This method adds class names to month buttons, to visually distinguish. * * @method _addMonthClassNames * @param {DOMElement} parent DOMElement where all the months are. * @private */ _addMonthClassNames: function(parent){ InkArray.forEach( (parent || this._monthSelector).getElementsByTagName('a'), Ink.bindMethod(this, '_addMonthButtonClassNames')); }, /** * Add the ink-calendar-on className if the given button is the current month, * otherwise add the ink-calendar-off className if the given button refers to * an unacceptable month (given dateRange and validMonthFn) */ _addMonthButtonClassNames: function (btn) { var data = InkElement.data(btn); if (!data.calMonth) { throw 'not a calendar month button!'; } var month = +data.calMonth - 1; if ( month === this._month ) { Css.addClassName( btn, 'ink-calendar-on' ); // This month Css.removeClassName( btn, 'ink-calendar-off' ); } else { Css.removeClassName( btn, 'ink-calendar-on' ); // Not this month var toDisable = !this._acceptableMonth({_year: this._year, _month: month}); Css.addRemoveClassName( btn, 'ink-calendar-off', toDisable); } }, /** * Prototype's method to allow the 'i18n files' to change all objects' language at once. * @param {Object} options Object with the texts' configuration. * @param {String} options.closeText Text of the close anchor * @param {String} options.cleanText Text of the clean text anchor * @param {String} options.prevLinkText "Previous" link's text * @param {String} options.nextLinkText "Next" link's text * @param {String} options.ofText The text "of", present in 'May of 2013' * @param {Object} options.month An object with keys from 1 to 12 for the full months' names * @param {Object} options.wDay An object with keys from 0 to 6 for the full weekdays' names * @public */ lang: function( options ){ this._lang = options; }, /** * This calls the rendering of the selected month. (Deprecated: use show() instead) * */ showMonth: function(){ this._renderMonth(); }, /** * Checks if the calendar screen is in 'select day' mode * * @return {Boolean} True if the calendar screen is in 'select day' mode * @public */ isMonthRendered: function(){ var header = Selector.select('.ink-calendar-header', this._containerObject)[0]; return ((Css.getStyle(header.parentNode,'display') !== 'none') && (Css.getStyle(header.parentNode.parentNode,'display') !== 'none') ); }, /** * Destroys this datepicker, removing it from the page. * * @public **/ destroy: function () { InkElement.unwrap(this._element); InkElement.remove(this._wrapper); InkElement.remove(this._containerObject); Common.unregisterInstance.call(this); } }; return DatePicker; });
siscia/jsdelivr
files/ink/3.0.0/js/ink.datepicker.js
JavaScript
mit
52,609
package dns import ( "crypto" "crypto/dsa" "crypto/ecdsa" "crypto/rsa" "io" "math/big" "strconv" "strings" ) // NewPrivateKey returns a PrivateKey by parsing the string s. // s should be in the same form of the BIND private key files. func (k *DNSKEY) NewPrivateKey(s string) (crypto.PrivateKey, error) { if s == "" || s[len(s)-1] != '\n' { // We need a closing newline return k.ReadPrivateKey(strings.NewReader(s+"\n"), "") } return k.ReadPrivateKey(strings.NewReader(s), "") } // ReadPrivateKey reads a private key from the io.Reader q. The string file is // only used in error reporting. // The public key must be known, because some cryptographic algorithms embed // the public inside the privatekey. func (k *DNSKEY) ReadPrivateKey(q io.Reader, file string) (crypto.PrivateKey, error) { m, err := parseKey(q, file) if m == nil { return nil, err } if _, ok := m["private-key-format"]; !ok { return nil, ErrPrivKey } if m["private-key-format"] != "v1.2" && m["private-key-format"] != "v1.3" { return nil, ErrPrivKey } // TODO(mg): check if the pubkey matches the private key algo, err := strconv.Atoi(strings.SplitN(m["algorithm"], " ", 2)[0]) if err != nil { return nil, ErrPrivKey } switch uint8(algo) { case DSA: priv, err := readPrivateKeyDSA(m) if err != nil { return nil, err } pub := k.publicKeyDSA() if pub == nil { return nil, ErrKey } priv.PublicKey = *pub return priv, nil case RSAMD5: fallthrough case RSASHA1: fallthrough case RSASHA1NSEC3SHA1: fallthrough case RSASHA256: fallthrough case RSASHA512: priv, err := readPrivateKeyRSA(m) if err != nil { return nil, err } pub := k.publicKeyRSA() if pub == nil { return nil, ErrKey } priv.PublicKey = *pub return priv, nil case ECCGOST: return nil, ErrPrivKey case ECDSAP256SHA256: fallthrough case ECDSAP384SHA384: priv, err := readPrivateKeyECDSA(m) if err != nil { return nil, err } pub := k.publicKeyECDSA() if pub == nil { return nil, ErrKey } priv.PublicKey = *pub return priv, nil default: return nil, ErrPrivKey } } // Read a private key (file) string and create a public key. Return the private key. func readPrivateKeyRSA(m map[string]string) (*rsa.PrivateKey, error) { p := new(rsa.PrivateKey) p.Primes = []*big.Int{nil, nil} for k, v := range m { switch k { case "modulus", "publicexponent", "privateexponent", "prime1", "prime2": v1, err := fromBase64([]byte(v)) if err != nil { return nil, err } switch k { case "modulus": p.PublicKey.N = big.NewInt(0) p.PublicKey.N.SetBytes(v1) case "publicexponent": i := big.NewInt(0) i.SetBytes(v1) p.PublicKey.E = int(i.Int64()) // int64 should be large enough case "privateexponent": p.D = big.NewInt(0) p.D.SetBytes(v1) case "prime1": p.Primes[0] = big.NewInt(0) p.Primes[0].SetBytes(v1) case "prime2": p.Primes[1] = big.NewInt(0) p.Primes[1].SetBytes(v1) } case "exponent1", "exponent2", "coefficient": // not used in Go (yet) case "created", "publish", "activate": // not used in Go (yet) } } return p, nil } func readPrivateKeyDSA(m map[string]string) (*dsa.PrivateKey, error) { p := new(dsa.PrivateKey) p.X = big.NewInt(0) for k, v := range m { switch k { case "private_value(x)": v1, err := fromBase64([]byte(v)) if err != nil { return nil, err } p.X.SetBytes(v1) case "created", "publish", "activate": /* not used in Go (yet) */ } } return p, nil } func readPrivateKeyECDSA(m map[string]string) (*ecdsa.PrivateKey, error) { p := new(ecdsa.PrivateKey) p.D = big.NewInt(0) // TODO: validate that the required flags are present for k, v := range m { switch k { case "privatekey": v1, err := fromBase64([]byte(v)) if err != nil { return nil, err } p.D.SetBytes(v1) case "created", "publish", "activate": /* not used in Go (yet) */ } } return p, nil } // parseKey reads a private key from r. It returns a map[string]string, // with the key-value pairs, or an error when the file is not correct. func parseKey(r io.Reader, file string) (map[string]string, error) { s := scanInit(r) m := make(map[string]string) c := make(chan lex) k := "" // Start the lexer go klexer(s, c) for l := range c { // It should alternate switch l.value { case zKey: k = l.token case zValue: if k == "" { return nil, &ParseError{file, "no private key seen", l} } //println("Setting", strings.ToLower(k), "to", l.token, "b") m[strings.ToLower(k)] = l.token k = "" } } return m, nil } // klexer scans the sourcefile and returns tokens on the channel c. func klexer(s *scan, c chan lex) { var l lex str := "" // Hold the current read text commt := false key := true x, err := s.tokenText() defer close(c) for err == nil { l.column = s.position.Column l.line = s.position.Line switch x { case ':': if commt { break } l.token = str if key { l.value = zKey c <- l // Next token is a space, eat it s.tokenText() key = false str = "" } else { l.value = zValue } case ';': commt = true case '\n': if commt { // Reset a comment commt = false } l.value = zValue l.token = str c <- l str = "" commt = false key = true default: if commt { break } str += string(x) } x, err = s.tokenText() } if len(str) > 0 { // Send remainder l.token = str l.value = zValue c <- l } }
turbosquid/gloon
vendor/src/github.com/miekg/dns/dnssec_keyscan.go
GO
mit
5,521
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; internal static partial class Interop { internal static partial class Winsock { [DllImport(Interop.Libraries.Ws2_32, ExactSpelling = true, CharSet = CharSet.Unicode, BestFitMapping = false, ThrowOnUnmappableChar = true, SetLastError = true)] internal static extern int GetAddrInfoW( [In] string nodename, [In] string servicename, [In] ref AddressInfo hints, [Out] out SafeFreeAddrInfo handle ); } }
nbarbettini/corefx
src/Common/src/Interop/Windows/Winsock/Interop.GetAddrInfoW.cs
C#
mit
789
/** * @license AngularJS v1.3.16 * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) { 'use strict'; /** * @ngdoc object * @name angular.mock * @description * * Namespace from 'angular-mocks.js' which contains testing related code. */ angular.mock = {}; /** * ! This is a private undocumented service ! * * @name $browser * * @description * This service is a mock implementation of {@link ng.$browser}. It provides fake * implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr, * cookies, etc... * * The api of this service is the same as that of the real {@link ng.$browser $browser}, except * that there are several helper methods available which can be used in tests. */ angular.mock.$BrowserProvider = function() { this.$get = function() { return new angular.mock.$Browser(); }; }; angular.mock.$Browser = function() { var self = this; this.isMock = true; self.$$url = "http://server/"; self.$$lastUrl = self.$$url; // used by url polling fn self.pollFns = []; // TODO(vojta): remove this temporary api self.$$completeOutstandingRequest = angular.noop; self.$$incOutstandingRequestCount = angular.noop; // register url polling fn self.onUrlChange = function(listener) { self.pollFns.push( function() { if (self.$$lastUrl !== self.$$url || self.$$state !== self.$$lastState) { self.$$lastUrl = self.$$url; self.$$lastState = self.$$state; listener(self.$$url, self.$$state); } } ); return listener; }; self.$$checkUrlChange = angular.noop; self.cookieHash = {}; self.lastCookieHash = {}; self.deferredFns = []; self.deferredNextId = 0; self.defer = function(fn, delay) { delay = delay || 0; self.deferredFns.push({time:(self.defer.now + delay), fn:fn, id: self.deferredNextId}); self.deferredFns.sort(function(a, b) { return a.time - b.time;}); return self.deferredNextId++; }; /** * @name $browser#defer.now * * @description * Current milliseconds mock time. */ self.defer.now = 0; self.defer.cancel = function(deferId) { var fnIndex; angular.forEach(self.deferredFns, function(fn, index) { if (fn.id === deferId) fnIndex = index; }); if (fnIndex !== undefined) { self.deferredFns.splice(fnIndex, 1); return true; } return false; }; /** * @name $browser#defer.flush * * @description * Flushes all pending requests and executes the defer callbacks. * * @param {number=} number of milliseconds to flush. See {@link #defer.now} */ self.defer.flush = function(delay) { if (angular.isDefined(delay)) { self.defer.now += delay; } else { if (self.deferredFns.length) { self.defer.now = self.deferredFns[self.deferredFns.length - 1].time; } else { throw new Error('No deferred tasks to be flushed'); } } while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) { self.deferredFns.shift().fn(); } }; self.$$baseHref = '/'; self.baseHref = function() { return this.$$baseHref; }; }; angular.mock.$Browser.prototype = { /** * @name $browser#poll * * @description * run all fns in pollFns */ poll: function poll() { angular.forEach(this.pollFns, function(pollFn) { pollFn(); }); }, addPollFn: function(pollFn) { this.pollFns.push(pollFn); return pollFn; }, url: function(url, replace, state) { if (angular.isUndefined(state)) { state = null; } if (url) { this.$$url = url; // Native pushState serializes & copies the object; simulate it. this.$$state = angular.copy(state); return this; } return this.$$url; }, state: function() { return this.$$state; }, cookies: function(name, value) { if (name) { if (angular.isUndefined(value)) { delete this.cookieHash[name]; } else { if (angular.isString(value) && //strings only value.length <= 4096) { //strict cookie storage limits this.cookieHash[name] = value; } } } else { if (!angular.equals(this.cookieHash, this.lastCookieHash)) { this.lastCookieHash = angular.copy(this.cookieHash); this.cookieHash = angular.copy(this.cookieHash); } return this.cookieHash; } }, notifyWhenNoOutstandingRequests: function(fn) { fn(); } }; /** * @ngdoc provider * @name $exceptionHandlerProvider * * @description * Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors * passed to the `$exceptionHandler`. */ /** * @ngdoc service * @name $exceptionHandler * * @description * Mock implementation of {@link ng.$exceptionHandler} that rethrows or logs errors passed * to it. See {@link ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration * information. * * * ```js * describe('$exceptionHandlerProvider', function() { * * it('should capture log messages and exceptions', function() { * * module(function($exceptionHandlerProvider) { * $exceptionHandlerProvider.mode('log'); * }); * * inject(function($log, $exceptionHandler, $timeout) { * $timeout(function() { $log.log(1); }); * $timeout(function() { $log.log(2); throw 'banana peel'; }); * $timeout(function() { $log.log(3); }); * expect($exceptionHandler.errors).toEqual([]); * expect($log.assertEmpty()); * $timeout.flush(); * expect($exceptionHandler.errors).toEqual(['banana peel']); * expect($log.log.logs).toEqual([[1], [2], [3]]); * }); * }); * }); * ``` */ angular.mock.$ExceptionHandlerProvider = function() { var handler; /** * @ngdoc method * @name $exceptionHandlerProvider#mode * * @description * Sets the logging mode. * * @param {string} mode Mode of operation, defaults to `rethrow`. * * - `log`: Sometimes it is desirable to test that an error is thrown, for this case the `log` * mode stores an array of errors in `$exceptionHandler.errors`, to allow later * assertion of them. See {@link ngMock.$log#assertEmpty assertEmpty()} and * {@link ngMock.$log#reset reset()} * - `rethrow`: If any errors are passed to the handler in tests, it typically means that there * is a bug in the application or test, so this mock will make these tests fail. * For any implementations that expect exceptions to be thrown, the `rethrow` mode * will also maintain a log of thrown errors. */ this.mode = function(mode) { switch (mode) { case 'log': case 'rethrow': var errors = []; handler = function(e) { if (arguments.length == 1) { errors.push(e); } else { errors.push([].slice.call(arguments, 0)); } if (mode === "rethrow") { throw e; } }; handler.errors = errors; break; default: throw new Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!"); } }; this.$get = function() { return handler; }; this.mode('rethrow'); }; /** * @ngdoc service * @name $log * * @description * Mock implementation of {@link ng.$log} that gathers all logged messages in arrays * (one array per logging level). These arrays are exposed as `logs` property of each of the * level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`. * */ angular.mock.$LogProvider = function() { var debug = true; function concat(array1, array2, index) { return array1.concat(Array.prototype.slice.call(array2, index)); } this.debugEnabled = function(flag) { if (angular.isDefined(flag)) { debug = flag; return this; } else { return debug; } }; this.$get = function() { var $log = { log: function() { $log.log.logs.push(concat([], arguments, 0)); }, warn: function() { $log.warn.logs.push(concat([], arguments, 0)); }, info: function() { $log.info.logs.push(concat([], arguments, 0)); }, error: function() { $log.error.logs.push(concat([], arguments, 0)); }, debug: function() { if (debug) { $log.debug.logs.push(concat([], arguments, 0)); } } }; /** * @ngdoc method * @name $log#reset * * @description * Reset all of the logging arrays to empty. */ $log.reset = function() { /** * @ngdoc property * @name $log#log.logs * * @description * Array of messages logged using {@link ng.$log#log `log()`}. * * @example * ```js * $log.log('Some Log'); * var first = $log.log.logs.unshift(); * ``` */ $log.log.logs = []; /** * @ngdoc property * @name $log#info.logs * * @description * Array of messages logged using {@link ng.$log#info `info()`}. * * @example * ```js * $log.info('Some Info'); * var first = $log.info.logs.unshift(); * ``` */ $log.info.logs = []; /** * @ngdoc property * @name $log#warn.logs * * @description * Array of messages logged using {@link ng.$log#warn `warn()`}. * * @example * ```js * $log.warn('Some Warning'); * var first = $log.warn.logs.unshift(); * ``` */ $log.warn.logs = []; /** * @ngdoc property * @name $log#error.logs * * @description * Array of messages logged using {@link ng.$log#error `error()`}. * * @example * ```js * $log.error('Some Error'); * var first = $log.error.logs.unshift(); * ``` */ $log.error.logs = []; /** * @ngdoc property * @name $log#debug.logs * * @description * Array of messages logged using {@link ng.$log#debug `debug()`}. * * @example * ```js * $log.debug('Some Error'); * var first = $log.debug.logs.unshift(); * ``` */ $log.debug.logs = []; }; /** * @ngdoc method * @name $log#assertEmpty * * @description * Assert that all of the logging methods have no logged messages. If any messages are present, * an exception is thrown. */ $log.assertEmpty = function() { var errors = []; angular.forEach(['error', 'warn', 'info', 'log', 'debug'], function(logLevel) { angular.forEach($log[logLevel].logs, function(log) { angular.forEach(log, function(logItem) { errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' + (logItem.stack || '')); }); }); }); if (errors.length) { errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or " + "an expected log message was not checked and removed:"); errors.push(''); throw new Error(errors.join('\n---------\n')); } }; $log.reset(); return $log; }; }; /** * @ngdoc service * @name $interval * * @description * Mock implementation of the $interval service. * * Use {@link ngMock.$interval#flush `$interval.flush(millis)`} to * move forward by `millis` milliseconds and trigger any functions scheduled to run in that * time. * * @param {function()} fn A function that should be called repeatedly. * @param {number} delay Number of milliseconds between each function call. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat * indefinitely. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. * @returns {promise} A promise which will be notified on each iteration. */ angular.mock.$IntervalProvider = function() { this.$get = ['$browser', '$rootScope', '$q', '$$q', function($browser, $rootScope, $q, $$q) { var repeatFns = [], nextRepeatId = 0, now = 0; var $interval = function(fn, delay, count, invokeApply) { var iteration = 0, skipApply = (angular.isDefined(invokeApply) && !invokeApply), deferred = (skipApply ? $$q : $q).defer(), promise = deferred.promise; count = (angular.isDefined(count)) ? count : 0; promise.then(null, null, fn); promise.$$intervalId = nextRepeatId; function tick() { deferred.notify(iteration++); if (count > 0 && iteration >= count) { var fnIndex; deferred.resolve(iteration); angular.forEach(repeatFns, function(fn, index) { if (fn.id === promise.$$intervalId) fnIndex = index; }); if (fnIndex !== undefined) { repeatFns.splice(fnIndex, 1); } } if (skipApply) { $browser.defer.flush(); } else { $rootScope.$apply(); } } repeatFns.push({ nextTime:(now + delay), delay: delay, fn: tick, id: nextRepeatId, deferred: deferred }); repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;}); nextRepeatId++; return promise; }; /** * @ngdoc method * @name $interval#cancel * * @description * Cancels a task associated with the `promise`. * * @param {promise} promise A promise from calling the `$interval` function. * @returns {boolean} Returns `true` if the task was successfully cancelled. */ $interval.cancel = function(promise) { if (!promise) return false; var fnIndex; angular.forEach(repeatFns, function(fn, index) { if (fn.id === promise.$$intervalId) fnIndex = index; }); if (fnIndex !== undefined) { repeatFns[fnIndex].deferred.reject('canceled'); repeatFns.splice(fnIndex, 1); return true; } return false; }; /** * @ngdoc method * @name $interval#flush * @description * * Runs interval tasks scheduled to be run in the next `millis` milliseconds. * * @param {number=} millis maximum timeout amount to flush up until. * * @return {number} The amount of time moved forward. */ $interval.flush = function(millis) { now += millis; while (repeatFns.length && repeatFns[0].nextTime <= now) { var task = repeatFns[0]; task.fn(); task.nextTime += task.delay; repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;}); } return millis; }; return $interval; }]; }; /* jshint -W101 */ /* The R_ISO8061_STR regex is never going to fit into the 100 char limit! * This directive should go inside the anonymous function but a bug in JSHint means that it would * not be enacted early enough to prevent the warning. */ var R_ISO8061_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/; function jsonStringToDate(string) { var match; if (match = string.match(R_ISO8061_STR)) { var date = new Date(0), tzHour = 0, tzMin = 0; if (match[9]) { tzHour = int(match[9] + match[10]); tzMin = int(match[9] + match[11]); } date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3])); date.setUTCHours(int(match[4] || 0) - tzHour, int(match[5] || 0) - tzMin, int(match[6] || 0), int(match[7] || 0)); return date; } return string; } function int(str) { return parseInt(str, 10); } function padNumber(num, digits, trim) { var neg = ''; if (num < 0) { neg = '-'; num = -num; } num = '' + num; while (num.length < digits) num = '0' + num; if (trim) num = num.substr(num.length - digits); return neg + num; } /** * @ngdoc type * @name angular.mock.TzDate * @description * * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`. * * Mock of the Date type which has its timezone specified via constructor arg. * * The main purpose is to create Date-like instances with timezone fixed to the specified timezone * offset, so that we can test code that depends on local timezone settings without dependency on * the time zone settings of the machine where the code is running. * * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored) * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC* * * @example * !!!! WARNING !!!!! * This is not a complete Date object so only methods that were implemented can be called safely. * To make matters worse, TzDate instances inherit stuff from Date via a prototype. * * We do our best to intercept calls to "unimplemented" methods, but since the list of methods is * incomplete we might be missing some non-standard methods. This can result in errors like: * "Date.prototype.foo called on incompatible Object". * * ```js * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z'); * newYearInBratislava.getTimezoneOffset() => -60; * newYearInBratislava.getFullYear() => 2010; * newYearInBratislava.getMonth() => 0; * newYearInBratislava.getDate() => 1; * newYearInBratislava.getHours() => 0; * newYearInBratislava.getMinutes() => 0; * newYearInBratislava.getSeconds() => 0; * ``` * */ angular.mock.TzDate = function(offset, timestamp) { var self = new Date(0); if (angular.isString(timestamp)) { var tsStr = timestamp; self.origDate = jsonStringToDate(timestamp); timestamp = self.origDate.getTime(); if (isNaN(timestamp)) throw { name: "Illegal Argument", message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string" }; } else { self.origDate = new Date(timestamp); } var localOffset = new Date(timestamp).getTimezoneOffset(); self.offsetDiff = localOffset * 60 * 1000 - offset * 1000 * 60 * 60; self.date = new Date(timestamp + self.offsetDiff); self.getTime = function() { return self.date.getTime() - self.offsetDiff; }; self.toLocaleDateString = function() { return self.date.toLocaleDateString(); }; self.getFullYear = function() { return self.date.getFullYear(); }; self.getMonth = function() { return self.date.getMonth(); }; self.getDate = function() { return self.date.getDate(); }; self.getHours = function() { return self.date.getHours(); }; self.getMinutes = function() { return self.date.getMinutes(); }; self.getSeconds = function() { return self.date.getSeconds(); }; self.getMilliseconds = function() { return self.date.getMilliseconds(); }; self.getTimezoneOffset = function() { return offset * 60; }; self.getUTCFullYear = function() { return self.origDate.getUTCFullYear(); }; self.getUTCMonth = function() { return self.origDate.getUTCMonth(); }; self.getUTCDate = function() { return self.origDate.getUTCDate(); }; self.getUTCHours = function() { return self.origDate.getUTCHours(); }; self.getUTCMinutes = function() { return self.origDate.getUTCMinutes(); }; self.getUTCSeconds = function() { return self.origDate.getUTCSeconds(); }; self.getUTCMilliseconds = function() { return self.origDate.getUTCMilliseconds(); }; self.getDay = function() { return self.date.getDay(); }; // provide this method only on browsers that already have it if (self.toISOString) { self.toISOString = function() { return padNumber(self.origDate.getUTCFullYear(), 4) + '-' + padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' + padNumber(self.origDate.getUTCDate(), 2) + 'T' + padNumber(self.origDate.getUTCHours(), 2) + ':' + padNumber(self.origDate.getUTCMinutes(), 2) + ':' + padNumber(self.origDate.getUTCSeconds(), 2) + '.' + padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z'; }; } //hide all methods not implemented in this mock that the Date prototype exposes var unimplementedMethods = ['getUTCDay', 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds', 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear', 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds', 'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString', 'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf']; angular.forEach(unimplementedMethods, function(methodName) { self[methodName] = function() { throw new Error("Method '" + methodName + "' is not implemented in the TzDate mock"); }; }); return self; }; //make "tzDateInstance instanceof Date" return true angular.mock.TzDate.prototype = Date.prototype; /* jshint +W101 */ angular.mock.animate = angular.module('ngAnimateMock', ['ng']) .config(['$provide', function($provide) { var reflowQueue = []; $provide.value('$$animateReflow', function(fn) { var index = reflowQueue.length; reflowQueue.push(fn); return function cancel() { reflowQueue.splice(index, 1); }; }); $provide.decorator('$animate', ['$delegate', '$$asyncCallback', '$timeout', '$browser', function($delegate, $$asyncCallback, $timeout, $browser) { var animate = { queue: [], cancel: $delegate.cancel, enabled: $delegate.enabled, triggerCallbackEvents: function() { $$asyncCallback.flush(); }, triggerCallbackPromise: function() { $timeout.flush(0); }, triggerCallbacks: function() { this.triggerCallbackEvents(); this.triggerCallbackPromise(); }, triggerReflow: function() { angular.forEach(reflowQueue, function(fn) { fn(); }); reflowQueue = []; } }; angular.forEach( ['animate','enter','leave','move','addClass','removeClass','setClass'], function(method) { animate[method] = function() { animate.queue.push({ event: method, element: arguments[0], options: arguments[arguments.length - 1], args: arguments }); return $delegate[method].apply($delegate, arguments); }; }); return animate; }]); }]); /** * @ngdoc function * @name angular.mock.dump * @description * * *NOTE*: this is not an injectable instance, just a globally available function. * * Method for serializing common angular objects (scope, elements, etc..) into strings, useful for * debugging. * * This method is also available on window, where it can be used to display objects on debug * console. * * @param {*} object - any object to turn into string. * @return {string} a serialized string of the argument */ angular.mock.dump = function(object) { return serialize(object); function serialize(object) { var out; if (angular.isElement(object)) { object = angular.element(object); out = angular.element('<div></div>'); angular.forEach(object, function(element) { out.append(angular.element(element).clone()); }); out = out.html(); } else if (angular.isArray(object)) { out = []; angular.forEach(object, function(o) { out.push(serialize(o)); }); out = '[ ' + out.join(', ') + ' ]'; } else if (angular.isObject(object)) { if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) { out = serializeScope(object); } else if (object instanceof Error) { out = object.stack || ('' + object.name + ': ' + object.message); } else { // TODO(i): this prevents methods being logged, // we should have a better way to serialize objects out = angular.toJson(object, true); } } else { out = String(object); } return out; } function serializeScope(scope, offset) { offset = offset || ' '; var log = [offset + 'Scope(' + scope.$id + '): {']; for (var key in scope) { if (Object.prototype.hasOwnProperty.call(scope, key) && !key.match(/^(\$|this)/)) { log.push(' ' + key + ': ' + angular.toJson(scope[key])); } } var child = scope.$$childHead; while (child) { log.push(serializeScope(child, offset + ' ')); child = child.$$nextSibling; } log.push('}'); return log.join('\n' + offset); } }; /** * @ngdoc service * @name $httpBackend * @description * Fake HTTP backend implementation suitable for unit testing applications that use the * {@link ng.$http $http service}. * * *Note*: For fake HTTP backend implementation suitable for end-to-end testing or backend-less * development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}. * * During unit testing, we want our unit tests to run quickly and have no external dependencies so * we don’t want to send [XHR](https://developer.mozilla.org/en/xmlhttprequest) or * [JSONP](http://en.wikipedia.org/wiki/JSONP) requests to a real server. All we really need is * to verify whether a certain request has been sent or not, or alternatively just let the * application make requests, respond with pre-trained responses and assert that the end result is * what we expect it to be. * * This mock implementation can be used to respond with static or dynamic responses via the * `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc). * * When an Angular application needs some data from a server, it calls the $http service, which * sends the request to a real server using $httpBackend service. With dependency injection, it is * easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify * the requests and respond with some testing data without sending a request to a real server. * * There are two ways to specify what test data should be returned as http responses by the mock * backend when the code under test makes http requests: * * - `$httpBackend.expect` - specifies a request expectation * - `$httpBackend.when` - specifies a backend definition * * * # Request Expectations vs Backend Definitions * * Request expectations provide a way to make assertions about requests made by the application and * to define responses for those requests. The test will fail if the expected requests are not made * or they are made in the wrong order. * * Backend definitions allow you to define a fake backend for your application which doesn't assert * if a particular request was made or not, it just returns a trained response if a request is made. * The test will pass whether or not the request gets made during testing. * * * <table class="table"> * <tr><th width="220px"></th><th>Request expectations</th><th>Backend definitions</th></tr> * <tr> * <th>Syntax</th> * <td>.expect(...).respond(...)</td> * <td>.when(...).respond(...)</td> * </tr> * <tr> * <th>Typical usage</th> * <td>strict unit tests</td> * <td>loose (black-box) unit testing</td> * </tr> * <tr> * <th>Fulfills multiple requests</th> * <td>NO</td> * <td>YES</td> * </tr> * <tr> * <th>Order of requests matters</th> * <td>YES</td> * <td>NO</td> * </tr> * <tr> * <th>Request required</th> * <td>YES</td> * <td>NO</td> * </tr> * <tr> * <th>Response required</th> * <td>optional (see below)</td> * <td>YES</td> * </tr> * </table> * * In cases where both backend definitions and request expectations are specified during unit * testing, the request expectations are evaluated first. * * If a request expectation has no response specified, the algorithm will search your backend * definitions for an appropriate response. * * If a request didn't match any expectation or if the expectation doesn't have the response * defined, the backend definitions are evaluated in sequential order to see if any of them match * the request. The response from the first matched definition is returned. * * * # Flushing HTTP requests * * The $httpBackend used in production always responds to requests asynchronously. If we preserved * this behavior in unit testing, we'd have to create async unit tests, which are hard to write, * to follow and to maintain. But neither can the testing mock respond synchronously; that would * change the execution of the code under test. For this reason, the mock $httpBackend has a * `flush()` method, which allows the test to explicitly flush pending requests. This preserves * the async api of the backend, while allowing the test to execute synchronously. * * * # Unit testing with mock $httpBackend * The following code shows how to setup and use the mock backend when unit testing a controller. * First we create the controller under test: * ```js // The module code angular .module('MyApp', []) .controller('MyController', MyController); // The controller code function MyController($scope, $http) { var authToken; $http.get('/auth.py').success(function(data, status, headers) { authToken = headers('A-Token'); $scope.user = data; }); $scope.saveMessage = function(message) { var headers = { 'Authorization': authToken }; $scope.status = 'Saving...'; $http.post('/add-msg.py', message, { headers: headers } ).success(function(response) { $scope.status = ''; }).error(function() { $scope.status = 'ERROR!'; }); }; } ``` * * Now we setup the mock backend and create the test specs: * ```js // testing controller describe('MyController', function() { var $httpBackend, $rootScope, createController, authRequestHandler; // Set up the module beforeEach(module('MyApp')); beforeEach(inject(function($injector) { // Set up the mock http service responses $httpBackend = $injector.get('$httpBackend'); // backend definition common for all tests authRequestHandler = $httpBackend.when('GET', '/auth.py') .respond({userId: 'userX'}, {'A-Token': 'xxx'}); // Get hold of a scope (i.e. the root scope) $rootScope = $injector.get('$rootScope'); // The $controller service is used to create instances of controllers var $controller = $injector.get('$controller'); createController = function() { return $controller('MyController', {'$scope' : $rootScope }); }; })); afterEach(function() { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); it('should fetch authentication token', function() { $httpBackend.expectGET('/auth.py'); var controller = createController(); $httpBackend.flush(); }); it('should fail authentication', function() { // Notice how you can change the response even after it was set authRequestHandler.respond(401, ''); $httpBackend.expectGET('/auth.py'); var controller = createController(); $httpBackend.flush(); expect($rootScope.status).toBe('Failed...'); }); it('should send msg to server', function() { var controller = createController(); $httpBackend.flush(); // now you don’t care about the authentication, but // the controller will still send the request and // $httpBackend will respond without you having to // specify the expectation and response for this request $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, ''); $rootScope.saveMessage('message content'); expect($rootScope.status).toBe('Saving...'); $httpBackend.flush(); expect($rootScope.status).toBe(''); }); it('should send auth header', function() { var controller = createController(); $httpBackend.flush(); $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) { // check if the header was send, if it wasn't the expectation won't // match the request and the test will fail return headers['Authorization'] == 'xxx'; }).respond(201, ''); $rootScope.saveMessage('whatever'); $httpBackend.flush(); }); }); ``` */ angular.mock.$HttpBackendProvider = function() { this.$get = ['$rootScope', '$timeout', createHttpBackendMock]; }; /** * General factory function for $httpBackend mock. * Returns instance for unit testing (when no arguments specified): * - passing through is disabled * - auto flushing is disabled * * Returns instance for e2e testing (when `$delegate` and `$browser` specified): * - passing through (delegating request to real backend) is enabled * - auto flushing is enabled * * @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified) * @param {Object=} $browser Auto-flushing enabled if specified * @return {Object} Instance of $httpBackend mock */ function createHttpBackendMock($rootScope, $timeout, $delegate, $browser) { var definitions = [], expectations = [], responses = [], responsesPush = angular.bind(responses, responses.push), copy = angular.copy; function createResponse(status, data, headers, statusText) { if (angular.isFunction(status)) return status; return function() { return angular.isNumber(status) ? [status, data, headers, statusText] : [200, status, data, headers]; }; } // TODO(vojta): change params to: method, url, data, headers, callback function $httpBackend(method, url, data, callback, headers, timeout, withCredentials) { var xhr = new MockXhr(), expectation = expectations[0], wasExpected = false; function prettyPrint(data) { return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp) ? data : angular.toJson(data); } function wrapResponse(wrapped) { if (!$browser && timeout) { timeout.then ? timeout.then(handleTimeout) : $timeout(handleTimeout, timeout); } return handleResponse; function handleResponse() { var response = wrapped.response(method, url, data, headers); xhr.$$respHeaders = response[2]; callback(copy(response[0]), copy(response[1]), xhr.getAllResponseHeaders(), copy(response[3] || '')); } function handleTimeout() { for (var i = 0, ii = responses.length; i < ii; i++) { if (responses[i] === handleResponse) { responses.splice(i, 1); callback(-1, undefined, ''); break; } } } } if (expectation && expectation.match(method, url)) { if (!expectation.matchData(data)) throw new Error('Expected ' + expectation + ' with different data\n' + 'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data); if (!expectation.matchHeaders(headers)) throw new Error('Expected ' + expectation + ' with different headers\n' + 'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' + prettyPrint(headers)); expectations.shift(); if (expectation.response) { responses.push(wrapResponse(expectation)); return; } wasExpected = true; } var i = -1, definition; while ((definition = definitions[++i])) { if (definition.match(method, url, data, headers || {})) { if (definition.response) { // if $browser specified, we do auto flush all requests ($browser ? $browser.defer : responsesPush)(wrapResponse(definition)); } else if (definition.passThrough) { $delegate(method, url, data, callback, headers, timeout, withCredentials); } else throw new Error('No response defined !'); return; } } throw wasExpected ? new Error('No response defined !') : new Error('Unexpected request: ' + method + ' ' + url + '\n' + (expectation ? 'Expected ' + expectation : 'No more request expected')); } /** * @ngdoc method * @name $httpBackend#when * @description * Creates a new backend definition. * * @param {string} method HTTP method. * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current definition. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. * * - respond – * `{function([status,] data[, headers, statusText]) * | function(function(method, url, data, headers)}` * – The respond method takes a set of static data to be returned or a function that can * return an array containing response status (number), response data (string), response * headers (Object), and the text for the status (string). The respond method returns the * `requestHandler` object for possible overrides. */ $httpBackend.when = function(method, url, data, headers) { var definition = new MockHttpExpectation(method, url, data, headers), chain = { respond: function(status, data, headers, statusText) { definition.passThrough = undefined; definition.response = createResponse(status, data, headers, statusText); return chain; } }; if ($browser) { chain.passThrough = function() { definition.response = undefined; definition.passThrough = true; return chain; }; } definitions.push(definition); return chain; }; /** * @ngdoc method * @name $httpBackend#whenGET * @description * Creates a new backend definition for GET requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenHEAD * @description * Creates a new backend definition for HEAD requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenDELETE * @description * Creates a new backend definition for DELETE requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenPOST * @description * Creates a new backend definition for POST requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenPUT * @description * Creates a new backend definition for PUT requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenJSONP * @description * Creates a new backend definition for JSONP requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ createShortMethods('when'); /** * @ngdoc method * @name $httpBackend#expect * @description * Creates a new request expectation. * * @param {string} method HTTP method. * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that * receives data string and returns true if the data is as expected, or Object if request body * is in JSON format. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current expectation. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. * * - respond – * `{function([status,] data[, headers, statusText]) * | function(function(method, url, data, headers)}` * – The respond method takes a set of static data to be returned or a function that can * return an array containing response status (number), response data (string), response * headers (Object), and the text for the status (string). The respond method returns the * `requestHandler` object for possible overrides. */ $httpBackend.expect = function(method, url, data, headers) { var expectation = new MockHttpExpectation(method, url, data, headers), chain = { respond: function(status, data, headers, statusText) { expectation.response = createResponse(status, data, headers, statusText); return chain; } }; expectations.push(expectation); return chain; }; /** * @ngdoc method * @name $httpBackend#expectGET * @description * Creates a new request expectation for GET requests. For more info see `expect()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. See #expect for more info. */ /** * @ngdoc method * @name $httpBackend#expectHEAD * @description * Creates a new request expectation for HEAD requests. For more info see `expect()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#expectDELETE * @description * Creates a new request expectation for DELETE requests. For more info see `expect()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#expectPOST * @description * Creates a new request expectation for POST requests. For more info see `expect()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that * receives data string and returns true if the data is as expected, or Object if request body * is in JSON format. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#expectPUT * @description * Creates a new request expectation for PUT requests. For more info see `expect()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that * receives data string and returns true if the data is as expected, or Object if request body * is in JSON format. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#expectPATCH * @description * Creates a new request expectation for PATCH requests. For more info see `expect()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that * receives data string and returns true if the data is as expected, or Object if request body * is in JSON format. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#expectJSONP * @description * Creates a new request expectation for JSONP requests. For more info see `expect()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ createShortMethods('expect'); /** * @ngdoc method * @name $httpBackend#flush * @description * Flushes all pending requests using the trained responses. * * @param {number=} count Number of responses to flush (in the order they arrived). If undefined, * all pending requests will be flushed. If there are no pending requests when the flush method * is called an exception is thrown (as this typically a sign of programming error). */ $httpBackend.flush = function(count, digest) { if (digest !== false) $rootScope.$digest(); if (!responses.length) throw new Error('No pending request to flush !'); if (angular.isDefined(count) && count !== null) { while (count--) { if (!responses.length) throw new Error('No more pending request to flush !'); responses.shift()(); } } else { while (responses.length) { responses.shift()(); } } $httpBackend.verifyNoOutstandingExpectation(digest); }; /** * @ngdoc method * @name $httpBackend#verifyNoOutstandingExpectation * @description * Verifies that all of the requests defined via the `expect` api were made. If any of the * requests were not made, verifyNoOutstandingExpectation throws an exception. * * Typically, you would call this method following each test case that asserts requests using an * "afterEach" clause. * * ```js * afterEach($httpBackend.verifyNoOutstandingExpectation); * ``` */ $httpBackend.verifyNoOutstandingExpectation = function(digest) { if (digest !== false) $rootScope.$digest(); if (expectations.length) { throw new Error('Unsatisfied requests: ' + expectations.join(', ')); } }; /** * @ngdoc method * @name $httpBackend#verifyNoOutstandingRequest * @description * Verifies that there are no outstanding requests that need to be flushed. * * Typically, you would call this method following each test case that asserts requests using an * "afterEach" clause. * * ```js * afterEach($httpBackend.verifyNoOutstandingRequest); * ``` */ $httpBackend.verifyNoOutstandingRequest = function() { if (responses.length) { throw new Error('Unflushed requests: ' + responses.length); } }; /** * @ngdoc method * @name $httpBackend#resetExpectations * @description * Resets all request expectations, but preserves all backend definitions. Typically, you would * call resetExpectations during a multiple-phase test when you want to reuse the same instance of * $httpBackend mock. */ $httpBackend.resetExpectations = function() { expectations.length = 0; responses.length = 0; }; return $httpBackend; function createShortMethods(prefix) { angular.forEach(['GET', 'DELETE', 'JSONP', 'HEAD'], function(method) { $httpBackend[prefix + method] = function(url, headers) { return $httpBackend[prefix](method, url, undefined, headers); }; }); angular.forEach(['PUT', 'POST', 'PATCH'], function(method) { $httpBackend[prefix + method] = function(url, data, headers) { return $httpBackend[prefix](method, url, data, headers); }; }); } } function MockHttpExpectation(method, url, data, headers) { this.data = data; this.headers = headers; this.match = function(m, u, d, h) { if (method != m) return false; if (!this.matchUrl(u)) return false; if (angular.isDefined(d) && !this.matchData(d)) return false; if (angular.isDefined(h) && !this.matchHeaders(h)) return false; return true; }; this.matchUrl = function(u) { if (!url) return true; if (angular.isFunction(url.test)) return url.test(u); if (angular.isFunction(url)) return url(u); return url == u; }; this.matchHeaders = function(h) { if (angular.isUndefined(headers)) return true; if (angular.isFunction(headers)) return headers(h); return angular.equals(headers, h); }; this.matchData = function(d) { if (angular.isUndefined(data)) return true; if (data && angular.isFunction(data.test)) return data.test(d); if (data && angular.isFunction(data)) return data(d); if (data && !angular.isString(data)) { return angular.equals(angular.fromJson(angular.toJson(data)), angular.fromJson(d)); } return data == d; }; this.toString = function() { return method + ' ' + url; }; } function createMockXhr() { return new MockXhr(); } function MockXhr() { // hack for testing $http, $httpBackend MockXhr.$$lastInstance = this; this.open = function(method, url, async) { this.$$method = method; this.$$url = url; this.$$async = async; this.$$reqHeaders = {}; this.$$respHeaders = {}; }; this.send = function(data) { this.$$data = data; }; this.setRequestHeader = function(key, value) { this.$$reqHeaders[key] = value; }; this.getResponseHeader = function(name) { // the lookup must be case insensitive, // that's why we try two quick lookups first and full scan last var header = this.$$respHeaders[name]; if (header) return header; name = angular.lowercase(name); header = this.$$respHeaders[name]; if (header) return header; header = undefined; angular.forEach(this.$$respHeaders, function(headerVal, headerName) { if (!header && angular.lowercase(headerName) == name) header = headerVal; }); return header; }; this.getAllResponseHeaders = function() { var lines = []; angular.forEach(this.$$respHeaders, function(value, key) { lines.push(key + ': ' + value); }); return lines.join('\n'); }; this.abort = angular.noop; } /** * @ngdoc service * @name $timeout * @description * * This service is just a simple decorator for {@link ng.$timeout $timeout} service * that adds a "flush" and "verifyNoPendingTasks" methods. */ angular.mock.$TimeoutDecorator = ['$delegate', '$browser', function($delegate, $browser) { /** * @ngdoc method * @name $timeout#flush * @description * * Flushes the queue of pending tasks. * * @param {number=} delay maximum timeout amount to flush up until */ $delegate.flush = function(delay) { $browser.defer.flush(delay); }; /** * @ngdoc method * @name $timeout#verifyNoPendingTasks * @description * * Verifies that there are no pending tasks that need to be flushed. */ $delegate.verifyNoPendingTasks = function() { if ($browser.deferredFns.length) { throw new Error('Deferred tasks to flush (' + $browser.deferredFns.length + '): ' + formatPendingTasksAsString($browser.deferredFns)); } }; function formatPendingTasksAsString(tasks) { var result = []; angular.forEach(tasks, function(task) { result.push('{id: ' + task.id + ', ' + 'time: ' + task.time + '}'); }); return result.join(', '); } return $delegate; }]; angular.mock.$RAFDecorator = ['$delegate', function($delegate) { var queue = []; var rafFn = function(fn) { var index = queue.length; queue.push(fn); return function() { queue.splice(index, 1); }; }; rafFn.supported = $delegate.supported; rafFn.flush = function() { if (queue.length === 0) { throw new Error('No rAF callbacks present'); } var length = queue.length; for (var i = 0; i < length; i++) { queue[i](); } queue = []; }; return rafFn; }]; angular.mock.$AsyncCallbackDecorator = ['$delegate', function($delegate) { var callbacks = []; var addFn = function(fn) { callbacks.push(fn); }; addFn.flush = function() { angular.forEach(callbacks, function(fn) { fn(); }); callbacks = []; }; return addFn; }]; /** * */ angular.mock.$RootElementProvider = function() { this.$get = function() { return angular.element('<div ng-app></div>'); }; }; /** * @ngdoc service * @name $controller * @description * A decorator for {@link ng.$controller} with additional `bindings` parameter, useful when testing * controllers of directives that use {@link $compile#-bindtocontroller- `bindToController`}. * * * ## Example * * ```js * * // Directive definition ... * * myMod.directive('myDirective', { * controller: 'MyDirectiveController', * bindToController: { * name: '@' * } * }); * * * // Controller definition ... * * myMod.controller('MyDirectiveController', ['log', function($log) { * $log.info(this.name); * })]; * * * // In a test ... * * describe('myDirectiveController', function() { * it('should write the bound name to the log', inject(function($controller, $log) { * var ctrl = $controller('MyDirective', { /* no locals &#42;/ }, { name: 'Clark Kent' }); * expect(ctrl.name).toEqual('Clark Kent'); * expect($log.info.logs).toEqual(['Clark Kent']); * }); * }); * * ``` * * @param {Function|string} constructor If called with a function then it's considered to be the * controller constructor function. Otherwise it's considered to be a string which is used * to retrieve the controller constructor using the following steps: * * * check if a controller with given name is registered via `$controllerProvider` * * check if evaluating the string on the current scope returns a constructor * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global * `window` object (not recommended) * * The string can use the `controller as property` syntax, where the controller instance is published * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this * to work correctly. * * @param {Object} locals Injection locals for Controller. * @param {Object=} bindings Properties to add to the controller before invoking the constructor. This is used * to simulate the `bindToController` feature and simplify certain kinds of tests. * @return {Object} Instance of given controller. */ angular.mock.$ControllerDecorator = ['$delegate', function($delegate) { return function(expression, locals, later, ident) { if (later && typeof later === 'object') { var create = $delegate(expression, locals, true, ident); angular.extend(create.instance, later); return create(); } return $delegate(expression, locals, later, ident); }; }]; /** * @ngdoc module * @name ngMock * @packageName angular-mocks * @description * * # ngMock * * The `ngMock` module provides support to inject and mock Angular services into unit tests. * In addition, ngMock also extends various core ng services such that they can be * inspected and controlled in a synchronous manner within test code. * * * <div doc-module-components="ngMock"></div> * */ angular.module('ngMock', ['ng']).provider({ $browser: angular.mock.$BrowserProvider, $exceptionHandler: angular.mock.$ExceptionHandlerProvider, $log: angular.mock.$LogProvider, $interval: angular.mock.$IntervalProvider, $httpBackend: angular.mock.$HttpBackendProvider, $rootElement: angular.mock.$RootElementProvider }).config(['$provide', function($provide) { $provide.decorator('$timeout', angular.mock.$TimeoutDecorator); $provide.decorator('$$rAF', angular.mock.$RAFDecorator); $provide.decorator('$$asyncCallback', angular.mock.$AsyncCallbackDecorator); $provide.decorator('$rootScope', angular.mock.$RootScopeDecorator); $provide.decorator('$controller', angular.mock.$ControllerDecorator); }]); /** * @ngdoc module * @name ngMockE2E * @module ngMockE2E * @packageName angular-mocks * @description * * The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing. * Currently there is only one mock present in this module - * the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock. */ angular.module('ngMockE2E', ['ng']).config(['$provide', function($provide) { $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator); }]); /** * @ngdoc service * @name $httpBackend * @module ngMockE2E * @description * Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of * applications that use the {@link ng.$http $http service}. * * *Note*: For fake http backend implementation suitable for unit testing please see * {@link ngMock.$httpBackend unit-testing $httpBackend mock}. * * This implementation can be used to respond with static or dynamic responses via the `when` api * and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the * real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch * templates from a webserver). * * As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application * is being developed with the real backend api replaced with a mock, it is often desirable for * certain category of requests to bypass the mock and issue a real http request (e.g. to fetch * templates or static files from the webserver). To configure the backend with this behavior * use the `passThrough` request handler of `when` instead of `respond`. * * Additionally, we don't want to manually have to flush mocked out requests like we do during unit * testing. For this reason the e2e $httpBackend flushes mocked out requests * automatically, closely simulating the behavior of the XMLHttpRequest object. * * To setup the application to run with this http backend, you have to create a module that depends * on the `ngMockE2E` and your application modules and defines the fake backend: * * ```js * myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']); * myAppDev.run(function($httpBackend) { * phones = [{name: 'phone1'}, {name: 'phone2'}]; * * // returns the current list of phones * $httpBackend.whenGET('/phones').respond(phones); * * // adds a new phone to the phones array * $httpBackend.whenPOST('/phones').respond(function(method, url, data) { * var phone = angular.fromJson(data); * phones.push(phone); * return [200, phone, {}]; * }); * $httpBackend.whenGET(/^\/templates\//).passThrough(); * //... * }); * ``` * * Afterwards, bootstrap your app with this new module. */ /** * @ngdoc method * @name $httpBackend#when * @module ngMockE2E * @description * Creates a new backend definition. * * @param {string} method HTTP method. * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp)=} data HTTP request body. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current definition. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. * * - respond – * `{function([status,] data[, headers, statusText]) * | function(function(method, url, data, headers)}` * – The respond method takes a set of static data to be returned or a function that can return * an array containing response status (number), response data (string), response headers * (Object), and the text for the status (string). * - passThrough – `{function()}` – Any request matching a backend definition with * `passThrough` handler will be passed through to the real backend (an XHR request will be made * to the server.) * - Both methods return the `requestHandler` object for possible overrides. */ /** * @ngdoc method * @name $httpBackend#whenGET * @module ngMockE2E * @description * Creates a new backend definition for GET requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenHEAD * @module ngMockE2E * @description * Creates a new backend definition for HEAD requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenDELETE * @module ngMockE2E * @description * Creates a new backend definition for DELETE requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenPOST * @module ngMockE2E * @description * Creates a new backend definition for POST requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp)=} data HTTP request body. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenPUT * @module ngMockE2E * @description * Creates a new backend definition for PUT requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp)=} data HTTP request body. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenPATCH * @module ngMockE2E * @description * Creates a new backend definition for PATCH requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @param {(string|RegExp)=} data HTTP request body. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenJSONP * @module ngMockE2E * @description * Creates a new backend definition for JSONP requests. For more info see `when()`. * * @param {string|RegExp|function(string)} url HTTP url or function that receives the url * and returns true if the url match the current definition. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ angular.mock.e2e = {}; angular.mock.e2e.$httpBackendDecorator = ['$rootScope', '$timeout', '$delegate', '$browser', createHttpBackendMock]; /** * @ngdoc type * @name $rootScope.Scope * @module ngMock * @description * {@link ng.$rootScope.Scope Scope} type decorated with helper methods useful for testing. These * methods are automatically available on any {@link ng.$rootScope.Scope Scope} instance when * `ngMock` module is loaded. * * In addition to all the regular `Scope` methods, the following helper methods are available: */ angular.mock.$RootScopeDecorator = ['$delegate', function($delegate) { var $rootScopePrototype = Object.getPrototypeOf($delegate); $rootScopePrototype.$countChildScopes = countChildScopes; $rootScopePrototype.$countWatchers = countWatchers; return $delegate; // ------------------------------------------------------------------------------------------ // /** * @ngdoc method * @name $rootScope.Scope#$countChildScopes * @module ngMock * @description * Counts all the direct and indirect child scopes of the current scope. * * The current scope is excluded from the count. The count includes all isolate child scopes. * * @returns {number} Total number of child scopes. */ function countChildScopes() { // jshint validthis: true var count = 0; // exclude the current scope var pendingChildHeads = [this.$$childHead]; var currentScope; while (pendingChildHeads.length) { currentScope = pendingChildHeads.shift(); while (currentScope) { count += 1; pendingChildHeads.push(currentScope.$$childHead); currentScope = currentScope.$$nextSibling; } } return count; } /** * @ngdoc method * @name $rootScope.Scope#$countWatchers * @module ngMock * @description * Counts all the watchers of direct and indirect child scopes of the current scope. * * The watchers of the current scope are included in the count and so are all the watchers of * isolate child scopes. * * @returns {number} Total number of watchers. */ function countWatchers() { // jshint validthis: true var count = this.$$watchers ? this.$$watchers.length : 0; // include the current scope var pendingChildHeads = [this.$$childHead]; var currentScope; while (pendingChildHeads.length) { currentScope = pendingChildHeads.shift(); while (currentScope) { count += currentScope.$$watchers ? currentScope.$$watchers.length : 0; pendingChildHeads.push(currentScope.$$childHead); currentScope = currentScope.$$nextSibling; } } return count; } }]; if (window.jasmine || window.mocha) { var currentSpec = null, annotatedFunctions = [], isSpecRunning = function() { return !!currentSpec; }; angular.mock.$$annotate = angular.injector.$$annotate; angular.injector.$$annotate = function(fn) { if (typeof fn === 'function' && !fn.$inject) { annotatedFunctions.push(fn); } return angular.mock.$$annotate.apply(this, arguments); }; (window.beforeEach || window.setup)(function() { annotatedFunctions = []; currentSpec = this; }); (window.afterEach || window.teardown)(function() { var injector = currentSpec.$injector; annotatedFunctions.forEach(function(fn) { delete fn.$inject; }); angular.forEach(currentSpec.$modules, function(module) { if (module && module.$$hashKey) { module.$$hashKey = undefined; } }); currentSpec.$injector = null; currentSpec.$modules = null; currentSpec = null; if (injector) { injector.get('$rootElement').off(); injector.get('$browser').pollFns.length = 0; } // clean up jquery's fragment cache angular.forEach(angular.element.fragments, function(val, key) { delete angular.element.fragments[key]; }); MockXhr.$$lastInstance = null; angular.forEach(angular.callbacks, function(val, key) { delete angular.callbacks[key]; }); angular.callbacks.counter = 0; }); /** * @ngdoc function * @name angular.mock.module * @description * * *NOTE*: This function is also published on window for easy access.<br> * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha * * This function registers a module configuration code. It collects the configuration information * which will be used when the injector is created by {@link angular.mock.inject inject}. * * See {@link angular.mock.inject inject} for usage example * * @param {...(string|Function|Object)} fns any number of modules which are represented as string * aliases or as anonymous module initialization functions. The modules are used to * configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. If an * object literal is passed they will be registered as values in the module, the key being * the module name and the value being what is returned. */ window.module = angular.mock.module = function() { var moduleFns = Array.prototype.slice.call(arguments, 0); return isSpecRunning() ? workFn() : workFn; ///////////////////// function workFn() { if (currentSpec.$injector) { throw new Error('Injector already created, can not register a module!'); } else { var modules = currentSpec.$modules || (currentSpec.$modules = []); angular.forEach(moduleFns, function(module) { if (angular.isObject(module) && !angular.isArray(module)) { modules.push(function($provide) { angular.forEach(module, function(value, key) { $provide.value(key, value); }); }); } else { modules.push(module); } }); } } }; /** * @ngdoc function * @name angular.mock.inject * @description * * *NOTE*: This function is also published on window for easy access.<br> * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha * * The inject function wraps a function into an injectable function. The inject() creates new * instance of {@link auto.$injector $injector} per test, which is then used for * resolving references. * * * ## Resolving References (Underscore Wrapping) * Often, we would like to inject a reference once, in a `beforeEach()` block and reuse this * in multiple `it()` clauses. To be able to do this we must assign the reference to a variable * that is declared in the scope of the `describe()` block. Since we would, most likely, want * the variable to have the same name of the reference we have a problem, since the parameter * to the `inject()` function would hide the outer variable. * * To help with this, the injected parameters can, optionally, be enclosed with underscores. * These are ignored by the injector when the reference name is resolved. * * For example, the parameter `_myService_` would be resolved as the reference `myService`. * Since it is available in the function body as _myService_, we can then assign it to a variable * defined in an outer scope. * * ``` * // Defined out reference variable outside * var myService; * * // Wrap the parameter in underscores * beforeEach( inject( function(_myService_){ * myService = _myService_; * })); * * // Use myService in a series of tests. * it('makes use of myService', function() { * myService.doStuff(); * }); * * ``` * * See also {@link angular.mock.module angular.mock.module} * * ## Example * Example of what a typical jasmine tests looks like with the inject method. * ```js * * angular.module('myApplicationModule', []) * .value('mode', 'app') * .value('version', 'v1.0.1'); * * * describe('MyApp', function() { * * // You need to load modules that you want to test, * // it loads only the "ng" module by default. * beforeEach(module('myApplicationModule')); * * * // inject() is used to inject arguments of all given functions * it('should provide a version', inject(function(mode, version) { * expect(version).toEqual('v1.0.1'); * expect(mode).toEqual('app'); * })); * * * // The inject and module method can also be used inside of the it or beforeEach * it('should override a version and test the new version is injected', function() { * // module() takes functions or strings (module aliases) * module(function($provide) { * $provide.value('version', 'overridden'); // override version here * }); * * inject(function(version) { * expect(version).toEqual('overridden'); * }); * }); * }); * * ``` * * @param {...Function} fns any number of functions which will be injected using the injector. */ var ErrorAddingDeclarationLocationStack = function(e, errorForStack) { this.message = e.message; this.name = e.name; if (e.line) this.line = e.line; if (e.sourceId) this.sourceId = e.sourceId; if (e.stack && errorForStack) this.stack = e.stack + '\n' + errorForStack.stack; if (e.stackArray) this.stackArray = e.stackArray; }; ErrorAddingDeclarationLocationStack.prototype.toString = Error.prototype.toString; window.inject = angular.mock.inject = function() { var blockFns = Array.prototype.slice.call(arguments, 0); var errorForStack = new Error('Declaration Location'); return isSpecRunning() ? workFn.call(currentSpec) : workFn; ///////////////////// function workFn() { var modules = currentSpec.$modules || []; var strictDi = !!currentSpec.$injectorStrict; modules.unshift('ngMock'); modules.unshift('ng'); var injector = currentSpec.$injector; if (!injector) { if (strictDi) { // If strictDi is enabled, annotate the providerInjector blocks angular.forEach(modules, function(moduleFn) { if (typeof moduleFn === "function") { angular.injector.$$annotate(moduleFn); } }); } injector = currentSpec.$injector = angular.injector(modules, strictDi); currentSpec.$injectorStrict = strictDi; } for (var i = 0, ii = blockFns.length; i < ii; i++) { if (currentSpec.$injectorStrict) { // If the injector is strict / strictDi, and the spec wants to inject using automatic // annotation, then annotate the function here. injector.annotate(blockFns[i]); } try { /* jshint -W040 *//* Jasmine explicitly provides a `this` object when calling functions */ injector.invoke(blockFns[i] || angular.noop, this); /* jshint +W040 */ } catch (e) { if (e.stack && errorForStack) { throw new ErrorAddingDeclarationLocationStack(e, errorForStack); } throw e; } finally { errorForStack = null; } } } }; angular.mock.inject.strictDi = function(value) { value = arguments.length ? !!value : true; return isSpecRunning() ? workFn() : workFn; function workFn() { if (value !== currentSpec.$injectorStrict) { if (currentSpec.$injector) { throw new Error('Injector already created, can not modify strict annotations'); } else { currentSpec.$injectorStrict = value; } } } }; } })(window, window.angular);
DreamInSun/OneRing
xdiamond/bower_components/angular-mocks/angular-mocks.js
JavaScript
apache-2.0
82,636
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Validate * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: $ */ /** * @see Zend_Validate_File_Exists */ require_once 'Zend/Validate/File/Exists.php'; /** * Validator which checks if the destination file does not exist * * @category Zend * @package Zend_Validate * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Validate_File_NotExists extends Zend_Validate_File_Exists { /** * @const string Error constants */ const DOES_EXIST = 'fileNotExistsDoesExist'; /** * @var array Error message templates */ protected $_messageTemplates = array( self::DOES_EXIST => "The file '%value%' does exist" ); /** * Defined by Zend_Validate_Interface * * Returns true if and only if the file does not exist in the set destinations * * @param string $value Real file to check for * @param array $file File data from Zend_File_Transfer * @return boolean */ public function isValid($value, $file = null) { $directories = $this->getDirectory(true); if (($file !== null) and (!empty($file['destination']))) { $directories[] = $file['destination']; } else if (!isset($file['name'])) { $file['name'] = $value; } foreach ($directories as $directory) { if (empty($directory)) { continue; } $check = true; if (file_exists($directory . DIRECTORY_SEPARATOR . $file['name'])) { $this->_throw($file, self::DOES_EXIST); return false; } } if (!isset($check)) { $this->_throw($file, self::DOES_EXIST); return false; } return true; } }
jsRuner/wuwenfu.cn
wp-includes/phpQuery/phpQuery/Zend/Validate/File/NotExists.php
PHP
gpl-2.0
2,520
class MemberDetail < ActiveRecord::Base belongs_to :member belongs_to :organization has_one :member_type, :through => :member end
maccman/dtwitter
vendor/rails/activerecord/test/models/member_detail.rb
Ruby
mit
136
<?php /** * WordPress CRON API * * @package WordPress */ /** * Schedules a hook to run only once. * * Schedules a hook which will be executed once by the WordPress actions core at * a time which you specify. The action will fire off when someone visits your * WordPress site, if the schedule time has passed. * * @since 2.1.0 * @link http://codex.wordpress.org/Function_Reference/wp_schedule_single_event * * @param int $timestamp Timestamp for when to run the event. * @param string $hook Action hook to execute when cron is run. * @param array $args Optional. Arguments to pass to the hook's callback function. */ function wp_schedule_single_event( $timestamp, $hook, $args = array()) { // don't schedule a duplicate if there's already an identical event due in the next 10 minutes $next = wp_next_scheduled($hook, $args); if ( $next && $next <= $timestamp + 600 ) return; $crons = _get_cron_array(); $event = (object) array( 'hook' => $hook, 'timestamp' => $timestamp, 'schedule' => false, 'args' => $args ); $event = apply_filters('schedule_event', $event); // A plugin disallowed this event if ( ! $event ) return false; $key = md5(serialize($event->args)); $crons[$event->timestamp][$event->hook][$key] = array( 'schedule' => $event->schedule, 'args' => $event->args ); uksort( $crons, "strnatcasecmp" ); _set_cron_array( $crons ); } /** * Schedule a periodic event. * * Schedules a hook which will be executed by the WordPress actions core on a * specific interval, specified by you. The action will trigger when someone * visits your WordPress site, if the scheduled time has passed. * * Valid values for the recurrence are hourly, daily and twicedaily. These can * be extended using the cron_schedules filter in wp_get_schedules(). * * Use wp_next_scheduled() to prevent duplicates * * @since 2.1.0 * * @param int $timestamp Timestamp for when to run the event. * @param string $recurrence How often the event should recur. * @param string $hook Action hook to execute when cron is run. * @param array $args Optional. Arguments to pass to the hook's callback function. * @return bool|null False on failure, null when complete with scheduling event. */ function wp_schedule_event( $timestamp, $recurrence, $hook, $args = array()) { $crons = _get_cron_array(); $schedules = wp_get_schedules(); if ( !isset( $schedules[$recurrence] ) ) return false; $event = (object) array( 'hook' => $hook, 'timestamp' => $timestamp, 'schedule' => $recurrence, 'args' => $args, 'interval' => $schedules[$recurrence]['interval'] ); $event = apply_filters('schedule_event', $event); // A plugin disallowed this event if ( ! $event ) return false; $key = md5(serialize($event->args)); $crons[$event->timestamp][$event->hook][$key] = array( 'schedule' => $event->schedule, 'args' => $event->args, 'interval' => $event->interval ); uksort( $crons, "strnatcasecmp" ); _set_cron_array( $crons ); } /** * Reschedule a recurring event. * * @since 2.1.0 * * @param int $timestamp Timestamp for when to run the event. * @param string $recurrence How often the event should recur. * @param string $hook Action hook to execute when cron is run. * @param array $args Optional. Arguments to pass to the hook's callback function. * @return bool|null False on failure. Null when event is rescheduled. */ function wp_reschedule_event( $timestamp, $recurrence, $hook, $args = array()) { $crons = _get_cron_array(); $schedules = wp_get_schedules(); $key = md5(serialize($args)); $interval = 0; // First we try to get it from the schedule if ( 0 == $interval ) $interval = $schedules[$recurrence]['interval']; // Now we try to get it from the saved interval in case the schedule disappears if ( 0 == $interval ) $interval = $crons[$timestamp][$hook][$key]['interval']; // Now we assume something is wrong and fail to schedule if ( 0 == $interval ) return false; $now = time(); if ( $timestamp >= $now ) $timestamp = $now + $interval; else $timestamp = $now + ($interval - (($now - $timestamp) % $interval)); wp_schedule_event( $timestamp, $recurrence, $hook, $args ); } /** * Unschedule a previously scheduled cron job. * * The $timestamp and $hook parameters are required, so that the event can be * identified. * * @since 2.1.0 * * @param int $timestamp Timestamp for when to run the event. * @param string $hook Action hook, the execution of which will be unscheduled. * @param array $args Arguments to pass to the hook's callback function. * Although not passed to a callback function, these arguments are used * to uniquely identify the scheduled event, so they should be the same * as those used when originally scheduling the event. */ function wp_unschedule_event( $timestamp, $hook, $args = array() ) { $crons = _get_cron_array(); $key = md5(serialize($args)); unset( $crons[$timestamp][$hook][$key] ); if ( empty($crons[$timestamp][$hook]) ) unset( $crons[$timestamp][$hook] ); if ( empty($crons[$timestamp]) ) unset( $crons[$timestamp] ); _set_cron_array( $crons ); } /** * Unschedule all cron jobs attached to a specific hook. * * @since 2.1.0 * * @param string $hook Action hook, the execution of which will be unscheduled. * @param array $args Optional. Arguments that were to be pass to the hook's callback function. */ function wp_clear_scheduled_hook( $hook, $args = array() ) { // Backward compatibility // Previously this function took the arguments as discrete vars rather than an array like the rest of the API if ( !is_array($args) ) { _deprecated_argument( __FUNCTION__, '3.0', __('This argument has changed to an array to match the behavior of the other cron functions.') ); $args = array_slice( func_get_args(), 1 ); } while ( $timestamp = wp_next_scheduled( $hook, $args ) ) wp_unschedule_event( $timestamp, $hook, $args ); } /** * Retrieve the next timestamp for a cron event. * * @since 2.1.0 * * @param string $hook Action hook to execute when cron is run. * @param array $args Optional. Arguments to pass to the hook's callback function. * @return bool|int The UNIX timestamp of the next time the scheduled event will occur. */ function wp_next_scheduled( $hook, $args = array() ) { $crons = _get_cron_array(); $key = md5(serialize($args)); if ( empty($crons) ) return false; foreach ( $crons as $timestamp => $cron ) { if ( isset( $cron[$hook][$key] ) ) return $timestamp; } return false; } /** * Send request to run cron through HTTP request that doesn't halt page loading. * * @since 2.1.0 * * @return null Cron could not be spawned, because it is not needed to run. */ function spawn_cron( $local_time = 0 ) { if ( !$local_time ) $local_time = time(); if ( defined('DOING_CRON') || isset($_GET['doing_wp_cron']) ) return; /* * multiple processes on multiple web servers can run this code concurrently * try to make this as atomic as possible by setting doing_cron switch */ $lock = get_transient('doing_cron'); if ( $lock > $local_time + 10*60 ) $lock = 0; // don't run if another process is currently running it or more than once every 60 sec. if ( $lock + WP_CRON_LOCK_TIMEOUT > $local_time ) return; //sanity check $crons = _get_cron_array(); if ( !is_array($crons) ) return; $keys = array_keys( $crons ); if ( isset($keys[0]) && $keys[0] > $local_time ) return; if ( defined('ALTERNATE_WP_CRON') && ALTERNATE_WP_CRON ) { if ( !empty($_POST) || defined('DOING_AJAX') ) return; $doing_wp_cron = $local_time; set_transient( 'doing_cron', $doing_wp_cron ); ob_start(); wp_redirect( add_query_arg('doing_wp_cron', $doing_wp_cron, stripslashes($_SERVER['REQUEST_URI'])) ); echo ' '; // flush any buffers and send the headers while ( @ob_end_flush() ); flush(); WP_DEBUG ? include_once( ABSPATH . 'wp-cron.php' ) : @include_once( ABSPATH . 'wp-cron.php' ); return; } $doing_wp_cron = $local_time; set_transient( 'doing_cron', $doing_wp_cron ); $cron_url = get_option( 'siteurl' ) . '/wp-cron.php?doing_wp_cron=' . $doing_wp_cron; wp_remote_post( $cron_url, array('timeout' => 0.01, 'blocking' => false, 'sslverify' => apply_filters('https_local_ssl_verify', true)) ); } /** * Run scheduled callbacks or spawn cron for all scheduled events. * * @since 2.1.0 * * @return null When doesn't need to run Cron. */ function wp_cron() { // Prevent infinite loops caused by lack of wp-cron.php if ( strpos($_SERVER['REQUEST_URI'], '/wp-cron.php') !== false || ( defined('DISABLE_WP_CRON') && DISABLE_WP_CRON ) ) return; if ( false === $crons = _get_cron_array() ) return; $local_time = time(); $keys = array_keys( $crons ); if ( isset($keys[0]) && $keys[0] > $local_time ) return; $schedules = wp_get_schedules(); foreach ( $crons as $timestamp => $cronhooks ) { if ( $timestamp > $local_time ) break; foreach ( (array) $cronhooks as $hook => $args ) { if ( isset($schedules[$hook]['callback']) && !call_user_func( $schedules[$hook]['callback'] ) ) continue; spawn_cron( $local_time ); break 2; } } } /** * Retrieve supported and filtered Cron recurrences. * * The supported recurrences are 'hourly' and 'daily'. A plugin may add more by * hooking into the 'cron_schedules' filter. The filter accepts an array of * arrays. The outer array has a key that is the name of the schedule or for * example 'weekly'. The value is an array with two keys, one is 'interval' and * the other is 'display'. * * The 'interval' is a number in seconds of when the cron job should run. So for * 'hourly', the time is 3600 or 60*60. For weekly, the value would be * 60*60*24*7 or 604800. The value of 'interval' would then be 604800. * * The 'display' is the description. For the 'weekly' key, the 'display' would * be <code>__('Once Weekly')</code>. * * For your plugin, you will be passed an array. you can easily add your * schedule by doing the following. * <code> * // filter parameter variable name is 'array' * $array['weekly'] = array( * 'interval' => 604800, * 'display' => __('Once Weekly') * ); * </code> * * @since 2.1.0 * * @return array */ function wp_get_schedules() { $schedules = array( 'hourly' => array( 'interval' => 3600, 'display' => __('Once Hourly') ), 'twicedaily' => array( 'interval' => 43200, 'display' => __('Twice Daily') ), 'daily' => array( 'interval' => 86400, 'display' => __('Once Daily') ), ); return array_merge( apply_filters( 'cron_schedules', array() ), $schedules ); } /** * Retrieve Cron schedule for hook with arguments. * * @since 2.1.0 * * @param string $hook Action hook to execute when cron is run. * @param array $args Optional. Arguments to pass to the hook's callback function. * @return string|bool False, if no schedule. Schedule on success. */ function wp_get_schedule($hook, $args = array()) { $crons = _get_cron_array(); $key = md5(serialize($args)); if ( empty($crons) ) return false; foreach ( $crons as $timestamp => $cron ) { if ( isset( $cron[$hook][$key] ) ) return $cron[$hook][$key]['schedule']; } return false; } // // Private functions // /** * Retrieve cron info array option. * * @since 2.1.0 * @access private * * @return array CRON info array. */ function _get_cron_array() { $cron = get_option('cron'); if ( ! is_array($cron) ) return false; if ( !isset($cron['version']) ) $cron = _upgrade_cron_array($cron); unset($cron['version']); return $cron; } /** * Updates the CRON option with the new CRON array. * * @since 2.1.0 * @access private * * @param array $cron Cron info array from {@link _get_cron_array()}. */ function _set_cron_array($cron) { $cron['version'] = 2; update_option( 'cron', $cron ); } /** * Upgrade a Cron info array. * * This function upgrades the Cron info array to version 2. * * @since 2.1.0 * @access private * * @param array $cron Cron info array from {@link _get_cron_array()}. * @return array An upgraded Cron info array. */ function _upgrade_cron_array($cron) { if ( isset($cron['version']) && 2 == $cron['version']) return $cron; $new_cron = array(); foreach ( (array) $cron as $timestamp => $hooks) { foreach ( (array) $hooks as $hook => $args ) { $key = md5(serialize($args['args'])); $new_cron[$timestamp][$hook][$key] = $args; } } $new_cron['version'] = 2; update_option( 'cron', $new_cron ); return $new_cron; }
andres-torres-marroquin/casa-camila
wp-includes/cron.php
PHP
gpl-2.0
12,428
/* Copyright 2014 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "fmt" "os" "runtime" "k8s.io/kubernetes/cmd/kube-proxy/app" "k8s.io/kubernetes/pkg/healthz" "k8s.io/kubernetes/pkg/util" "k8s.io/kubernetes/pkg/version/verflag" "github.com/spf13/pflag" ) func init() { healthz.DefaultHealthz() } func main() { runtime.GOMAXPROCS(runtime.NumCPU()) s := app.NewProxyServer() s.AddFlags(pflag.CommandLine) util.InitFlags() util.InitLogs() defer util.FlushLogs() verflag.PrintAndExitIfRequested() if err := s.Run(pflag.CommandLine.Args()); err != nil { fmt.Fprintf(os.Stderr, "%v\n", err) os.Exit(1) } }
StevenLudwig/kubernetes
cmd/kube-proxy/proxy.go
GO
apache-2.0
1,176
import parse = require('xml-parser'); declare var assert: { equal<T>(a: T, b: T): void }; var doc: parse.Document = parse( '<?xml version="1.0" encoding="utf-8"?>' + '<mydoc><child a="1">foo</child><child/></mydoc>'); var declaration: parse.Declaration = doc.declaration; assert.equal(declaration.attributes['version'], '1.0'); assert.equal(declaration.attributes['encoding'], 'utf-8'); var root: parse.Node = doc.root; assert.equal(root.name, 'mydoc'); var children: parse.Node[] = root.children; assert.equal(children.length, 2); var child1: parse.Node = children[0]; assert.equal(child1.name, 'child'); assert.equal(child1.attributes['a'], '1'); assert.equal(child1.content, 'foo');
aaronryden/DefinitelyTyped
types/xml-parser/xml-parser-tests.ts
TypeScript
mit
693
let arr = []; for(let i = 0; i < 10; i++) { for (let i = 0; i < 10; i++) { arr.push(() => i); } }
ellbee/babel
test/core/fixtures/transformation/es6.block-scoping/issue-973/actual.js
JavaScript
mit
106
// basic_types.hpp --------------------------------------------------------------// // Copyright 2010 Vicente J. Botet Escriba // Copyright 2015 Andrey Semashev // Distributed under the Boost Software License, Version 1.0. // See http://www.boost.org/LICENSE_1_0.txt #ifndef BOOST_DETAIL_WINAPI_BASIC_TYPES_HPP #define BOOST_DETAIL_WINAPI_BASIC_TYPES_HPP #include <cstdarg> #include <boost/cstdint.hpp> #include <boost/detail/winapi/config.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif #if defined( BOOST_USE_WINDOWS_H ) # include <windows.h> #elif defined( WIN32 ) || defined( _WIN32 ) || defined( __WIN32__ ) || defined(__CYGWIN__) # include <winerror.h> # ifdef UNDER_CE # ifndef WINAPI # ifndef _WIN32_WCE_EMULATION # define WINAPI __cdecl // Note this doesn't match the desktop definition # else # define WINAPI __stdcall # endif # endif // Windows CE defines a few functions as inline functions in kfuncs.h typedef int BOOL; typedef unsigned long DWORD; typedef void* HANDLE; # include <kfuncs.h> # else # ifndef WINAPI # define WINAPI __stdcall # endif # endif # ifndef NTAPI # define NTAPI __stdcall # endif #else # error "Win32 functions not available" #endif #ifndef NO_STRICT #ifndef STRICT #define STRICT 1 #endif #endif #if defined(STRICT) #define BOOST_DETAIL_WINAPI_DECLARE_HANDLE(x) struct x##__; typedef struct x##__ *x #else #define BOOST_DETAIL_WINAPI_DECLARE_HANDLE(x) typedef void* x #endif #if !defined( BOOST_USE_WINDOWS_H ) extern "C" { union _LARGE_INTEGER; struct _SECURITY_ATTRIBUTES; BOOST_DETAIL_WINAPI_DECLARE_HANDLE(HINSTANCE); typedef HINSTANCE HMODULE; } #endif #if defined(__GNUC__) #define BOOST_DETAIL_WINAPI_MAY_ALIAS __attribute__ ((__may_alias__)) #else #define BOOST_DETAIL_WINAPI_MAY_ALIAS #endif // MinGW64 gcc 4.8.2 fails to compile function declarations with boost::detail::winapi::VOID_ arguments even though // the typedef expands to void. In Windows SDK, VOID is a macro which unfolds to void. We use our own macro in such cases. #define BOOST_DETAIL_WINAPI_VOID void namespace boost { namespace detail { namespace winapi { #if defined( BOOST_USE_WINDOWS_H ) typedef ::BOOL BOOL_; typedef ::PBOOL PBOOL_; typedef ::LPBOOL LPBOOL_; typedef ::BOOLEAN BOOLEAN_; typedef ::PBOOLEAN PBOOLEAN_; typedef ::BYTE BYTE_; typedef ::PBYTE PBYTE_; typedef ::LPBYTE LPBYTE_; typedef ::WORD WORD_; typedef ::PWORD PWORD_; typedef ::LPWORD LPWORD_; typedef ::DWORD DWORD_; typedef ::PDWORD PDWORD_; typedef ::LPDWORD LPDWORD_; typedef ::HANDLE HANDLE_; typedef ::PHANDLE PHANDLE_; typedef ::SHORT SHORT_; typedef ::PSHORT PSHORT_; typedef ::USHORT USHORT_; typedef ::PUSHORT PUSHORT_; typedef ::INT INT_; typedef ::PINT PINT_; typedef ::LPINT LPINT_; typedef ::UINT UINT_; typedef ::PUINT PUINT_; typedef ::LONG LONG_; typedef ::PLONG PLONG_; typedef ::LPLONG LPLONG_; typedef ::ULONG ULONG_; typedef ::PULONG PULONG_; typedef ::LONGLONG LONGLONG_; typedef ::ULONGLONG ULONGLONG_; typedef ::INT_PTR INT_PTR_; typedef ::UINT_PTR UINT_PTR_; typedef ::LONG_PTR LONG_PTR_; typedef ::ULONG_PTR ULONG_PTR_; typedef ::DWORD_PTR DWORD_PTR_; typedef ::PDWORD_PTR PDWORD_PTR_; typedef ::SIZE_T SIZE_T_; typedef ::PSIZE_T PSIZE_T_; typedef ::SSIZE_T SSIZE_T_; typedef ::PSSIZE_T PSSIZE_T_; typedef VOID VOID_; // VOID is a macro typedef ::PVOID PVOID_; typedef ::LPVOID LPVOID_; typedef ::LPCVOID LPCVOID_; typedef ::CHAR CHAR_; typedef ::LPSTR LPSTR_; typedef ::LPCSTR LPCSTR_; typedef ::WCHAR WCHAR_; typedef ::LPWSTR LPWSTR_; typedef ::LPCWSTR LPCWSTR_; #else // defined( BOOST_USE_WINDOWS_H ) typedef int BOOL_; typedef BOOL_* PBOOL_; typedef BOOL_* LPBOOL_; typedef unsigned char BYTE_; typedef BYTE_* PBYTE_; typedef BYTE_* LPBYTE_; typedef BYTE_ BOOLEAN_; typedef BOOLEAN_* PBOOLEAN_; typedef unsigned short WORD_; typedef WORD_* PWORD_; typedef WORD_* LPWORD_; typedef unsigned long DWORD_; typedef DWORD_* PDWORD_; typedef DWORD_* LPDWORD_; typedef void* HANDLE_; typedef void** PHANDLE_; typedef short SHORT_; typedef SHORT_* PSHORT_; typedef unsigned short USHORT_; typedef USHORT_* PUSHORT_; typedef int INT_; typedef INT_* PINT_; typedef INT_* LPINT_; typedef unsigned int UINT_; typedef UINT_* PUINT_; typedef long LONG_; typedef LONG_* PLONG_; typedef LONG_* LPLONG_; typedef unsigned long ULONG_; typedef ULONG_* PULONG_; typedef boost::int64_t LONGLONG_; typedef boost::uint64_t ULONGLONG_; # ifdef _WIN64 # if defined(__CYGWIN__) typedef long INT_PTR_; typedef unsigned long UINT_PTR_; typedef long LONG_PTR_; typedef unsigned long ULONG_PTR_; # else typedef __int64 INT_PTR_; typedef unsigned __int64 UINT_PTR_; typedef __int64 LONG_PTR_; typedef unsigned __int64 ULONG_PTR_; # endif # else typedef int INT_PTR_; typedef unsigned int UINT_PTR_; typedef long LONG_PTR_; typedef unsigned long ULONG_PTR_; # endif typedef ULONG_PTR_ DWORD_PTR_, *PDWORD_PTR_; typedef ULONG_PTR_ SIZE_T_, *PSIZE_T_; typedef LONG_PTR_ SSIZE_T_, *PSSIZE_T_; typedef void VOID_; typedef void *PVOID_; typedef void *LPVOID_; typedef const void *LPCVOID_; typedef char CHAR_; typedef CHAR_ *LPSTR_; typedef const CHAR_ *LPCSTR_; typedef wchar_t WCHAR_; typedef WCHAR_ *LPWSTR_; typedef const WCHAR_ *LPCWSTR_; #endif // defined( BOOST_USE_WINDOWS_H ) typedef ::HMODULE HMODULE_; typedef union BOOST_DETAIL_WINAPI_MAY_ALIAS _LARGE_INTEGER { struct { DWORD_ LowPart; LONG_ HighPart; } u; LONGLONG_ QuadPart; } LARGE_INTEGER_, *PLARGE_INTEGER_; typedef struct BOOST_DETAIL_WINAPI_MAY_ALIAS _SECURITY_ATTRIBUTES { DWORD_ nLength; LPVOID_ lpSecurityDescriptor; BOOL_ bInheritHandle; } SECURITY_ATTRIBUTES_, *PSECURITY_ATTRIBUTES_, *LPSECURITY_ATTRIBUTES_; } } } #endif // BOOST_DETAIL_WINAPI_BASIC_TYPES_HPP
nealkruis/kiva
vendor/boost-1.61.0/boost/detail/winapi/basic_types.hpp
C++
gpl-3.0
5,732
<?php /** * Exception for 503 Service Unavailable responses * * @package Requests */ /** * Exception for 503 Service Unavailable responses * * @package Requests */ class Requests_Exception_HTTP_503 extends Requests_Exception_HTTP { /** * HTTP status code * * @var integer */ protected $code = 503; /** * Reason phrase * * @var string */ protected $reason = 'Service Unavailable'; }
dexxtr/osbb-web-manager
www/wp-includes/Requests/Exception/HTTP/503.php
PHP
gpl-3.0
411
/*! * jQuery Cycle Plugin (with Transition Definitions) * Examples and documentation at: http://jquery.malsup.com/cycle/ * Copyright (c) 2007-2013 M. Alsup * Version: 3.0.3 (11-JUL-2013) * Dual licensed under the MIT and GPL licenses. * http://jquery.malsup.com/license.html * Requires: jQuery v1.7.1 or later */ ;(function($, undefined) { "use strict"; var ver = '3.0.3'; function debug(s) { if ($.fn.cycle.debug) log(s); } function log() { /*global console */ if (window.console && console.log) console.log('[cycle] ' + Array.prototype.join.call(arguments,' ')); } $.expr[':'].paused = function(el) { return el.cyclePause; }; // the options arg can be... // a number - indicates an immediate transition should occur to the given slide index // a string - 'pause', 'resume', 'toggle', 'next', 'prev', 'stop', 'destroy' or the name of a transition effect (ie, 'fade', 'zoom', etc) // an object - properties to control the slideshow // // the arg2 arg can be... // the name of an fx (only used in conjunction with a numeric value for 'options') // the value true (only used in first arg == 'resume') and indicates // that the resume should occur immediately (not wait for next timeout) $.fn.cycle = function(options, arg2) { var o = { s: this.selector, c: this.context }; // in 1.3+ we can fix mistakes with the ready state if (this.length === 0 && options != 'stop') { if (!$.isReady && o.s) { log('DOM not ready, queuing slideshow'); $(function() { $(o.s,o.c).cycle(options,arg2); }); return this; } // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready() log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)')); return this; } // iterate the matched nodeset return this.each(function() { var opts = handleArguments(this, options, arg2); if (opts === false) return; opts.updateActivePagerLink = opts.updateActivePagerLink || $.fn.cycle.updateActivePagerLink; // stop existing slideshow for this container (if there is one) if (this.cycleTimeout) clearTimeout(this.cycleTimeout); this.cycleTimeout = this.cyclePause = 0; this.cycleStop = 0; // issue #108 var $cont = $(this); var $slides = opts.slideExpr ? $(opts.slideExpr, this) : $cont.children(); var els = $slides.get(); if (els.length < 2) { log('terminating; too few slides: ' + els.length); return; } var opts2 = buildOptions($cont, $slides, els, opts, o); if (opts2 === false) return; var startTime = opts2.continuous ? 10 : getTimeout(els[opts2.currSlide], els[opts2.nextSlide], opts2, !opts2.backwards); // if it's an auto slideshow, kick it off if (startTime) { startTime += (opts2.delay || 0); if (startTime < 10) startTime = 10; debug('first timeout: ' + startTime); this.cycleTimeout = setTimeout(function(){go(els,opts2,0,!opts.backwards);}, startTime); } }); }; function triggerPause(cont, byHover, onPager) { var opts = $(cont).data('cycle.opts'); if (!opts) return; var paused = !!cont.cyclePause; if (paused && opts.paused) opts.paused(cont, opts, byHover, onPager); else if (!paused && opts.resumed) opts.resumed(cont, opts, byHover, onPager); } // process the args that were passed to the plugin fn function handleArguments(cont, options, arg2) { if (cont.cycleStop === undefined) cont.cycleStop = 0; if (options === undefined || options === null) options = {}; if (options.constructor == String) { switch(options) { case 'destroy': case 'stop': var opts = $(cont).data('cycle.opts'); if (!opts) return false; cont.cycleStop++; // callbacks look for change if (cont.cycleTimeout) clearTimeout(cont.cycleTimeout); cont.cycleTimeout = 0; if (opts.elements) $(opts.elements).stop(); $(cont).removeData('cycle.opts'); if (options == 'destroy') destroy(cont, opts); return false; case 'toggle': cont.cyclePause = (cont.cyclePause === 1) ? 0 : 1; checkInstantResume(cont.cyclePause, arg2, cont); triggerPause(cont); return false; case 'pause': cont.cyclePause = 1; triggerPause(cont); return false; case 'resume': cont.cyclePause = 0; checkInstantResume(false, arg2, cont); triggerPause(cont); return false; case 'prev': case 'next': opts = $(cont).data('cycle.opts'); if (!opts) { log('options not found, "prev/next" ignored'); return false; } if (typeof arg2 == 'string') opts.oneTimeFx = arg2; $.fn.cycle[options](opts); return false; default: options = { fx: options }; } return options; } else if (options.constructor == Number) { // go to the requested slide var num = options; options = $(cont).data('cycle.opts'); if (!options) { log('options not found, can not advance slide'); return false; } if (num < 0 || num >= options.elements.length) { log('invalid slide index: ' + num); return false; } options.nextSlide = num; if (cont.cycleTimeout) { clearTimeout(cont.cycleTimeout); cont.cycleTimeout = 0; } if (typeof arg2 == 'string') options.oneTimeFx = arg2; go(options.elements, options, 1, num >= options.currSlide); return false; } return options; function checkInstantResume(isPaused, arg2, cont) { if (!isPaused && arg2 === true) { // resume now! var options = $(cont).data('cycle.opts'); if (!options) { log('options not found, can not resume'); return false; } if (cont.cycleTimeout) { clearTimeout(cont.cycleTimeout); cont.cycleTimeout = 0; } go(options.elements, options, 1, !options.backwards); } } } function removeFilter(el, opts) { if (!$.support.opacity && opts.cleartype && el.style.filter) { try { el.style.removeAttribute('filter'); } catch(smother) {} // handle old opera versions } } // unbind event handlers function destroy(cont, opts) { if (opts.next) $(opts.next).unbind(opts.prevNextEvent); if (opts.prev) $(opts.prev).unbind(opts.prevNextEvent); if (opts.pager || opts.pagerAnchorBuilder) $.each(opts.pagerAnchors || [], function() { this.unbind().remove(); }); opts.pagerAnchors = null; $(cont).unbind('mouseenter.cycle mouseleave.cycle'); if (opts.destroy) // callback opts.destroy(opts); } // one-time initialization function buildOptions($cont, $slides, els, options, o) { var startingSlideSpecified; // support metadata plugin (v1.0 and v2.0) var opts = $.extend({}, $.fn.cycle.defaults, options || {}, $.metadata ? $cont.metadata() : $.meta ? $cont.data() : {}); var meta = $.isFunction($cont.data) ? $cont.data(opts.metaAttr) : null; if (meta) opts = $.extend(opts, meta); if (opts.autostop) opts.countdown = opts.autostopCount || els.length; var cont = $cont[0]; $cont.data('cycle.opts', opts); opts.$cont = $cont; opts.stopCount = cont.cycleStop; opts.elements = els; opts.before = opts.before ? [opts.before] : []; opts.after = opts.after ? [opts.after] : []; // push some after callbacks if (!$.support.opacity && opts.cleartype) opts.after.push(function() { removeFilter(this, opts); }); if (opts.continuous) opts.after.push(function() { go(els,opts,0,!opts.backwards); }); saveOriginalOpts(opts); // clearType corrections if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg) clearTypeFix($slides); // container requires non-static position so that slides can be position within if ($cont.css('position') == 'static') $cont.css('position', 'relative'); if (opts.width) $cont.width(opts.width); if (opts.height && opts.height != 'auto') $cont.height(opts.height); if (opts.startingSlide !== undefined) { opts.startingSlide = parseInt(opts.startingSlide,10); if (opts.startingSlide >= els.length || opts.startSlide < 0) opts.startingSlide = 0; // catch bogus input else startingSlideSpecified = true; } else if (opts.backwards) opts.startingSlide = els.length - 1; else opts.startingSlide = 0; // if random, mix up the slide array if (opts.random) { opts.randomMap = []; for (var i = 0; i < els.length; i++) opts.randomMap.push(i); opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;}); if (startingSlideSpecified) { // try to find the specified starting slide and if found set start slide index in the map accordingly for ( var cnt = 0; cnt < els.length; cnt++ ) { if ( opts.startingSlide == opts.randomMap[cnt] ) { opts.randomIndex = cnt; } } } else { opts.randomIndex = 1; opts.startingSlide = opts.randomMap[1]; } } else if (opts.startingSlide >= els.length) opts.startingSlide = 0; // catch bogus input opts.currSlide = opts.startingSlide || 0; var first = opts.startingSlide; // set position and zIndex on all the slides $slides.css({position: 'absolute', top:0, left:0}).hide().each(function(i) { var z; if (opts.backwards) z = first ? i <= first ? els.length + (i-first) : first-i : els.length-i; else z = first ? i >= first ? els.length - (i-first) : first-i : els.length-i; $(this).css('z-index', z); }); // make sure first slide is visible $(els[first]).css('opacity',1).show(); // opacity bit needed to handle restart use case removeFilter(els[first], opts); // stretch slides if (opts.fit) { if (!opts.aspect) { if (opts.width) $slides.width(opts.width); if (opts.height && opts.height != 'auto') $slides.height(opts.height); } else { $slides.each(function(){ var $slide = $(this); var ratio = (opts.aspect === true) ? $slide.width()/$slide.height() : opts.aspect; if( opts.width && $slide.width() != opts.width ) { $slide.width( opts.width ); $slide.height( opts.width / ratio ); } if( opts.height && $slide.height() < opts.height ) { $slide.height( opts.height ); $slide.width( opts.height * ratio ); } }); } } if (opts.center && ((!opts.fit) || opts.aspect)) { $slides.each(function(){ var $slide = $(this); $slide.css({ "margin-left": opts.width ? ((opts.width - $slide.width()) / 2) + "px" : 0, "margin-top": opts.height ? ((opts.height - $slide.height()) / 2) + "px" : 0 }); }); } if (opts.center && !opts.fit && !opts.slideResize) { $slides.each(function(){ var $slide = $(this); $slide.css({ "margin-left": opts.width ? ((opts.width - $slide.width()) / 2) + "px" : 0, "margin-top": opts.height ? ((opts.height - $slide.height()) / 2) + "px" : 0 }); }); } // stretch container var reshape = (opts.containerResize || opts.containerResizeHeight) && $cont.innerHeight() < 1; if (reshape) { // do this only if container has no size http://tinyurl.com/da2oa9 var maxw = 0, maxh = 0; for(var j=0; j < els.length; j++) { var $e = $(els[j]), e = $e[0], w = $e.outerWidth(), h = $e.outerHeight(); if (!w) w = e.offsetWidth || e.width || $e.attr('width'); if (!h) h = e.offsetHeight || e.height || $e.attr('height'); maxw = w > maxw ? w : maxw; maxh = h > maxh ? h : maxh; } if (opts.containerResize && maxw > 0 && maxh > 0) $cont.css({width:maxw+'px',height:maxh+'px'}); if (opts.containerResizeHeight && maxh > 0) $cont.css({height:maxh+'px'}); } var pauseFlag = false; // https://github.com/malsup/cycle/issues/44 if (opts.pause) $cont.bind('mouseenter.cycle', function(){ pauseFlag = true; this.cyclePause++; triggerPause(cont, true); }).bind('mouseleave.cycle', function(){ if (pauseFlag) this.cyclePause--; triggerPause(cont, true); }); if (supportMultiTransitions(opts) === false) return false; // apparently a lot of people use image slideshows without height/width attributes on the images. // Cycle 2.50+ requires the sizing info for every slide; this block tries to deal with that. var requeue = false; options.requeueAttempts = options.requeueAttempts || 0; $slides.each(function() { // try to get height/width of each slide var $el = $(this); this.cycleH = (opts.fit && opts.height) ? opts.height : ($el.height() || this.offsetHeight || this.height || $el.attr('height') || 0); this.cycleW = (opts.fit && opts.width) ? opts.width : ($el.width() || this.offsetWidth || this.width || $el.attr('width') || 0); if ( $el.is('img') ) { var loading = (this.cycleH === 0 && this.cycleW === 0 && !this.complete); // don't requeue for images that are still loading but have a valid size if (loading) { if (o.s && opts.requeueOnImageNotLoaded && ++options.requeueAttempts < 100) { // track retry count so we don't loop forever log(options.requeueAttempts,' - img slide not loaded, requeuing slideshow: ', this.src, this.cycleW, this.cycleH); setTimeout(function() {$(o.s,o.c).cycle(options);}, opts.requeueTimeout); requeue = true; return false; // break each loop } else { log('could not determine size of image: '+this.src, this.cycleW, this.cycleH); } } } return true; }); if (requeue) return false; opts.cssBefore = opts.cssBefore || {}; opts.cssAfter = opts.cssAfter || {}; opts.cssFirst = opts.cssFirst || {}; opts.animIn = opts.animIn || {}; opts.animOut = opts.animOut || {}; $slides.not(':eq('+first+')').css(opts.cssBefore); $($slides[first]).css(opts.cssFirst); if (opts.timeout) { opts.timeout = parseInt(opts.timeout,10); // ensure that timeout and speed settings are sane if (opts.speed.constructor == String) opts.speed = $.fx.speeds[opts.speed] || parseInt(opts.speed,10); if (!opts.sync) opts.speed = opts.speed / 2; var buffer = opts.fx == 'none' ? 0 : opts.fx == 'shuffle' ? 500 : 250; while((opts.timeout - opts.speed) < buffer) // sanitize timeout opts.timeout += opts.speed; } if (opts.easing) opts.easeIn = opts.easeOut = opts.easing; if (!opts.speedIn) opts.speedIn = opts.speed; if (!opts.speedOut) opts.speedOut = opts.speed; opts.slideCount = els.length; opts.currSlide = opts.lastSlide = first; if (opts.random) { if (++opts.randomIndex == els.length) opts.randomIndex = 0; opts.nextSlide = opts.randomMap[opts.randomIndex]; } else if (opts.backwards) opts.nextSlide = opts.startingSlide === 0 ? (els.length-1) : opts.startingSlide-1; else opts.nextSlide = opts.startingSlide >= (els.length-1) ? 0 : opts.startingSlide+1; // run transition init fn if (!opts.multiFx) { var init = $.fn.cycle.transitions[opts.fx]; if ($.isFunction(init)) init($cont, $slides, opts); else if (opts.fx != 'custom' && !opts.multiFx) { log('unknown transition: ' + opts.fx,'; slideshow terminating'); return false; } } // fire artificial events var e0 = $slides[first]; if (!opts.skipInitializationCallbacks) { if (opts.before.length) opts.before[0].apply(e0, [e0, e0, opts, true]); if (opts.after.length) opts.after[0].apply(e0, [e0, e0, opts, true]); } if (opts.next) $(opts.next).bind(opts.prevNextEvent,function(){return advance(opts,1);}); if (opts.prev) $(opts.prev).bind(opts.prevNextEvent,function(){return advance(opts,0);}); if (opts.pager || opts.pagerAnchorBuilder) buildPager(els,opts); exposeAddSlide(opts, els); return opts; } // save off original opts so we can restore after clearing state function saveOriginalOpts(opts) { opts.original = { before: [], after: [] }; opts.original.cssBefore = $.extend({}, opts.cssBefore); opts.original.cssAfter = $.extend({}, opts.cssAfter); opts.original.animIn = $.extend({}, opts.animIn); opts.original.animOut = $.extend({}, opts.animOut); $.each(opts.before, function() { opts.original.before.push(this); }); $.each(opts.after, function() { opts.original.after.push(this); }); } function supportMultiTransitions(opts) { var i, tx, txs = $.fn.cycle.transitions; // look for multiple effects if (opts.fx.indexOf(',') > 0) { opts.multiFx = true; opts.fxs = opts.fx.replace(/\s*/g,'').split(','); // discard any bogus effect names for (i=0; i < opts.fxs.length; i++) { var fx = opts.fxs[i]; tx = txs[fx]; if (!tx || !txs.hasOwnProperty(fx) || !$.isFunction(tx)) { log('discarding unknown transition: ',fx); opts.fxs.splice(i,1); i--; } } // if we have an empty list then we threw everything away! if (!opts.fxs.length) { log('No valid transitions named; slideshow terminating.'); return false; } } else if (opts.fx == 'all') { // auto-gen the list of transitions opts.multiFx = true; opts.fxs = []; for (var p in txs) { if (txs.hasOwnProperty(p)) { tx = txs[p]; if (txs.hasOwnProperty(p) && $.isFunction(tx)) opts.fxs.push(p); } } } if (opts.multiFx && opts.randomizeEffects) { // munge the fxs array to make effect selection random var r1 = Math.floor(Math.random() * 20) + 30; for (i = 0; i < r1; i++) { var r2 = Math.floor(Math.random() * opts.fxs.length); opts.fxs.push(opts.fxs.splice(r2,1)[0]); } debug('randomized fx sequence: ',opts.fxs); } return true; } // provide a mechanism for adding slides after the slideshow has started function exposeAddSlide(opts, els) { opts.addSlide = function(newSlide, prepend) { var $s = $(newSlide), s = $s[0]; if (!opts.autostopCount) opts.countdown++; els[prepend?'unshift':'push'](s); if (opts.els) opts.els[prepend?'unshift':'push'](s); // shuffle needs this opts.slideCount = els.length; // add the slide to the random map and resort if (opts.random) { opts.randomMap.push(opts.slideCount-1); opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;}); } $s.css('position','absolute'); $s[prepend?'prependTo':'appendTo'](opts.$cont); if (prepend) { opts.currSlide++; opts.nextSlide++; } if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg) clearTypeFix($s); if (opts.fit && opts.width) $s.width(opts.width); if (opts.fit && opts.height && opts.height != 'auto') $s.height(opts.height); s.cycleH = (opts.fit && opts.height) ? opts.height : $s.height(); s.cycleW = (opts.fit && opts.width) ? opts.width : $s.width(); $s.css(opts.cssBefore); if (opts.pager || opts.pagerAnchorBuilder) $.fn.cycle.createPagerAnchor(els.length-1, s, $(opts.pager), els, opts); if ($.isFunction(opts.onAddSlide)) opts.onAddSlide($s); else $s.hide(); // default behavior }; } // reset internal state; we do this on every pass in order to support multiple effects $.fn.cycle.resetState = function(opts, fx) { fx = fx || opts.fx; opts.before = []; opts.after = []; opts.cssBefore = $.extend({}, opts.original.cssBefore); opts.cssAfter = $.extend({}, opts.original.cssAfter); opts.animIn = $.extend({}, opts.original.animIn); opts.animOut = $.extend({}, opts.original.animOut); opts.fxFn = null; $.each(opts.original.before, function() { opts.before.push(this); }); $.each(opts.original.after, function() { opts.after.push(this); }); // re-init var init = $.fn.cycle.transitions[fx]; if ($.isFunction(init)) init(opts.$cont, $(opts.elements), opts); }; // this is the main engine fn, it handles the timeouts, callbacks and slide index mgmt function go(els, opts, manual, fwd) { var p = opts.$cont[0], curr = els[opts.currSlide], next = els[opts.nextSlide]; // opts.busy is true if we're in the middle of an animation if (manual && opts.busy && opts.manualTrump) { // let manual transitions requests trump active ones debug('manualTrump in go(), stopping active transition'); $(els).stop(true,true); opts.busy = 0; clearTimeout(p.cycleTimeout); } // don't begin another timeout-based transition if there is one active if (opts.busy) { debug('transition active, ignoring new tx request'); return; } // stop cycling if we have an outstanding stop request if (p.cycleStop != opts.stopCount || p.cycleTimeout === 0 && !manual) return; // check to see if we should stop cycling based on autostop options if (!manual && !p.cyclePause && !opts.bounce && ((opts.autostop && (--opts.countdown <= 0)) || (opts.nowrap && !opts.random && opts.nextSlide < opts.currSlide))) { if (opts.end) opts.end(opts); return; } // if slideshow is paused, only transition on a manual trigger var changed = false; if ((manual || !p.cyclePause) && (opts.nextSlide != opts.currSlide)) { changed = true; var fx = opts.fx; // keep trying to get the slide size if we don't have it yet curr.cycleH = curr.cycleH || $(curr).height(); curr.cycleW = curr.cycleW || $(curr).width(); next.cycleH = next.cycleH || $(next).height(); next.cycleW = next.cycleW || $(next).width(); // support multiple transition types if (opts.multiFx) { if (fwd && (opts.lastFx === undefined || ++opts.lastFx >= opts.fxs.length)) opts.lastFx = 0; else if (!fwd && (opts.lastFx === undefined || --opts.lastFx < 0)) opts.lastFx = opts.fxs.length - 1; fx = opts.fxs[opts.lastFx]; } // one-time fx overrides apply to: $('div').cycle(3,'zoom'); if (opts.oneTimeFx) { fx = opts.oneTimeFx; opts.oneTimeFx = null; } $.fn.cycle.resetState(opts, fx); // run the before callbacks if (opts.before.length) $.each(opts.before, function(i,o) { if (p.cycleStop != opts.stopCount) return; o.apply(next, [curr, next, opts, fwd]); }); // stage the after callacks var after = function() { opts.busy = 0; $.each(opts.after, function(i,o) { if (p.cycleStop != opts.stopCount) return; o.apply(next, [curr, next, opts, fwd]); }); if (!p.cycleStop) { // queue next transition queueNext(); } }; debug('tx firing('+fx+'); currSlide: ' + opts.currSlide + '; nextSlide: ' + opts.nextSlide); // get ready to perform the transition opts.busy = 1; if (opts.fxFn) // fx function provided? opts.fxFn(curr, next, opts, after, fwd, manual && opts.fastOnEvent); else if ($.isFunction($.fn.cycle[opts.fx])) // fx plugin ? $.fn.cycle[opts.fx](curr, next, opts, after, fwd, manual && opts.fastOnEvent); else $.fn.cycle.custom(curr, next, opts, after, fwd, manual && opts.fastOnEvent); } else { queueNext(); } if (changed || opts.nextSlide == opts.currSlide) { // calculate the next slide var roll; opts.lastSlide = opts.currSlide; if (opts.random) { opts.currSlide = opts.nextSlide; if (++opts.randomIndex == els.length) { opts.randomIndex = 0; opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;}); } opts.nextSlide = opts.randomMap[opts.randomIndex]; if (opts.nextSlide == opts.currSlide) opts.nextSlide = (opts.currSlide == opts.slideCount - 1) ? 0 : opts.currSlide + 1; } else if (opts.backwards) { roll = (opts.nextSlide - 1) < 0; if (roll && opts.bounce) { opts.backwards = !opts.backwards; opts.nextSlide = 1; opts.currSlide = 0; } else { opts.nextSlide = roll ? (els.length-1) : opts.nextSlide-1; opts.currSlide = roll ? 0 : opts.nextSlide+1; } } else { // sequence roll = (opts.nextSlide + 1) == els.length; if (roll && opts.bounce) { opts.backwards = !opts.backwards; opts.nextSlide = els.length-2; opts.currSlide = els.length-1; } else { opts.nextSlide = roll ? 0 : opts.nextSlide+1; opts.currSlide = roll ? els.length-1 : opts.nextSlide-1; } } } if (changed && opts.pager) opts.updateActivePagerLink(opts.pager, opts.currSlide, opts.activePagerClass); function queueNext() { // stage the next transition var ms = 0, timeout = opts.timeout; if (opts.timeout && !opts.continuous) { ms = getTimeout(els[opts.currSlide], els[opts.nextSlide], opts, fwd); if (opts.fx == 'shuffle') ms -= opts.speedOut; } else if (opts.continuous && p.cyclePause) // continuous shows work off an after callback, not this timer logic ms = 10; if (ms > 0) p.cycleTimeout = setTimeout(function(){ go(els, opts, 0, !opts.backwards); }, ms); } } // invoked after transition $.fn.cycle.updateActivePagerLink = function(pager, currSlide, clsName) { $(pager).each(function() { $(this).children().removeClass(clsName).eq(currSlide).addClass(clsName); }); }; // calculate timeout value for current transition function getTimeout(curr, next, opts, fwd) { if (opts.timeoutFn) { // call user provided calc fn var t = opts.timeoutFn.call(curr,curr,next,opts,fwd); while (opts.fx != 'none' && (t - opts.speed) < 250) // sanitize timeout t += opts.speed; debug('calculated timeout: ' + t + '; speed: ' + opts.speed); if (t !== false) return t; } return opts.timeout; } // expose next/prev function, caller must pass in state $.fn.cycle.next = function(opts) { advance(opts,1); }; $.fn.cycle.prev = function(opts) { advance(opts,0);}; // advance slide forward or back function advance(opts, moveForward) { var val = moveForward ? 1 : -1; var els = opts.elements; var p = opts.$cont[0], timeout = p.cycleTimeout; if (timeout) { clearTimeout(timeout); p.cycleTimeout = 0; } if (opts.random && val < 0) { // move back to the previously display slide opts.randomIndex--; if (--opts.randomIndex == -2) opts.randomIndex = els.length-2; else if (opts.randomIndex == -1) opts.randomIndex = els.length-1; opts.nextSlide = opts.randomMap[opts.randomIndex]; } else if (opts.random) { opts.nextSlide = opts.randomMap[opts.randomIndex]; } else { opts.nextSlide = opts.currSlide + val; if (opts.nextSlide < 0) { if (opts.nowrap) return false; opts.nextSlide = els.length - 1; } else if (opts.nextSlide >= els.length) { if (opts.nowrap) return false; opts.nextSlide = 0; } } var cb = opts.onPrevNextEvent || opts.prevNextClick; // prevNextClick is deprecated if ($.isFunction(cb)) cb(val > 0, opts.nextSlide, els[opts.nextSlide]); go(els, opts, 1, moveForward); return false; } function buildPager(els, opts) { var $p = $(opts.pager); $.each(els, function(i,o) { $.fn.cycle.createPagerAnchor(i,o,$p,els,opts); }); opts.updateActivePagerLink(opts.pager, opts.startingSlide, opts.activePagerClass); } $.fn.cycle.createPagerAnchor = function(i, el, $p, els, opts) { var a; if ($.isFunction(opts.pagerAnchorBuilder)) { a = opts.pagerAnchorBuilder(i,el); debug('pagerAnchorBuilder('+i+', el) returned: ' + a); } else a = '<a href="#">'+(i+1)+'</a>'; if (!a) return; var $a = $(a); // don't reparent if anchor is in the dom if ($a.parents('body').length === 0) { var arr = []; if ($p.length > 1) { $p.each(function() { var $clone = $a.clone(true); $(this).append($clone); arr.push($clone[0]); }); $a = $(arr); } else { $a.appendTo($p); } } opts.pagerAnchors = opts.pagerAnchors || []; opts.pagerAnchors.push($a); var pagerFn = function(e) { e.preventDefault(); opts.nextSlide = i; var p = opts.$cont[0], timeout = p.cycleTimeout; if (timeout) { clearTimeout(timeout); p.cycleTimeout = 0; } var cb = opts.onPagerEvent || opts.pagerClick; // pagerClick is deprecated if ($.isFunction(cb)) cb(opts.nextSlide, els[opts.nextSlide]); go(els,opts,1,opts.currSlide < i); // trigger the trans // return false; // <== allow bubble }; if ( /mouseenter|mouseover/i.test(opts.pagerEvent) ) { $a.hover(pagerFn, function(){/* no-op */} ); } else { $a.bind(opts.pagerEvent, pagerFn); } if ( ! /^click/.test(opts.pagerEvent) && !opts.allowPagerClickBubble) $a.bind('click.cycle', function(){return false;}); // suppress click var cont = opts.$cont[0]; var pauseFlag = false; // https://github.com/malsup/cycle/issues/44 if (opts.pauseOnPagerHover) { $a.hover( function() { pauseFlag = true; cont.cyclePause++; triggerPause(cont,true,true); }, function() { if (pauseFlag) cont.cyclePause--; triggerPause(cont,true,true); } ); } }; // helper fn to calculate the number of slides between the current and the next $.fn.cycle.hopsFromLast = function(opts, fwd) { var hops, l = opts.lastSlide, c = opts.currSlide; if (fwd) hops = c > l ? c - l : opts.slideCount - l; else hops = c < l ? l - c : l + opts.slideCount - c; return hops; }; // fix clearType problems in ie6 by setting an explicit bg color // (otherwise text slides look horrible during a fade transition) function clearTypeFix($slides) { debug('applying clearType background-color hack'); function hex(s) { s = parseInt(s,10).toString(16); return s.length < 2 ? '0'+s : s; } function getBg(e) { for ( ; e && e.nodeName.toLowerCase() != 'html'; e = e.parentNode) { var v = $.css(e,'background-color'); if (v && v.indexOf('rgb') >= 0 ) { var rgb = v.match(/\d+/g); return '#'+ hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]); } if (v && v != 'transparent') return v; } return '#ffffff'; } $slides.each(function() { $(this).css('background-color', getBg(this)); }); } // reset common props before the next transition $.fn.cycle.commonReset = function(curr,next,opts,w,h,rev) { $(opts.elements).not(curr).hide(); if (typeof opts.cssBefore.opacity == 'undefined') opts.cssBefore.opacity = 1; opts.cssBefore.display = 'block'; if (opts.slideResize && w !== false && next.cycleW > 0) opts.cssBefore.width = next.cycleW; if (opts.slideResize && h !== false && next.cycleH > 0) opts.cssBefore.height = next.cycleH; opts.cssAfter = opts.cssAfter || {}; opts.cssAfter.display = 'none'; $(curr).css('zIndex',opts.slideCount + (rev === true ? 1 : 0)); $(next).css('zIndex',opts.slideCount + (rev === true ? 0 : 1)); }; // the actual fn for effecting a transition $.fn.cycle.custom = function(curr, next, opts, cb, fwd, speedOverride) { var $l = $(curr), $n = $(next); var speedIn = opts.speedIn, speedOut = opts.speedOut, easeIn = opts.easeIn, easeOut = opts.easeOut, animInDelay = opts.animInDelay, animOutDelay = opts.animOutDelay; $n.css(opts.cssBefore); if (speedOverride) { if (typeof speedOverride == 'number') speedIn = speedOut = speedOverride; else speedIn = speedOut = 1; easeIn = easeOut = null; } var fn = function() { $n.delay(animInDelay).animate(opts.animIn, speedIn, easeIn, function() { cb(); }); }; $l.delay(animOutDelay).animate(opts.animOut, speedOut, easeOut, function() { $l.css(opts.cssAfter); if (!opts.sync) fn(); }); if (opts.sync) fn(); }; // transition definitions - only fade is defined here, transition pack defines the rest $.fn.cycle.transitions = { fade: function($cont, $slides, opts) { $slides.not(':eq('+opts.currSlide+')').css('opacity',0); opts.before.push(function(curr,next,opts) { $.fn.cycle.commonReset(curr,next,opts); opts.cssBefore.opacity = 0; }); opts.animIn = { opacity: 1 }; opts.animOut = { opacity: 0 }; opts.cssBefore = { top: 0, left: 0 }; } }; $.fn.cycle.ver = function() { return ver; }; // override these globally if you like (they are all optional) $.fn.cycle.defaults = { activePagerClass: 'activeSlide', // class name used for the active pager link after: null, // transition callback (scope set to element that was shown): function(currSlideElement, nextSlideElement, options, forwardFlag) allowPagerClickBubble: false, // allows or prevents click event on pager anchors from bubbling animIn: null, // properties that define how the slide animates in animInDelay: 0, // allows delay before next slide transitions in animOut: null, // properties that define how the slide animates out animOutDelay: 0, // allows delay before current slide transitions out aspect: false, // preserve aspect ratio during fit resizing, cropping if necessary (must be used with fit option) autostop: 0, // true to end slideshow after X transitions (where X == slide count) autostopCount: 0, // number of transitions (optionally used with autostop to define X) backwards: false, // true to start slideshow at last slide and move backwards through the stack before: null, // transition callback (scope set to element to be shown): function(currSlideElement, nextSlideElement, options, forwardFlag) center: null, // set to true to have cycle add top/left margin to each slide (use with width and height options) cleartype: !$.support.opacity, // true if clearType corrections should be applied (for IE) cleartypeNoBg: false, // set to true to disable extra cleartype fixing (leave false to force background color setting on slides) containerResize: 1, // resize container to fit largest slide containerResizeHeight: 0, // resize containers height to fit the largest slide but leave the width dynamic continuous: 0, // true to start next transition immediately after current one completes cssAfter: null, // properties that defined the state of the slide after transitioning out cssBefore: null, // properties that define the initial state of the slide before transitioning in delay: 0, // additional delay (in ms) for first transition (hint: can be negative) easeIn: null, // easing for "in" transition easeOut: null, // easing for "out" transition easing: null, // easing method for both in and out transitions end: null, // callback invoked when the slideshow terminates (use with autostop or nowrap options): function(options) fastOnEvent: 0, // force fast transitions when triggered manually (via pager or prev/next); value == time in ms fit: 0, // force slides to fit container fx: 'fade', // name of transition effect (or comma separated names, ex: 'fade,scrollUp,shuffle') fxFn: null, // function used to control the transition: function(currSlideElement, nextSlideElement, options, afterCalback, forwardFlag) height: 'auto', // container height (if the 'fit' option is true, the slides will be set to this height as well) manualTrump: true, // causes manual transition to stop an active transition instead of being ignored metaAttr: 'cycle', // data- attribute that holds the option data for the slideshow next: null, // element, jQuery object, or jQuery selector string for the element to use as event trigger for next slide nowrap: 0, // true to prevent slideshow from wrapping onPagerEvent: null, // callback fn for pager events: function(zeroBasedSlideIndex, slideElement) onPrevNextEvent: null, // callback fn for prev/next events: function(isNext, zeroBasedSlideIndex, slideElement) pager: null, // element, jQuery object, or jQuery selector string for the element to use as pager container pagerAnchorBuilder: null, // callback fn for building anchor links: function(index, DOMelement) pagerEvent: 'click.cycle', // name of event which drives the pager navigation pause: 0, // true to enable "pause on hover" pauseOnPagerHover: 0, // true to pause when hovering over pager link prev: null, // element, jQuery object, or jQuery selector string for the element to use as event trigger for previous slide prevNextEvent: 'click.cycle',// event which drives the manual transition to the previous or next slide random: 0, // true for random, false for sequence (not applicable to shuffle fx) randomizeEffects: 1, // valid when multiple effects are used; true to make the effect sequence random requeueOnImageNotLoaded: true, // requeue the slideshow if any image slides are not yet loaded requeueTimeout: 250, // ms delay for requeue rev: 0, // causes animations to transition in reverse (for effects that support it such as scrollHorz/scrollVert/shuffle) shuffle: null, // coords for shuffle animation, ex: { top:15, left: 200 } skipInitializationCallbacks: false, // set to true to disable the first before/after callback that occurs prior to any transition slideExpr: null, // expression for selecting slides (if something other than all children is required) slideResize: 1, // force slide width/height to fixed size before every transition speed: 1000, // speed of the transition (any valid fx speed value) speedIn: null, // speed of the 'in' transition speedOut: null, // speed of the 'out' transition startingSlide: undefined,// zero-based index of the first slide to be displayed sync: 1, // true if in/out transitions should occur simultaneously timeout: 4000, // milliseconds between slide transitions (0 to disable auto advance) timeoutFn: null, // callback for determining per-slide timeout value: function(currSlideElement, nextSlideElement, options, forwardFlag) updateActivePagerLink: null,// callback fn invoked to update the active pager link (adds/removes activePagerClass style) width: null // container width (if the 'fit' option is true, the slides will be set to this width as well) }; })(jQuery); /*! * jQuery Cycle Plugin Transition Definitions * This script is a plugin for the jQuery Cycle Plugin * Examples and documentation at: http://malsup.com/jquery/cycle/ * Copyright (c) 2007-2010 M. Alsup * Version: 2.73 * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ (function($) { "use strict"; // // These functions define slide initialization and properties for the named // transitions. To save file size feel free to remove any of these that you // don't need. // $.fn.cycle.transitions.none = function($cont, $slides, opts) { opts.fxFn = function(curr,next,opts,after){ $(next).show(); $(curr).hide(); after(); }; }; // not a cross-fade, fadeout only fades out the top slide $.fn.cycle.transitions.fadeout = function($cont, $slides, opts) { $slides.not(':eq('+opts.currSlide+')').css({ display: 'block', 'opacity': 1 }); opts.before.push(function(curr,next,opts,w,h,rev) { $(curr).css('zIndex',opts.slideCount + (rev !== true ? 1 : 0)); $(next).css('zIndex',opts.slideCount + (rev !== true ? 0 : 1)); }); opts.animIn.opacity = 1; opts.animOut.opacity = 0; opts.cssBefore.opacity = 1; opts.cssBefore.display = 'block'; opts.cssAfter.zIndex = 0; }; // scrollUp/Down/Left/Right $.fn.cycle.transitions.scrollUp = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var h = $cont.height(); opts.cssBefore.top = h; opts.cssBefore.left = 0; opts.cssFirst.top = 0; opts.animIn.top = 0; opts.animOut.top = -h; }; $.fn.cycle.transitions.scrollDown = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var h = $cont.height(); opts.cssFirst.top = 0; opts.cssBefore.top = -h; opts.cssBefore.left = 0; opts.animIn.top = 0; opts.animOut.top = h; }; $.fn.cycle.transitions.scrollLeft = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var w = $cont.width(); opts.cssFirst.left = 0; opts.cssBefore.left = w; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.left = 0-w; }; $.fn.cycle.transitions.scrollRight = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var w = $cont.width(); opts.cssFirst.left = 0; opts.cssBefore.left = -w; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.left = w; }; $.fn.cycle.transitions.scrollHorz = function($cont, $slides, opts) { $cont.css('overflow','hidden').width(); opts.before.push(function(curr, next, opts, fwd) { if (opts.rev) fwd = !fwd; $.fn.cycle.commonReset(curr,next,opts); opts.cssBefore.left = fwd ? (next.cycleW-1) : (1-next.cycleW); opts.animOut.left = fwd ? -curr.cycleW : curr.cycleW; }); opts.cssFirst.left = 0; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.top = 0; }; $.fn.cycle.transitions.scrollVert = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push(function(curr, next, opts, fwd) { if (opts.rev) fwd = !fwd; $.fn.cycle.commonReset(curr,next,opts); opts.cssBefore.top = fwd ? (1-next.cycleH) : (next.cycleH-1); opts.animOut.top = fwd ? curr.cycleH : -curr.cycleH; }); opts.cssFirst.top = 0; opts.cssBefore.left = 0; opts.animIn.top = 0; opts.animOut.left = 0; }; // slideX/slideY $.fn.cycle.transitions.slideX = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $(opts.elements).not(curr).hide(); $.fn.cycle.commonReset(curr,next,opts,false,true); opts.animIn.width = next.cycleW; }); opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.cssBefore.width = 0; opts.animIn.width = 'show'; opts.animOut.width = 0; }; $.fn.cycle.transitions.slideY = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $(opts.elements).not(curr).hide(); $.fn.cycle.commonReset(curr,next,opts,true,false); opts.animIn.height = next.cycleH; }); opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.cssBefore.height = 0; opts.animIn.height = 'show'; opts.animOut.height = 0; }; // shuffle $.fn.cycle.transitions.shuffle = function($cont, $slides, opts) { var i, w = $cont.css('overflow', 'visible').width(); $slides.css({left: 0, top: 0}); opts.before.push(function(curr,next,opts) { $.fn.cycle.commonReset(curr,next,opts,true,true,true); }); // only adjust speed once! if (!opts.speedAdjusted) { opts.speed = opts.speed / 2; // shuffle has 2 transitions opts.speedAdjusted = true; } opts.random = 0; opts.shuffle = opts.shuffle || {left:-w, top:15}; opts.els = []; for (i=0; i < $slides.length; i++) opts.els.push($slides[i]); for (i=0; i < opts.currSlide; i++) opts.els.push(opts.els.shift()); // custom transition fn (hat tip to Benjamin Sterling for this bit of sweetness!) opts.fxFn = function(curr, next, opts, cb, fwd) { if (opts.rev) fwd = !fwd; var $el = fwd ? $(curr) : $(next); $(next).css(opts.cssBefore); var count = opts.slideCount; $el.animate(opts.shuffle, opts.speedIn, opts.easeIn, function() { var hops = $.fn.cycle.hopsFromLast(opts, fwd); for (var k=0; k < hops; k++) { if (fwd) opts.els.push(opts.els.shift()); else opts.els.unshift(opts.els.pop()); } if (fwd) { for (var i=0, len=opts.els.length; i < len; i++) $(opts.els[i]).css('z-index', len-i+count); } else { var z = $(curr).css('z-index'); $el.css('z-index', parseInt(z,10)+1+count); } $el.animate({left:0, top:0}, opts.speedOut, opts.easeOut, function() { $(fwd ? this : curr).hide(); if (cb) cb(); }); }); }; $.extend(opts.cssBefore, { display: 'block', opacity: 1, top: 0, left: 0 }); }; // turnUp/Down/Left/Right $.fn.cycle.transitions.turnUp = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false); opts.cssBefore.top = next.cycleH; opts.animIn.height = next.cycleH; opts.animOut.width = next.cycleW; }); opts.cssFirst.top = 0; opts.cssBefore.left = 0; opts.cssBefore.height = 0; opts.animIn.top = 0; opts.animOut.height = 0; }; $.fn.cycle.transitions.turnDown = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false); opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH; }); opts.cssFirst.top = 0; opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.cssBefore.height = 0; opts.animOut.height = 0; }; $.fn.cycle.transitions.turnLeft = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true); opts.cssBefore.left = next.cycleW; opts.animIn.width = next.cycleW; }); opts.cssBefore.top = 0; opts.cssBefore.width = 0; opts.animIn.left = 0; opts.animOut.width = 0; }; $.fn.cycle.transitions.turnRight = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true); opts.animIn.width = next.cycleW; opts.animOut.left = curr.cycleW; }); $.extend(opts.cssBefore, { top: 0, left: 0, width: 0 }); opts.animIn.left = 0; opts.animOut.width = 0; }; // zoom $.fn.cycle.transitions.zoom = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,false,true); opts.cssBefore.top = next.cycleH/2; opts.cssBefore.left = next.cycleW/2; $.extend(opts.animIn, { top: 0, left: 0, width: next.cycleW, height: next.cycleH }); $.extend(opts.animOut, { width: 0, height: 0, top: curr.cycleH/2, left: curr.cycleW/2 }); }); opts.cssFirst.top = 0; opts.cssFirst.left = 0; opts.cssBefore.width = 0; opts.cssBefore.height = 0; }; // fadeZoom $.fn.cycle.transitions.fadeZoom = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,false); opts.cssBefore.left = next.cycleW/2; opts.cssBefore.top = next.cycleH/2; $.extend(opts.animIn, { top: 0, left: 0, width: next.cycleW, height: next.cycleH }); }); opts.cssBefore.width = 0; opts.cssBefore.height = 0; opts.animOut.opacity = 0; }; // blindX $.fn.cycle.transitions.blindX = function($cont, $slides, opts) { var w = $cont.css('overflow','hidden').width(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.animIn.width = next.cycleW; opts.animOut.left = curr.cycleW; }); opts.cssBefore.left = w; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.left = w; }; // blindY $.fn.cycle.transitions.blindY = function($cont, $slides, opts) { var h = $cont.css('overflow','hidden').height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH; }); opts.cssBefore.top = h; opts.cssBefore.left = 0; opts.animIn.top = 0; opts.animOut.top = h; }; // blindZ $.fn.cycle.transitions.blindZ = function($cont, $slides, opts) { var h = $cont.css('overflow','hidden').height(); var w = $cont.width(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH; }); opts.cssBefore.top = h; opts.cssBefore.left = w; opts.animIn.top = 0; opts.animIn.left = 0; opts.animOut.top = h; opts.animOut.left = w; }; // growX - grow horizontally from centered 0 width $.fn.cycle.transitions.growX = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true); opts.cssBefore.left = this.cycleW/2; opts.animIn.left = 0; opts.animIn.width = this.cycleW; opts.animOut.left = 0; }); opts.cssBefore.top = 0; opts.cssBefore.width = 0; }; // growY - grow vertically from centered 0 height $.fn.cycle.transitions.growY = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false); opts.cssBefore.top = this.cycleH/2; opts.animIn.top = 0; opts.animIn.height = this.cycleH; opts.animOut.top = 0; }); opts.cssBefore.height = 0; opts.cssBefore.left = 0; }; // curtainX - squeeze in both edges horizontally $.fn.cycle.transitions.curtainX = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true,true); opts.cssBefore.left = next.cycleW/2; opts.animIn.left = 0; opts.animIn.width = this.cycleW; opts.animOut.left = curr.cycleW/2; opts.animOut.width = 0; }); opts.cssBefore.top = 0; opts.cssBefore.width = 0; }; // curtainY - squeeze in both edges vertically $.fn.cycle.transitions.curtainY = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false,true); opts.cssBefore.top = next.cycleH/2; opts.animIn.top = 0; opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH/2; opts.animOut.height = 0; }); opts.cssBefore.height = 0; opts.cssBefore.left = 0; }; // cover - curr slide covered by next slide $.fn.cycle.transitions.cover = function($cont, $slides, opts) { var d = opts.direction || 'left'; var w = $cont.css('overflow','hidden').width(); var h = $cont.height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.cssAfter.display = ''; if (d == 'right') opts.cssBefore.left = -w; else if (d == 'up') opts.cssBefore.top = h; else if (d == 'down') opts.cssBefore.top = -h; else opts.cssBefore.left = w; }); opts.animIn.left = 0; opts.animIn.top = 0; opts.cssBefore.top = 0; opts.cssBefore.left = 0; }; // uncover - curr slide moves off next slide $.fn.cycle.transitions.uncover = function($cont, $slides, opts) { var d = opts.direction || 'left'; var w = $cont.css('overflow','hidden').width(); var h = $cont.height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,true,true); if (d == 'right') opts.animOut.left = w; else if (d == 'up') opts.animOut.top = -h; else if (d == 'down') opts.animOut.top = h; else opts.animOut.left = -w; }); opts.animIn.left = 0; opts.animIn.top = 0; opts.cssBefore.top = 0; opts.cssBefore.left = 0; }; // toss - move top slide and fade away $.fn.cycle.transitions.toss = function($cont, $slides, opts) { var w = $cont.css('overflow','visible').width(); var h = $cont.height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,true,true); // provide default toss settings if animOut not provided if (!opts.animOut.left && !opts.animOut.top) $.extend(opts.animOut, { left: w*2, top: -h/2, opacity: 0 }); else opts.animOut.opacity = 0; }); opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.animIn.left = 0; }; // wipe - clip animation $.fn.cycle.transitions.wipe = function($cont, $slides, opts) { var w = $cont.css('overflow','hidden').width(); var h = $cont.height(); opts.cssBefore = opts.cssBefore || {}; var clip; if (opts.clip) { if (/l2r/.test(opts.clip)) clip = 'rect(0px 0px '+h+'px 0px)'; else if (/r2l/.test(opts.clip)) clip = 'rect(0px '+w+'px '+h+'px '+w+'px)'; else if (/t2b/.test(opts.clip)) clip = 'rect(0px '+w+'px 0px 0px)'; else if (/b2t/.test(opts.clip)) clip = 'rect('+h+'px '+w+'px '+h+'px 0px)'; else if (/zoom/.test(opts.clip)) { var top = parseInt(h/2,10); var left = parseInt(w/2,10); clip = 'rect('+top+'px '+left+'px '+top+'px '+left+'px)'; } } opts.cssBefore.clip = opts.cssBefore.clip || clip || 'rect(0px 0px 0px 0px)'; var d = opts.cssBefore.clip.match(/(\d+)/g); var t = parseInt(d[0],10), r = parseInt(d[1],10), b = parseInt(d[2],10), l = parseInt(d[3],10); opts.before.push(function(curr, next, opts) { if (curr == next) return; var $curr = $(curr), $next = $(next); $.fn.cycle.commonReset(curr,next,opts,true,true,false); opts.cssAfter.display = 'block'; var step = 1, count = parseInt((opts.speedIn / 13),10) - 1; (function f() { var tt = t ? t - parseInt(step * (t/count),10) : 0; var ll = l ? l - parseInt(step * (l/count),10) : 0; var bb = b < h ? b + parseInt(step * ((h-b)/count || 1),10) : h; var rr = r < w ? r + parseInt(step * ((w-r)/count || 1),10) : w; $next.css({ clip: 'rect('+tt+'px '+rr+'px '+bb+'px '+ll+'px)' }); (step++ <= count) ? setTimeout(f, 13) : $curr.css('display', 'none'); })(); }); $.extend(opts.cssBefore, { display: 'block', opacity: 1, top: 0, left: 0 }); opts.animIn = { left: 0 }; opts.animOut = { left: 0 }; }; })(jQuery);
delfintrinidadIV/firstproject
wp-content/themes/simple-catch/js/jquery.cycle.all.js
JavaScript
gpl-2.0
52,026
/** * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/> * Build: `lodash modularize modern exports="node" -o ./modern/` * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE> * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <http://lodash.com/license> */ var baseIndexOf = require('./baseIndexOf'), cacheIndexOf = require('./cacheIndexOf'), createCache = require('./createCache'), getArray = require('./getArray'), largeArraySize = require('./largeArraySize'), releaseArray = require('./releaseArray'), releaseObject = require('./releaseObject'); /** * The base implementation of `_.uniq` without support for callback shorthands * or `thisArg` binding. * * @private * @param {Array} array The array to process. * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted. * @param {Function} [callback] The function called per iteration. * @returns {Array} Returns a duplicate-value-free array. */ function baseUniq(array, isSorted, callback) { var index = -1, indexOf = baseIndexOf, length = array ? array.length : 0, result = []; var isLarge = !isSorted && length >= largeArraySize, seen = (callback || isLarge) ? getArray() : result; if (isLarge) { var cache = createCache(seen); indexOf = cacheIndexOf; seen = cache; } while (++index < length) { var value = array[index], computed = callback ? callback(value, index, array) : value; if (isSorted ? !index || seen[seen.length - 1] !== computed : indexOf(seen, computed) < 0 ) { if (callback || isLarge) { seen.push(computed); } result.push(value); } } if (isLarge) { releaseArray(seen.array); releaseObject(seen); } else if (callback) { releaseArray(seen); } return result; } module.exports = baseUniq;
tspires/personal
zillow/node_modules/xml2js/node_modules/xmlbuilder/node_modules/lodash-node/modern/internals/baseUniq.js
JavaScript
mit
2,014
/* Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package service contains code for syncing cloud load balancers // with the service registry. package service // import "k8s.io/kubernetes/pkg/controller/service"
humblec/external-storage
vendor/k8s.io/kubernetes/pkg/controller/service/doc.go
GO
apache-2.0
736
var browser_history_support = (window.history != null ? window.history.pushState : null) != null; createTest('Nested route with the many children as a tokens, callbacks should yield historic params', { '/a': { '/:id': { '/:id': function(a, b) { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, ''), a, b); } else { shared.fired.push(location.pathname, a, b); } } } } }, function() { this.navigate('/a/b/c', function() { deepEqual(shared.fired, ['/a/b/c', 'b', 'c']); this.finish(); }); }); createTest('Nested route with the first child as a token, callback should yield a param', { '/foo': { '/:id': { on: function(id) { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, ''), id); } else { shared.fired.push(location.pathname, id); } } } } }, function() { this.navigate('/foo/a', function() { this.navigate('/foo/b/c', function() { deepEqual(shared.fired, ['/foo/a', 'a']); this.finish(); }); }); }); createTest('Nested route with the first child as a regexp, callback should yield a param', { '/foo': { '/(\\w+)': { on: function(value) { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, ''), value); } else { shared.fired.push(location.pathname, value); } } } } }, function() { this.navigate('/foo/a', function() { this.navigate('/foo/b/c', function() { deepEqual(shared.fired, ['/foo/a', 'a']); this.finish(); }); }); }); createTest('Nested route with the several regular expressions, callback should yield a param', { '/a': { '/(\\w+)': { '/(\\w+)': function(a, b) { shared.fired.push(a, b); } } } }, function() { this.navigate('/a/b/c', function() { deepEqual(shared.fired, ['b', 'c']); this.finish(); }); }); createTest('Single nested route with on member containing function value', { '/a': { '/b': { on: function() { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, '')); } else { shared.fired.push(location.pathname); } } } } }, function() { this.navigate('/a/b', function() { deepEqual(shared.fired, ['/a/b']); this.finish(); }); }); createTest('Single non-nested route with on member containing function value', { '/a/b': { on: function() { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, '')); } else { shared.fired.push(location.pathname); } } } }, function() { this.navigate('/a/b', function() { deepEqual(shared.fired, ['/a/b']); this.finish(); }); }); createTest('Single nested route with on member containing array of function values', { '/a': { '/b': { on: [function() { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, '')); } else { shared.fired.push(location.pathname); } }, function() { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, '')); } else { shared.fired.push(location.pathname); } }] } } }, function() { this.navigate('/a/b', function() { deepEqual(shared.fired, ['/a/b', '/a/b']); this.finish(); }); }); createTest('method should only fire once on the route.', { '/a': { '/b': { once: function() { shared.fired_count++; } } } }, function() { this.navigate('/a/b', function() { this.navigate('/a/b', function() { this.navigate('/a/b', function() { deepEqual(shared.fired_count, 1); this.finish(); }); }); }); }); createTest('method should only fire once on the route, multiple nesting.', { '/a': { on: function() { shared.fired_count++; }, once: function() { shared.fired_count++; } }, '/b': { on: function() { shared.fired_count++; }, once: function() { shared.fired_count++; } } }, function() { this.navigate('/a', function() { this.navigate('/b', function() { this.navigate('/a', function() { this.navigate('/b', function() { deepEqual(shared.fired_count, 6); this.finish(); }); }); }); }); }); createTest('overlapping routes with tokens.', { '/a/:b/c' : function() { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, '')); } else { shared.fired.push(location.pathname); } }, '/a/:b/c/:d' : function() { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, '')); } else { shared.fired.push(location.pathname); } } }, function() { this.navigate('/a/b/c', function() { this.navigate('/a/b/c/d', function() { deepEqual(shared.fired, ['/a/b/c', '/a/b/c/d']); this.finish(); }); }); }); // // // // // // Recursion features // // // ---------------------------------------------------------- createTest('Nested routes with no recursion', { '/a': { '/b': { '/c': { on: function c() { shared.fired.push('c'); } }, on: function b() { shared.fired.push('b'); } }, on: function a() { shared.fired.push('a'); } } }, function() { this.navigate('/a/b/c', function() { deepEqual(shared.fired, ['c']); this.finish(); }); }); createTest('Nested routes with backward recursion', { '/a': { '/b': { '/c': { on: function c() { shared.fired.push('c'); } }, on: function b() { shared.fired.push('b'); } }, on: function a() { shared.fired.push('a'); } } }, { recurse: 'backward' }, function() { this.navigate('/a/b/c', function() { deepEqual(shared.fired, ['c', 'b', 'a']); this.finish(); }); }); createTest('Breaking out of nested routes with backward recursion', { '/a': { '/:b': { '/c': { on: function c() { shared.fired.push('c'); } }, on: function b() { shared.fired.push('b'); return false; } }, on: function a() { shared.fired.push('a'); } } }, { recurse: 'backward' }, function() { this.navigate('/a/b/c', function() { deepEqual(shared.fired, ['c', 'b']); this.finish(); }); }); createTest('Nested routes with forward recursion', { '/a': { '/b': { '/c': { on: function c() { shared.fired.push('c'); } }, on: function b() { shared.fired.push('b'); } }, on: function a() { shared.fired.push('a'); } } }, { recurse: 'forward' }, function() { this.navigate('/a/b/c', function() { deepEqual(shared.fired, ['a', 'b', 'c']); this.finish(); }); }); createTest('Nested routes with forward recursion, single route with an after event.', { '/a': { '/b': { '/c': { on: function c() { shared.fired.push('c'); }, after: function() { shared.fired.push('c-after'); } }, on: function b() { shared.fired.push('b'); } }, on: function a() { shared.fired.push('a'); } } }, { recurse: 'forward' }, function() { this.navigate('/a/b/c', function() { this.navigate('/a/b', function() { deepEqual(shared.fired, ['a', 'b', 'c', 'c-after', 'a', 'b']); this.finish(); }); }); }); createTest('Breaking out of nested routes with forward recursion', { '/a': { '/b': { '/c': { on: function c() { shared.fired.push('c'); } }, on: function b() { shared.fired.push('b'); return false; } }, on: function a() { shared.fired.push('a'); } } }, { recurse: 'forward' }, function() { this.navigate('/a/b/c', function() { deepEqual(shared.fired, ['a', 'b']); this.finish(); }); }); // // ABOVE IS WORKING // // // // // Special Events // // ---------------------------------------------------------- createTest('All global event should fire after every route', { '/a': { on: function a() { shared.fired.push('a'); } }, '/b': { '/c': { on: function a() { shared.fired.push('a'); } } }, '/d': { '/:e': { on: function a() { shared.fired.push('a'); } } } }, { after: function() { shared.fired.push('b'); } }, function() { this.navigate('/a', function() { this.navigate('/b/c', function() { this.navigate('/d/e', function() { deepEqual(shared.fired, ['a', 'b', 'a', 'b', 'a']); this.finish(); }); }); }); }); createTest('Not found.', { '/a': { on: function a() { shared.fired.push('a'); } }, '/b': { on: function a() { shared.fired.push('b'); } } }, { notfound: function() { shared.fired.push('notfound'); } }, function() { this.navigate('/c', function() { this.navigate('/d', function() { deepEqual(shared.fired, ['notfound', 'notfound']); this.finish(); }); }); }); createTest('On all.', { '/a': { on: function a() { shared.fired.push('a'); } }, '/b': { on: function a() { shared.fired.push('b'); } } }, { on: function() { shared.fired.push('c'); } }, function() { this.navigate('/a', function() { this.navigate('/b', function() { deepEqual(shared.fired, ['a', 'c', 'b', 'c']); this.finish(); }); }); }); createTest('After all.', { '/a': { on: function a() { shared.fired.push('a'); } }, '/b': { on: function a() { shared.fired.push('b'); } } }, { after: function() { shared.fired.push('c'); } }, function() { this.navigate('/a', function() { this.navigate('/b', function() { deepEqual(shared.fired, ['a', 'c', 'b']); this.finish(); }); }); }); createTest('resource object.', { '/a': { '/b/:c': { on: 'f1' }, on: 'f2' }, '/d': { on: ['f1', 'f2'] } }, { resource: { f1: function (name){ shared.fired.push("f1-" + name); }, f2: function (name){ shared.fired.push("f2"); } } }, function() { this.navigate('/a/b/c', function() { this.navigate('/d', function() { deepEqual(shared.fired, ['f1-c', 'f1-undefined', 'f2']); this.finish(); }); }); }); createTest('argument matching should be case agnostic', { '/fooBar/:name': { on: function(name) { shared.fired.push("fooBar-" + name); } } }, function() { this.navigate('/fooBar/tesTing', function() { deepEqual(shared.fired, ['fooBar-tesTing']); this.finish(); }); }); createTest('sanity test', { '/is/:this/:sane': { on: function(a, b) { shared.fired.push('yes ' + a + ' is ' + b); } }, '/': { on: function() { shared.fired.push('is there sanity?'); } } }, function() { this.navigate('/is/there/sanity', function() { deepEqual(shared.fired, ['yes there is sanity']); this.finish(); }); }); createTest('`/` route should be navigable from the routing table', { '/': { on: function root() { shared.fired.push('/'); } }, '/:username': { on: function afunc(username) { shared.fired.push('/' + username); } } }, function() { this.navigate('/', function root() { deepEqual(shared.fired, ['/']); this.finish(); }); }); createTest('`/` route should not override a `/:token` route', { '/': { on: function root() { shared.fired.push('/'); } }, '/:username': { on: function afunc(username) { shared.fired.push('/' + username); } } }, function() { this.navigate('/a', function afunc() { deepEqual(shared.fired, ['/a']); this.finish(); }); }); createTest('should accept the root as a token.', { '/:a': { on: function root() { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, '')); } else { shared.fired.push(location.pathname); } } } }, function() { this.navigate('/a', function root() { deepEqual(shared.fired, ['/a']); this.finish(); }); }); createTest('routes should allow wildcards.', { '/:a/b*d': { on: function() { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, '')); } else { shared.fired.push(location.pathname); } } } }, function() { this.navigate('/a/bcd', function root() { deepEqual(shared.fired, ['/a/bcd']); this.finish(); }); }); createTest('functions should have |this| context of the router instance.', { '/': { on: function root() { shared.fired.push(!!this.routes); } } }, function() { this.navigate('/', function root() { deepEqual(shared.fired, [true]); this.finish(); }); }); createTest('setRoute with a single parameter should change location correctly', { '/bonk': { on: function() { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, '')); } else { shared.fired.push(window.location.pathname); } } } }, function() { var self = this; this.router.setRoute('/bonk'); setTimeout(function() { deepEqual(shared.fired, ['/bonk']); self.finish(); }, 14) }); createTest('route should accept _ and . within parameters', { '/:a': { on: function root() { if (!browser_history_support) { shared.fired.push(location.hash.replace(/^#/, '')); } else { shared.fired.push(location.pathname); } } } }, function() { this.navigate('/a_complex_route.co.uk', function root() { deepEqual(shared.fired, ['/a_complex_route.co.uk']); this.finish(); }); });
WAPMADRID/server
wapmadrid/node_modules/forever/node_modules/flatiron/node_modules/director/test/browser/html5-routes-test.js
JavaScript
gpl-2.0
14,089
/// <reference types="easeljs"/> var target = new createjs.DisplayObject(); // source : http://www.createjs.com/Docs/TweenJS/modules/TweenJS.html // Chainable modules : target.alpha = 1; createjs.Tween.get(target).wait(500, false).to({ alpha: 0, visible: false }, 1000).call(onComplete); function onComplete() { //Tween complete }
zuzusik/DefinitelyTyped
types/tweenjs/tweenjs-tests.ts
TypeScript
mit
337
#ifndef BOOST_MPL_LOWER_BOUND_HPP_INCLUDED #define BOOST_MPL_LOWER_BOUND_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2001-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id: lower_bound.hpp 49267 2008-10-11 06:19:02Z agurtovoy $ // $Date: 2008-10-10 23:19:02 -0700 (Fri, 10 Oct 2008) $ // $Revision: 49267 $ #include <boost/mpl/less.hpp> #include <boost/mpl/lambda.hpp> #include <boost/mpl/aux_/na_spec.hpp> #include <boost/mpl/aux_/config/workaround.hpp> #if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x610)) # define BOOST_MPL_CFG_STRIPPED_DOWN_LOWER_BOUND_IMPL #endif #if !defined(BOOST_MPL_CFG_STRIPPED_DOWN_LOWER_BOUND_IMPL) # include <boost/mpl/minus.hpp> # include <boost/mpl/divides.hpp> # include <boost/mpl/size.hpp> # include <boost/mpl/advance.hpp> # include <boost/mpl/begin_end.hpp> # include <boost/mpl/long.hpp> # include <boost/mpl/eval_if.hpp> # include <boost/mpl/prior.hpp> # include <boost/mpl/deref.hpp> # include <boost/mpl/apply.hpp> # include <boost/mpl/aux_/value_wknd.hpp> #else # include <boost/mpl/not.hpp> # include <boost/mpl/find.hpp> # include <boost/mpl/bind.hpp> #endif #include <boost/config.hpp> namespace boost { namespace mpl { #if defined(BOOST_MPL_CFG_STRIPPED_DOWN_LOWER_BOUND_IMPL) // agurt 23/oct/02: has a wrong complexity etc., but at least it works // feel free to contribute a better implementation! template< typename BOOST_MPL_AUX_NA_PARAM(Sequence) , typename BOOST_MPL_AUX_NA_PARAM(T) , typename Predicate = less<> , typename pred_ = typename lambda<Predicate>::type > struct lower_bound : find_if< Sequence, bind1< not_<>, bind2<pred_,_,T> > > { }; #else namespace aux { template< typename Distance , typename Predicate , typename T , typename DeferredIterator > struct lower_bound_step_impl; template< typename Distance , typename Predicate , typename T , typename DeferredIterator > struct lower_bound_step { typedef typename eval_if< Distance , lower_bound_step_impl<Distance,Predicate,T,DeferredIterator> , DeferredIterator >::type type; }; template< typename Distance , typename Predicate , typename T , typename DeferredIterator > struct lower_bound_step_impl { typedef typename divides< Distance, long_<2> >::type offset_; typedef typename DeferredIterator::type iter_; typedef typename advance< iter_,offset_ >::type middle_; typedef typename apply2< Predicate , typename deref<middle_>::type , T >::type cond_; typedef typename prior< minus< Distance, offset_> >::type step_; typedef lower_bound_step< offset_,Predicate,T,DeferredIterator > step_forward_; typedef lower_bound_step< step_,Predicate,T,next<middle_> > step_backward_; typedef typename eval_if< cond_ , step_backward_ , step_forward_ >::type type; }; } // namespace aux template< typename BOOST_MPL_AUX_NA_PARAM(Sequence) , typename BOOST_MPL_AUX_NA_PARAM(T) , typename Predicate = less<> > struct lower_bound { private: typedef typename lambda<Predicate>::type pred_; typedef typename size<Sequence>::type size_; public: typedef typename aux::lower_bound_step< size_,pred_,T,begin<Sequence> >::type type; }; #endif // BOOST_MPL_CFG_STRIPPED_DOWN_LOWER_BOUND_IMPL BOOST_MPL_AUX_NA_SPEC(2, lower_bound) }} #endif // BOOST_MPL_LOWER_BOUND_HPP_INCLUDED
hpl1nk/nonamegame
xray/SDK/include/boost/mpl/lower_bound.hpp
C++
gpl-3.0
3,713
/** * @license AngularJS v1.0.6 * (c) 2010-2012 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) { 'use strict'; /** * @ngdoc overview * @name ngResource * @description */ /** * @ngdoc object * @name ngResource.$resource * @requires $http * * @description * A factory which creates a resource object that lets you interact with * [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources. * * The returned resource object has action methods which provide high-level behaviors without * the need to interact with the low level {@link ng.$http $http} service. * * # Installation * To use $resource make sure you have included the `angular-resource.js` that comes in Angular * package. You can also find this file on Google CDN, bower as well as at * {@link http://code.angularjs.org/ code.angularjs.org}. * * Finally load the module in your application: * * angular.module('app', ['ngResource']); * * and you are ready to get started! * * @param {string} url A parameterized URL template with parameters prefixed by `:` as in * `/user/:username`. If you are using a URL with a port number (e.g. * `http://example.com:8080/api`), you'll need to escape the colon character before the port * number, like this: `$resource('http://example.com\\:8080/api')`. * * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in * `actions` methods. * * Each key value in the parameter object is first bound to url template if present and then any * excess keys are appended to the url search query after the `?`. * * Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in * URL `/path/greet?salutation=Hello`. * * If the parameter value is prefixed with `@` then the value of that parameter is extracted from * the data object (useful for non-GET operations). * * @param {Object.<Object>=} actions Hash with declaration of custom action that should extend the * default set of resource actions. The declaration should be created in the following format: * * {action1: {method:?, params:?, isArray:?}, * action2: {method:?, params:?, isArray:?}, * ...} * * Where: * * - `action` – {string} – The name of action. This name becomes the name of the method on your * resource object. * - `method` – {string} – HTTP request method. Valid methods are: `GET`, `POST`, `PUT`, `DELETE`, * and `JSONP` * - `params` – {object=} – Optional set of pre-bound parameters for this action. * - isArray – {boolean=} – If true then the returned object for this action is an array, see * `returns` section. * * @returns {Object} A resource "class" object with methods for the default set of resource actions * optionally extended with custom `actions`. The default set contains these actions: * * { 'get': {method:'GET'}, * 'save': {method:'POST'}, * 'query': {method:'GET', isArray:true}, * 'remove': {method:'DELETE'}, * 'delete': {method:'DELETE'} }; * * Calling these methods invoke an {@link ng.$http} with the specified http method, * destination and parameters. When the data is returned from the server then the object is an * instance of the resource class. The actions `save`, `remove` and `delete` are available on it * as methods with the `$` prefix. This allows you to easily perform CRUD operations (create, * read, update, delete) on server-side data like this: * <pre> var User = $resource('/user/:userId', {userId:'@id'}); var user = User.get({userId:123}, function() { user.abc = true; user.$save(); }); </pre> * * It is important to realize that invoking a $resource object method immediately returns an * empty reference (object or array depending on `isArray`). Once the data is returned from the * server the existing reference is populated with the actual data. This is a useful trick since * usually the resource is assigned to a model which is then rendered by the view. Having an empty * object results in no rendering, once the data arrives from the server then the object is * populated with the data and the view automatically re-renders itself showing the new data. This * means that in most case one never has to write a callback function for the action methods. * * The action methods on the class object or instance object can be invoked with the following * parameters: * * - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])` * - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])` * - non-GET instance actions: `instance.$action([parameters], [success], [error])` * * * @example * * # Credit card resource * * <pre> // Define CreditCard class var CreditCard = $resource('/user/:userId/card/:cardId', {userId:123, cardId:'@id'}, { charge: {method:'POST', params:{charge:true}} }); // We can retrieve a collection from the server var cards = CreditCard.query(function() { // GET: /user/123/card // server returns: [ {id:456, number:'1234', name:'Smith'} ]; var card = cards[0]; // each item is an instance of CreditCard expect(card instanceof CreditCard).toEqual(true); card.name = "J. Smith"; // non GET methods are mapped onto the instances card.$save(); // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'} // server returns: {id:456, number:'1234', name: 'J. Smith'}; // our custom method is mapped as well. card.$charge({amount:9.99}); // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'} }); // we can create an instance as well var newCard = new CreditCard({number:'0123'}); newCard.name = "Mike Smith"; newCard.$save(); // POST: /user/123/card {number:'0123', name:'Mike Smith'} // server returns: {id:789, number:'01234', name: 'Mike Smith'}; expect(newCard.id).toEqual(789); * </pre> * * The object returned from this function execution is a resource "class" which has "static" method * for each action in the definition. * * Calling these methods invoke `$http` on the `url` template with the given `method` and `params`. * When the data is returned from the server then the object is an instance of the resource type and * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD * operations (create, read, update, delete) on server-side data. <pre> var User = $resource('/user/:userId', {userId:'@id'}); var user = User.get({userId:123}, function() { user.abc = true; user.$save(); }); </pre> * * It's worth noting that the success callback for `get`, `query` and other method gets passed * in the response that came from the server as well as $http header getter function, so one * could rewrite the above example and get access to http headers as: * <pre> var User = $resource('/user/:userId', {userId:'@id'}); User.get({userId:123}, function(u, getResponseHeaders){ u.abc = true; u.$save(function(u, putResponseHeaders) { //u => saved user object //putResponseHeaders => $http header getter }); }); </pre> * # Buzz client Let's look at what a buzz client created with the `$resource` service looks like: <doc:example> <doc:source jsfiddle="false"> <script> function BuzzController($resource) { this.userId = 'googlebuzz'; this.Activity = $resource( 'https://www.googleapis.com/buzz/v1/activities/:userId/:visibility/:activityId/:comments', {alt:'json', callback:'JSON_CALLBACK'}, {get:{method:'JSONP', params:{visibility:'@self'}}, replies: {method:'JSONP', params:{visibility:'@self', comments:'@comments'}}} ); } BuzzController.prototype = { fetch: function() { this.activities = this.Activity.get({userId:this.userId}); }, expandReplies: function(activity) { activity.replies = this.Activity.replies({userId:this.userId, activityId:activity.id}); } }; BuzzController.$inject = ['$resource']; </script> <div ng-controller="BuzzController"> <input ng-model="userId"/> <button ng-click="fetch()">fetch</button> <hr/> <div ng-repeat="item in activities.data.items"> <h1 style="font-size: 15px;"> <img src="{{item.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/> <a href="{{item.actor.profileUrl}}">{{item.actor.name}}</a> <a href ng-click="expandReplies(item)" style="float: right;">Expand replies: {{item.links.replies[0].count}}</a> </h1> {{item.object.content | html}} <div ng-repeat="reply in item.replies.data.items" style="margin-left: 20px;"> <img src="{{reply.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/> <a href="{{reply.actor.profileUrl}}">{{reply.actor.name}}</a>: {{reply.content | html}} </div> </div> </div> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ angular.module('ngResource', ['ng']). factory('$resource', ['$http', '$parse', function($http, $parse) { var DEFAULT_ACTIONS = { 'get': {method:'GET'}, 'save': {method:'POST'}, 'query': {method:'GET', isArray:true}, 'remove': {method:'DELETE'}, 'delete': {method:'DELETE'} }; var noop = angular.noop, forEach = angular.forEach, extend = angular.extend, copy = angular.copy, isFunction = angular.isFunction, getter = function(obj, path) { return $parse(path)(obj); }; /** * We need our custom method because encodeURIComponent is too aggressive and doesn't follow * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path * segments: * segment = *pchar * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * pct-encoded = "%" HEXDIG HEXDIG * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriSegment(val) { return encodeUriQuery(val, true). replace(/%26/gi, '&'). replace(/%3D/gi, '='). replace(/%2B/gi, '+'); } /** * This method is intended for encoding *key* or *value* parts of query component. We need a custom * method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be * encoded per http://tools.ietf.org/html/rfc3986: * query = *( pchar / "/" / "?" ) * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * pct-encoded = "%" HEXDIG HEXDIG * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriQuery(val, pctEncodeSpaces) { return encodeURIComponent(val). replace(/%40/gi, '@'). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); } function Route(template, defaults) { this.template = template = template + '#'; this.defaults = defaults || {}; var urlParams = this.urlParams = {}; forEach(template.split(/\W/), function(param){ if (param && (new RegExp("(^|[^\\\\]):" + param + "\\W").test(template))) { urlParams[param] = true; } }); this.template = template.replace(/\\:/g, ':'); } Route.prototype = { url: function(params) { var self = this, url = this.template, val, encodedVal; params = params || {}; forEach(this.urlParams, function(_, urlParam){ val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam]; if (angular.isDefined(val) && val !== null) { encodedVal = encodeUriSegment(val); url = url.replace(new RegExp(":" + urlParam + "(\\W)", "g"), encodedVal + "$1"); } else { url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W)", "g"), function(match, leadingSlashes, tail) { if (tail.charAt(0) == '/') { return tail; } else { return leadingSlashes + tail; } }); } }); url = url.replace(/\/?#$/, ''); var query = []; forEach(params, function(value, key){ if (!self.urlParams[key]) { query.push(encodeUriQuery(key) + '=' + encodeUriQuery(value)); } }); query.sort(); url = url.replace(/\/*$/, ''); return url + (query.length ? '?' + query.join('&') : ''); } }; function ResourceFactory(url, paramDefaults, actions) { var route = new Route(url); actions = extend({}, DEFAULT_ACTIONS, actions); function extractParams(data, actionParams){ var ids = {}; actionParams = extend({}, paramDefaults, actionParams); forEach(actionParams, function(value, key){ ids[key] = value.charAt && value.charAt(0) == '@' ? getter(data, value.substr(1)) : value; }); return ids; } function Resource(value){ copy(value || {}, this); } forEach(actions, function(action, name) { action.method = angular.uppercase(action.method); var hasBody = action.method == 'POST' || action.method == 'PUT' || action.method == 'PATCH'; Resource[name] = function(a1, a2, a3, a4) { var params = {}; var data; var success = noop; var error = null; switch(arguments.length) { case 4: error = a4; success = a3; //fallthrough case 3: case 2: if (isFunction(a2)) { if (isFunction(a1)) { success = a1; error = a2; break; } success = a2; error = a3; //fallthrough } else { params = a1; data = a2; success = a3; break; } case 1: if (isFunction(a1)) success = a1; else if (hasBody) data = a1; else params = a1; break; case 0: break; default: throw "Expected between 0-4 arguments [params, data, success, error], got " + arguments.length + " arguments."; } var value = this instanceof Resource ? this : (action.isArray ? [] : new Resource(data)); $http({ method: action.method, url: route.url(extend({}, extractParams(data, action.params || {}), params)), data: data }).then(function(response) { var data = response.data; if (data) { if (action.isArray) { value.length = 0; forEach(data, function(item) { value.push(new Resource(item)); }); } else { copy(data, value); } } (success||noop)(value, response.headers); }, error); return value; }; Resource.prototype['$' + name] = function(a1, a2, a3) { var params = extractParams(this), success = noop, error; switch(arguments.length) { case 3: params = a1; success = a2; error = a3; break; case 2: case 1: if (isFunction(a1)) { success = a1; error = a2; } else { params = a1; success = a2 || noop; } case 0: break; default: throw "Expected between 1-3 arguments [params, success, error], got " + arguments.length + " arguments."; } var data = hasBody ? this : undefined; Resource[name].call(this, params, data, success, error); }; }); Resource.bind = function(additionalParamDefaults){ return ResourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions); }; return Resource; } return ResourceFactory; }]); })(window, window.angular);
bacardi55/b-55-log
web/jocs/components/angular-resource/angular-resource.js
JavaScript
mit
17,163
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Allows the execution of relational queries, including those expressed in SQL using Spark. */ package org.apache.spark.sql.api.java;
esi-mineset/spark
sql/core/src/main/java/org/apache/spark/sql/api/java/package-info.java
Java
apache-2.0
942
import { Duration, isDuration } from './constructor'; import toInt from '../utils/to-int'; import hasOwnProp from '../utils/has-own-prop'; import { DATE, HOUR, MINUTE, SECOND, MILLISECOND } from '../units/constants'; import { cloneWithOffset } from '../units/offset'; import { createLocal } from '../create/local'; // ASP.NET json date format regex var aspNetRegex = /^(\-)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?\d*)?$/; // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere // and further modified to allow for strings containing both week and day var isoRegex = /^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/; export function createDuration (input, key) { var duration = input, // matching against regexp is expensive, do it on demand match = null, sign, ret, diffRes; if (isDuration(input)) { duration = { ms : input._milliseconds, d : input._days, M : input._months }; } else if (typeof input === 'number') { duration = {}; if (key) { duration[key] = input; } else { duration.milliseconds = input; } } else if (!!(match = aspNetRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; duration = { y : 0, d : toInt(match[DATE]) * sign, h : toInt(match[HOUR]) * sign, m : toInt(match[MINUTE]) * sign, s : toInt(match[SECOND]) * sign, ms : toInt(match[MILLISECOND]) * sign }; } else if (!!(match = isoRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; duration = { y : parseIso(match[2], sign), M : parseIso(match[3], sign), w : parseIso(match[4], sign), d : parseIso(match[5], sign), h : parseIso(match[6], sign), m : parseIso(match[7], sign), s : parseIso(match[8], sign) }; } else if (duration == null) {// checks for null or undefined duration = {}; } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to)); duration = {}; duration.ms = diffRes.milliseconds; duration.M = diffRes.months; } ret = new Duration(duration); if (isDuration(input) && hasOwnProp(input, '_locale')) { ret._locale = input._locale; } return ret; } createDuration.fn = Duration.prototype; function parseIso (inp, sign) { // We'd normally use ~~inp for this, but unfortunately it also // converts floats to ints. // inp may be undefined, so careful calling replace on it. var res = inp && parseFloat(inp.replace(',', '.')); // apply sign while we're at it return (isNaN(res) ? 0 : res) * sign; } function positiveMomentsDifference(base, other) { var res = {milliseconds: 0, months: 0}; res.months = other.month() - base.month() + (other.year() - base.year()) * 12; if (base.clone().add(res.months, 'M').isAfter(other)) { --res.months; } res.milliseconds = +other - +(base.clone().add(res.months, 'M')); return res; } function momentsDifference(base, other) { var res; if (!(base.isValid() && other.isValid())) { return {milliseconds: 0, months: 0}; } other = cloneWithOffset(other, base); if (base.isBefore(other)) { res = positiveMomentsDifference(base, other); } else { res = positiveMomentsDifference(other, base); res.milliseconds = -res.milliseconds; res.months = -res.months; } return res; }
krasnyuk/e-liquid-MS
wwwroot/assets/js/moment/src/lib/duration/create.js
JavaScript
mit
3,948
// { dg-do assemble } template <class T> void foo(); // { dg-message "" } candidate void (*bar)() = foo<void>; void (*baz)() = foo; // { dg-error "" } can't deduce T
selmentdev/selment-toolchain
source/gcc-latest/gcc/testsuite/g++.old-deja/g++.pt/overload5.C
C++
gpl-3.0
169
<?php namespace Illuminate\Validation; use Exception; class ValidationException extends Exception { /** * The validator instance. * * @var \Illuminate\Validation\Validator */ public $validator; /** * The recommended response to send to the client. * * @var \Illuminate\Http\Response|null */ public $response; /** * Create a new exception instance. * * @param \Illuminate\Validation\Validator $validator * @param \Illuminate\Http\Response $response * @return void */ public function __construct($validator, $response = null) { parent::__construct('The given data failed to pass validation.'); $this->response = $response; $this->validator = $validator; } /** * Get the underlying response instance. * * @return \Symfony\Component\HttpFoundation\Response */ public function getResponse() { return $this->response; } }
goldenscarab/scriba
vendor/laravel/framework/src/Illuminate/Validation/ValidationException.php
PHP
mit
997
/* jshint -W100 */ /* jslint maxlen: 86 */ define(function () { // Farsi (Persian) return { errorLoading: function () { return 'امکان بارگذاری نتایج وجود ندارد.'; }, inputTooLong: function (args) { var overChars = args.input.length - args.maximum; var message = 'لطفاً ' + overChars + ' کاراکتر را حذف نمایید'; return message; }, inputTooShort: function (args) { var remainingChars = args.minimum - args.input.length; var message = 'لطفاً تعداد ' + remainingChars + ' کاراکتر یا بیشتر وارد نمایید'; return message; }, loadingMore: function () { return 'در حال بارگذاری نتایج بیشتر...'; }, maximumSelected: function (args) { var message = 'شما تنها می‌توانید ' + args.maximum + ' آیتم را انتخاب نمایید'; return message; }, noResults: function () { return 'هیچ نتیجه‌ای یافت نشد'; }, searching: function () { return 'در حال جستجو...'; } }; });
krasnyuk/e-liquid-MS
wwwroot/assets/js/select2/src/js/select2/i18n/fa.js
JavaScript
mit
1,152
/* * Copyright (C) 2005-2013 Team XBMC * http://xbmc.org * * 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 2, 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 XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "DirectoryNodeAlbumCompilations.h" #include "QueryParams.h" #include "music/MusicDatabase.h" using namespace XFILE::MUSICDATABASEDIRECTORY; CDirectoryNodeAlbumCompilations::CDirectoryNodeAlbumCompilations(const std::string& strName, CDirectoryNode* pParent) : CDirectoryNode(NODE_TYPE_ALBUM_COMPILATIONS, strName, pParent) { } NODE_TYPE CDirectoryNodeAlbumCompilations::GetChildType() const { if (GetName()=="-1") return NODE_TYPE_ALBUM_COMPILATIONS_SONGS; return NODE_TYPE_SONG; } std::string CDirectoryNodeAlbumCompilations::GetLocalizedName() const { if (GetID() == -1) return g_localizeStrings.Get(15102); // All Albums CMusicDatabase db; if (db.Open()) return db.GetAlbumById(GetID()); return ""; } bool CDirectoryNodeAlbumCompilations::GetContent(CFileItemList& items) const { CMusicDatabase musicdatabase; if (!musicdatabase.Open()) return false; CQueryParams params; CollectQueryParams(params); bool bSuccess=musicdatabase.GetCompilationAlbums(BuildPath(), items); musicdatabase.Close(); return bSuccess; }
joethefox/xbmc
xbmc/filesystem/MusicDatabaseDirectory/DirectoryNodeAlbumCompilations.cpp
C++
gpl-2.0
1,817
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.oncrpc; /** * Represent an RPC message as defined in RFC 1831. */ public abstract class RpcMessage { /** Message type */ public static enum Type { // the order of the values below are significant. RPC_CALL, RPC_REPLY; public int getValue() { return ordinal(); } public static Type fromValue(int value) { if (value < 0 || value >= values().length) { return null; } return values()[value]; } } protected final int xid; protected final Type messageType; RpcMessage(int xid, Type messageType) { if (messageType != Type.RPC_CALL && messageType != Type.RPC_REPLY) { throw new IllegalArgumentException("Invalid message type " + messageType); } this.xid = xid; this.messageType = messageType; } public abstract XDR write(XDR xdr); public int getXid() { return xid; } public Type getMessageType() { return messageType; } protected void validateMessageType(Type expected) { if (expected != messageType) { throw new IllegalArgumentException("Message type is expected to be " + expected + " but got " + messageType); } } }
tseen/Federated-HDFS
tseenliu/FedHDFS-hadoop-src/hadoop-common-project/hadoop-nfs/src/main/java/org/apache/hadoop/oncrpc/RpcMessage.java
Java
apache-2.0
2,009
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.ExceptionServices; using System.Threading; namespace System.Threading.Tasks { internal static class ExceptionDispatchHelper { internal static void ThrowAsync(Exception exception, SynchronizationContext targetContext) { if (exception == null) return; // TODO - decide how to cleanly do it so it lights up if TA is defined //if (exception is ThreadAbortException) // return; ExceptionDispatchInfo exceptionDispatchInfo = ExceptionDispatchInfo.Capture(exception); if (targetContext != null) { try { targetContext.Post((edi) => ((ExceptionDispatchInfo)edi).Throw(), exceptionDispatchInfo); } catch { // Something went wrong in the Post; let's try using the thread pool instead: ThrowAsync(exception, null); } return; } bool scheduled = true; try { new SynchronizationContext().Post((edi) => ((ExceptionDispatchInfo)edi).Throw(), exceptionDispatchInfo); } catch { // Something went wrong when scheduling the thrower; we do our best by throwing the exception here: scheduled = false; } if (!scheduled) exceptionDispatchInfo.Throw(); } } // ExceptionDispatchHelper } // namespace // ExceptionDispatchHelper.cs
krytarowski/corefx
src/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/ExceptionDispatchHelper.cs
C#
mit
1,835
<?php /* * This file is part of the symfony package. * (c) Fabien Potencier <fabien.potencier@symfony-project.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ require_once(dirname(__FILE__).'/../../bootstrap/unit.php'); class FormFormatterStub extends sfWidgetFormSchemaFormatter { public function __construct() {} public function translate($subject, $parameters = array()) { return sprintf('translation[%s]', $subject); } } $t = new lime_test(13); $dom = new DomDocument('1.0', 'utf-8'); $dom->validateOnParse = true; // ->render() $t->diag('->render()'); $w = new sfWidgetFormSelectCheckbox(array('choices' => array('foo' => 'bar', 'foobar' => 'foo'), 'separator' => '')); $output = '<ul class="checkbox_list">'. '<li><input name="foo[]" type="checkbox" value="foo" id="foo_foo" />&nbsp;<label for="foo_foo">bar</label></li>'. '<li><input name="foo[]" type="checkbox" value="foobar" id="foo_foobar" checked="checked" />&nbsp;<label for="foo_foobar">foo</label></li>'. '</ul>'; $t->is($w->render('foo', array('foobar')), $output, '->render() renders a checkbox tag with the value checked'); // attributes $onChange = '<ul class="checkbox_list">'. '<li><input name="foo[]" type="checkbox" value="foo" id="foo_foo" onChange="alert(42)" />'. '&nbsp;<label for="foo_foo">bar</label></li>'. '<li><input name="foo[]" type="checkbox" value="foobar" id="foo_foobar" checked="checked" onChange="alert(42)" />'. '&nbsp;<label for="foo_foobar">foo</label></li>'. '</ul>'; $t->is($w->render('foo', array('foobar'), array('onChange' => 'alert(42)')), $onChange, '->render() renders a checkbox tag using extra attributes'); $w = new sfWidgetFormSelectCheckbox(array('choices' => array('0' => 'bar', '1' => 'foo'))); $output = <<< EOF <ul class="checkbox_list"><li><input name="myname[]" type="checkbox" value="0" id="myname_0" checked="checked" />&nbsp;<label for="myname_0">bar</label></li> <li><input name="myname[]" type="checkbox" value="1" id="myname_1" />&nbsp;<label for="myname_1">foo</label></li></ul> EOF; $t->is($w->render('myname', array(false)), fix_linebreaks($output), '->render() considers false to be an integer 0'); $w = new sfWidgetFormSelectCheckbox(array('choices' => array('0' => 'bar', '1' => 'foo'))); $output = <<< EOF <ul class="checkbox_list"><li><input name="myname[]" type="checkbox" value="0" id="myname_0" />&nbsp;<label for="myname_0">bar</label></li> <li><input name="myname[]" type="checkbox" value="1" id="myname_1" checked="checked" />&nbsp;<label for="myname_1">foo</label></li></ul> EOF; $t->is($w->render('myname', array(true)), fix_linebreaks($output), '->render() considers true to be an integer 1'); $w = new sfWidgetFormSelectCheckbox(array('choices' => array())); $t->is($w->render('myname', array()), '', '->render() returns an empty HTML string if no choices'); // group support $t->diag('group support'); $w = new sfWidgetFormSelectCheckbox(array('choices' => array('foo' => array('foo' => 'bar', 'bar' => 'foo'), 'bar' => array('foobar' => 'barfoo')))); $output = <<<EOF foo <ul class="checkbox_list"><li><input name="foo[]" type="checkbox" value="foo" id="foo_foo" checked="checked" />&nbsp;<label for="foo_foo">bar</label></li> <li><input name="foo[]" type="checkbox" value="bar" id="foo_bar" />&nbsp;<label for="foo_bar">foo</label></li></ul> bar <ul class="checkbox_list"><li><input name="foo[]" type="checkbox" value="foobar" id="foo_foobar" checked="checked" />&nbsp;<label for="foo_foobar">barfoo</label></li></ul> EOF; $t->is($w->render('foo', array('foo', 'foobar')), fix_linebreaks($output), '->render() has support for groups'); $w->setOption('choices', array('foo' => array('foo' => 'bar', 'bar' => 'foo'))); $output = <<<EOF foo <ul class="checkbox_list"><li><input name="foo[]" type="checkbox" value="foo" id="foo_foo" />&nbsp;<label for="foo_foo">bar</label></li> <li><input name="foo[]" type="checkbox" value="bar" id="foo_bar" checked="checked" />&nbsp;<label for="foo_bar">foo</label></li></ul> EOF; $t->is($w->render('foo', array('bar')), fix_linebreaks($output), '->render() accepts a single group'); try { $w = new sfWidgetFormSelectCheckbox(); $t->fail('__construct() throws an RuntimeException if you don\'t pass a choices option'); } catch (RuntimeException $e) { $t->pass('__construct() throws an RuntimeException if you don\'t pass a choices option'); } // choices as a callable $t->diag('choices as a callable'); function choice_callable() { return array(1, 2, 3); } $w = new sfWidgetFormSelectCheckbox(array('choices' => new sfCallable('choice_callable'))); $dom->loadHTML($w->render('foo')); $css = new sfDomCssSelector($dom); $t->is(count($css->matchAll('input[type="checkbox"]')->getNodes()), 3, '->render() accepts a sfCallable as a choices option'); // choices are translated $t->diag('choices are translated'); $ws = new sfWidgetFormSchema(); $ws->addFormFormatter('stub', new FormFormatterStub()); $ws->setFormFormatterName('stub'); $w = new sfWidgetFormSelectCheckbox(array('choices' => array('foo' => 'bar', 'foobar' => 'foo'), 'separator' => '')); $w->setParent($ws); $output = '<ul class="checkbox_list">'. '<li><input name="foo[]" type="checkbox" value="foo" id="foo_foo" />&nbsp;<label for="foo_foo">translation[bar]</label></li>'. '<li><input name="foo[]" type="checkbox" value="foobar" id="foo_foobar" />&nbsp;<label for="foo_foobar">translation[foo]</label></li>'. '</ul>'; $t->is($w->render('foo'), $output, '->render() translates the options'); // choices are escaped $t->diag('choices are escaped'); $w = new sfWidgetFormSelectCheckbox(array('choices' => array('<b>Hello world</b>'))); $t->is($w->render('foo'), '<ul class="checkbox_list"><li><input name="foo[]" type="checkbox" value="0" id="foo_0" />&nbsp;<label for="foo_0">&lt;b&gt;Hello world&lt;/b&gt;</label></li></ul>', '->render() escapes the choices'); // __clone() $t->diag('__clone()'); $w = new sfWidgetFormSelectCheckbox(array('choices' => new sfCallable(array($w, 'foo')))); $w1 = clone $w; $callable = $w1->getOption('choices')->getCallable(); $t->is(spl_object_hash($callable[0]), spl_object_hash($w1), '__clone() changes the choices is a callable and the object is an instance of the current object'); $w = new sfWidgetFormSelectCheckbox(array('choices' => new sfCallable(array($a = new stdClass(), 'foo')))); $w1 = clone $w; $callable = $w1->getOption('choices')->getCallable(); $t->is(spl_object_hash($callable[0]), spl_object_hash($a), '__clone() changes nothing if the choices is a callable and the object is not an instance of the current object');
voota/voota
www/lib/vendor/symfony/test/unit/widget/sfWidgetFormSelectCheckboxTest.php
PHP
mit
6,638
/* TwoWire.cpp - TWI/I2C library for Wiring & Arduino Copyright (c) 2006 Nicholas Zambetti. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Modified 2012 by Todd Krein (todd@krein.org) to implement repeated starts */ extern "C" { #include <stdlib.h> #include <string.h> #include <inttypes.h> #include "twi.h" } #include "Wire.h" // Initialize Class Variables ////////////////////////////////////////////////// uint8_t TwoWire::rxBuffer[BUFFER_LENGTH]; uint8_t TwoWire::rxBufferIndex = 0; uint8_t TwoWire::rxBufferLength = 0; uint8_t TwoWire::txAddress = 0; uint8_t TwoWire::txBuffer[BUFFER_LENGTH]; uint8_t TwoWire::txBufferIndex = 0; uint8_t TwoWire::txBufferLength = 0; uint8_t TwoWire::transmitting = 0; void (*TwoWire::user_onRequest)(void); void (*TwoWire::user_onReceive)(int); // Constructors //////////////////////////////////////////////////////////////// TwoWire::TwoWire() { } // Public Methods ////////////////////////////////////////////////////////////// void TwoWire::begin(void) { rxBufferIndex = 0; rxBufferLength = 0; txBufferIndex = 0; txBufferLength = 0; twi_init(); } void TwoWire::begin(uint8_t address) { twi_setAddress(address); twi_attachSlaveTxEvent(onRequestService); twi_attachSlaveRxEvent(onReceiveService); begin(); } void TwoWire::begin(int address) { begin((uint8_t)address); } uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity, uint8_t sendStop) { // clamp to buffer length if(quantity > BUFFER_LENGTH){ quantity = BUFFER_LENGTH; } // perform blocking read into buffer uint8_t read = twi_readFrom(address, rxBuffer, quantity, sendStop); // set rx buffer iterator vars rxBufferIndex = 0; rxBufferLength = read; return read; } uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity) { return requestFrom((uint8_t)address, (uint8_t)quantity, (uint8_t)true); } uint8_t TwoWire::requestFrom(int address, int quantity) { return requestFrom((uint8_t)address, (uint8_t)quantity, (uint8_t)true); } uint8_t TwoWire::requestFrom(int address, int quantity, int sendStop) { return requestFrom((uint8_t)address, (uint8_t)quantity, (uint8_t)sendStop); } void TwoWire::beginTransmission(uint8_t address) { // indicate that we are transmitting transmitting = 1; // set address of targeted slave txAddress = address; // reset tx buffer iterator vars txBufferIndex = 0; txBufferLength = 0; } void TwoWire::beginTransmission(int address) { beginTransmission((uint8_t)address); } // // Originally, 'endTransmission' was an f(void) function. // It has been modified to take one parameter indicating // whether or not a STOP should be performed on the bus. // Calling endTransmission(false) allows a sketch to // perform a repeated start. // // WARNING: Nothing in the library keeps track of whether // the bus tenure has been properly ended with a STOP. It // is very possible to leave the bus in a hung state if // no call to endTransmission(true) is made. Some I2C // devices will behave oddly if they do not see a STOP. // uint8_t TwoWire::endTransmission(uint8_t sendStop) { // transmit buffer (blocking) int8_t ret = twi_writeTo(txAddress, txBuffer, txBufferLength, 1, sendStop); // reset tx buffer iterator vars txBufferIndex = 0; txBufferLength = 0; // indicate that we are done transmitting transmitting = 0; return ret; } // This provides backwards compatibility with the original // definition, and expected behaviour, of endTransmission // uint8_t TwoWire::endTransmission(void) { return endTransmission(true); } // must be called in: // slave tx event callback // or after beginTransmission(address) size_t TwoWire::write(uint8_t data) { if(transmitting){ // in master transmitter mode // don't bother if buffer is full if(txBufferLength >= BUFFER_LENGTH){ setWriteError(); return 0; } // put byte in tx buffer txBuffer[txBufferIndex] = data; ++txBufferIndex; // update amount in buffer txBufferLength = txBufferIndex; }else{ // in slave send mode // reply to master twi_transmit(&data, 1); } return 1; } // must be called in: // slave tx event callback // or after beginTransmission(address) size_t TwoWire::write(const uint8_t *data, size_t quantity) { if(transmitting){ // in master transmitter mode for(size_t i = 0; i < quantity; ++i){ write(data[i]); } }else{ // in slave send mode // reply to master twi_transmit(data, quantity); } return quantity; } // must be called in: // slave rx event callback // or after requestFrom(address, numBytes) int TwoWire::available(void) { return rxBufferLength - rxBufferIndex; } // must be called in: // slave rx event callback // or after requestFrom(address, numBytes) int TwoWire::read(void) { int value = -1; // get each successive byte on each call if(rxBufferIndex < rxBufferLength){ value = rxBuffer[rxBufferIndex]; ++rxBufferIndex; } return value; } // must be called in: // slave rx event callback // or after requestFrom(address, numBytes) int TwoWire::peek(void) { int value = -1; if(rxBufferIndex < rxBufferLength){ value = rxBuffer[rxBufferIndex]; } return value; } void TwoWire::flush(void) { // XXX: to be implemented. } // behind the scenes function that is called when data is received void TwoWire::onReceiveService(uint8_t* inBytes, int numBytes) { // don't bother if user hasn't registered a callback if(!user_onReceive){ return; } // don't bother if rx buffer is in use by a master requestFrom() op // i know this drops data, but it allows for slight stupidity // meaning, they may not have read all the master requestFrom() data yet if(rxBufferIndex < rxBufferLength){ return; } // copy twi rx buffer into local read buffer // this enables new reads to happen in parallel for(uint8_t i = 0; i < numBytes; ++i){ rxBuffer[i] = inBytes[i]; } // set rx iterator vars rxBufferIndex = 0; rxBufferLength = numBytes; // alert user program user_onReceive(numBytes); } // behind the scenes function that is called when data is requested void TwoWire::onRequestService(void) { // don't bother if user hasn't registered a callback if(!user_onRequest){ return; } // reset tx buffer iterator vars // !!! this will kill any pending pre-master sendTo() activity txBufferIndex = 0; txBufferLength = 0; // alert user program user_onRequest(); } // sets function called on slave write void TwoWire::onReceive( void (*function)(int) ) { user_onReceive = function; } // sets function called on slave read void TwoWire::onRequest( void (*function)(void) ) { user_onRequest = function; } // Preinstantiate Objects ////////////////////////////////////////////////////// TwoWire Wire = TwoWire();
chcbaram/FPGA
zap-2.3.0-windows/papilio-zap-ide/hardware/arduino/avr/libraries/Wire/Wire.cpp
C++
mit
7,532
//! moment.js locale configuration //! locale : belarusian (be) //! author : Dmitry Demidov : https://github.com/demidov91 //! author: Praleska: http://praleska.pro/ //! Author : Menelion Elensúle : https://github.com/Oire import moment from '../moment'; function plural(word, num) { var forms = word.split('_'); return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); } function relativeTimeWithPlural(number, withoutSuffix, key) { var format = { 'mm': withoutSuffix ? 'хвіліна_хвіліны_хвілін' : 'хвіліну_хвіліны_хвілін', 'hh': withoutSuffix ? 'гадзіна_гадзіны_гадзін' : 'гадзіну_гадзіны_гадзін', 'dd': 'дзень_дні_дзён', 'MM': 'месяц_месяцы_месяцаў', 'yy': 'год_гады_гадоў' }; if (key === 'm') { return withoutSuffix ? 'хвіліна' : 'хвіліну'; } else if (key === 'h') { return withoutSuffix ? 'гадзіна' : 'гадзіну'; } else { return number + ' ' + plural(format[key], +number); } } function monthsCaseReplace(m, format) { var months = { 'nominative': 'студзень_люты_сакавік_красавік_травень_чэрвень_ліпень_жнівень_верасень_кастрычнік_лістапад_снежань'.split('_'), 'accusative': 'студзеня_лютага_сакавіка_красавіка_траўня_чэрвеня_ліпеня_жніўня_верасня_кастрычніка_лістапада_снежня'.split('_') }, nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ? 'accusative' : 'nominative'; return months[nounCase][m.month()]; } function weekdaysCaseReplace(m, format) { var weekdays = { 'nominative': 'нядзеля_панядзелак_аўторак_серада_чацвер_пятніца_субота'.split('_'), 'accusative': 'нядзелю_панядзелак_аўторак_сераду_чацвер_пятніцу_суботу'.split('_') }, nounCase = (/\[ ?[Вв] ?(?:мінулую|наступную)? ?\] ?dddd/).test(format) ? 'accusative' : 'nominative'; return weekdays[nounCase][m.day()]; } export default moment.defineLocale('be', { months : monthsCaseReplace, monthsShort : 'студ_лют_сак_крас_трав_чэрв_ліп_жнів_вер_каст_ліст_снеж'.split('_'), weekdays : weekdaysCaseReplace, weekdaysShort : 'нд_пн_ат_ср_чц_пт_сб'.split('_'), weekdaysMin : 'нд_пн_ат_ср_чц_пт_сб'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD.MM.YYYY', LL : 'D MMMM YYYY г.', LLL : 'D MMMM YYYY г., HH:mm', LLLL : 'dddd, D MMMM YYYY г., HH:mm' }, calendar : { sameDay: '[Сёння ў] LT', nextDay: '[Заўтра ў] LT', lastDay: '[Учора ў] LT', nextWeek: function () { return '[У] dddd [ў] LT'; }, lastWeek: function () { switch (this.day()) { case 0: case 3: case 5: case 6: return '[У мінулую] dddd [ў] LT'; case 1: case 2: case 4: return '[У мінулы] dddd [ў] LT'; } }, sameElse: 'L' }, relativeTime : { future : 'праз %s', past : '%s таму', s : 'некалькі секунд', m : relativeTimeWithPlural, mm : relativeTimeWithPlural, h : relativeTimeWithPlural, hh : relativeTimeWithPlural, d : 'дзень', dd : relativeTimeWithPlural, M : 'месяц', MM : relativeTimeWithPlural, y : 'год', yy : relativeTimeWithPlural }, meridiemParse: /ночы|раніцы|дня|вечара/, isPM : function (input) { return /^(дня|вечара)$/.test(input); }, meridiem : function (hour, minute, isLower) { if (hour < 4) { return 'ночы'; } else if (hour < 12) { return 'раніцы'; } else if (hour < 17) { return 'дня'; } else { return 'вечара'; } }, ordinalParse: /\d{1,2}-(і|ы|га)/, ordinal: function (number, period) { switch (period) { case 'M': case 'd': case 'DDD': case 'w': case 'W': return (number % 10 === 2 || number % 10 === 3) && (number % 100 !== 12 && number % 100 !== 13) ? number + '-і' : number + '-ы'; case 'D': return number + '-га'; default: return number; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } });
LilShy/test
新建文件夹/material_admin_v-1.5-2/Template/jquery/vendors/bower_components/moment/src/locale/be.js
JavaScript
apache-2.0
5,171
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "go/ast" "go/parser" "go/token" "os" "path" "runtime" "strings" ) func isGoFile(dir os.FileInfo) bool { return !dir.IsDir() && !strings.HasPrefix(dir.Name(), ".") && // ignore .files path.Ext(dir.Name()) == ".go" } func isPkgFile(dir os.FileInfo) bool { return isGoFile(dir) && !strings.HasSuffix(dir.Name(), "_test.go") // ignore test files } func pkgName(filename string) string { file, err := parser.ParseFile(token.NewFileSet(), filename, nil, parser.PackageClauseOnly) if err != nil || file == nil { return "" } return file.Name.Name } func parseDir(dirpath string) map[string]*ast.Package { // the package name is the directory name within its parent. // (use dirname instead of path because dirname is clean; it // has no trailing '/') _, pkgname := path.Split(dirpath) // filter function to select the desired .go files filter := func(d os.FileInfo) bool { if isPkgFile(d) { // Some directories contain main packages: Only accept // files that belong to the expected package so that // parser.ParsePackage doesn't return "multiple packages // found" errors. // Additionally, accept the special package name // fakePkgName if we are looking at cmd documentation. name := pkgName(dirpath + "/" + d.Name()) return name == pkgname } return false } // get package AST pkgs, err := parser.ParseDir(token.NewFileSet(), dirpath, filter, parser.ParseComments) if err != nil { println("parse", dirpath, err.Error()) panic("go ParseDir fail: " + err.Error()) } return pkgs } func stressParseGo() { pkgroot := runtime.GOROOT() + "/src/" for { m := make(map[string]map[string]*ast.Package) for _, pkg := range packages { m[pkg] = parseDir(pkgroot + pkg) Println("parsed go package", pkg) } } } // find . -type d -not -path "./exp" -not -path "./exp/*" -printf "\t\"%p\",\n" | sort | sed "s/\.\///" | grep -v testdata var packages = []string{ "archive", "archive/tar", "archive/zip", "bufio", "builtin", "bytes", "compress", "compress/bzip2", "compress/flate", "compress/gzip", "compress/lzw", "compress/zlib", "container", "container/heap", "container/list", "container/ring", "crypto", "crypto/aes", "crypto/cipher", "crypto/des", "crypto/dsa", "crypto/ecdsa", "crypto/elliptic", "crypto/hmac", "crypto/md5", "crypto/rand", "crypto/rc4", "crypto/rsa", "crypto/sha1", "crypto/sha256", "crypto/sha512", "crypto/subtle", "crypto/tls", "crypto/x509", "crypto/x509/pkix", "database", "database/sql", "database/sql/driver", "debug", "debug/dwarf", "debug/elf", "debug/gosym", "debug/macho", "debug/pe", "encoding", "encoding/ascii85", "encoding/asn1", "encoding/base32", "encoding/base64", "encoding/binary", "encoding/csv", "encoding/gob", "encoding/hex", "encoding/json", "encoding/pem", "encoding/xml", "errors", "expvar", "flag", "fmt", "go", "go/ast", "go/build", "go/doc", "go/format", "go/parser", "go/printer", "go/scanner", "go/token", "hash", "hash/adler32", "hash/crc32", "hash/crc64", "hash/fnv", "html", "html/template", "image", "image/color", "image/draw", "image/gif", "image/jpeg", "image/png", "index", "index/suffixarray", "io", "io/ioutil", "log", "log/syslog", "math", "math/big", "math/cmplx", "math/rand", "mime", "mime/multipart", "net", "net/http", "net/http/cgi", "net/http/cookiejar", "net/http/fcgi", "net/http/httptest", "net/http/httputil", "net/http/pprof", "net/mail", "net/rpc", "net/rpc/jsonrpc", "net/smtp", "net/textproto", "net/url", "os", "os/exec", "os/signal", "os/user", "path", "path/filepath", "reflect", "regexp", "regexp/syntax", "runtime", "runtime/cgo", "runtime/debug", "runtime/pprof", "runtime/race", "sort", "strconv", "strings", "sync", "sync/atomic", "syscall", "testing", "testing/iotest", "testing/quick", "text", "text/scanner", "text/tabwriter", "text/template", "text/template/parse", "time", "unicode", "unicode/utf16", "unicode/utf8", "unsafe", }
shishkander/go
test/stress/parsego.go
GO
bsd-3-clause
4,212
<?php /** * @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ // No direct access. defined('_JEXEC') or die; jimport('joomla.application.component.modellist'); /** * Messages Component Messages Model * * @package Joomla.Administrator * @subpackage com_messages * @since 1.6 */ class MessagesModelMessages extends JModelList { /** * Constructor. * * @param array An optional associative array of configuration settings. * @see JController * @since 1.6 */ public function __construct($config = array()) { if (empty($config['filter_fields'])) { $config['filter_fields'] = array( 'message_id', 'a.id', 'subject', 'a.subject', 'state', 'a.state', 'user_id_from', 'a.user_id_from', 'user_id_to', 'a.user_id_to', 'date_time', 'a.date_time', 'priority', 'a.priority', ); } parent::__construct($config); } /** * Method to auto-populate the model state. * * Note. Calling getState in this method will result in recursion. * * @since 1.6 */ protected function populateState($ordering = null, $direction = null) { // Initialise variables. $app = JFactory::getApplication('administrator'); // Load the filter state. $search = $this->getUserStateFromRequest($this->context.'.filter.search', 'filter_search'); $this->setState('filter.search', $search); $state = $this->getUserStateFromRequest($this->context.'.filter.state', 'filter_state', '', 'string'); $this->setState('filter.state', $state); // List state information. parent::populateState('a.date_time', 'desc'); } /** * Method to get a store id based on model configuration state. * * This is necessary because the model is used by the component and * different modules that might need different sets of data or different * ordering requirements. * * @param string A prefix for the store id. * * @return string A store id. */ protected function getStoreId($id = '') { // Compile the store id. $id .= ':'.$this->getState('filter.search'); $id .= ':'.$this->getState('filter.state'); return parent::getStoreId($id); } /** * Build an SQL query to load the list data. * * @return JDatabaseQuery */ protected function getListQuery() { // Create a new query object. $db = $this->getDbo(); $query = $db->getQuery(true); $user = JFactory::getUser(); // Select the required fields from the table. $query->select( $this->getState( 'list.select', 'a.*, '. 'u.name AS user_from' ) ); $query->from('#__messages AS a'); // Join over the users for message owner. $query->join('INNER', '#__users AS u ON u.id = a.user_id_from'); $query->where('a.user_id_to = '.(int) $user->get('id')); // Filter by published state. $state = $this->getState('filter.state'); if (is_numeric($state)) { $query->where('a.state = '.(int) $state); } elseif ($state === '') { $query->where('(a.state IN (0, 1))'); } // Filter by search in subject or message. $search = $this->getState('filter.search'); if (!empty($search)) { $search = $db->Quote('%'.$db->escape($search, true).'%', false); $query->where('a.subject LIKE '.$search.' OR a.message LIKE '.$search); } // Add the list ordering clause. $query->order($db->escape($this->getState('list.ordering', 'a.date_time')).' '.$db->escape($this->getState('list.direction', 'DESC'))); //echo nl2br(str_replace('#__','jos_',$query)); return $query; } }
baxri/cvote
tmp/install_54bd2998c811f/administrator/components/com_messages/models/messages.php
PHP
gpl-2.0
3,562
#!/usr/bin/env node require("./bin/npm-cli.js")
nikste/visualizationDemo
zeppelin-web/node/npm/cli.js
JavaScript
apache-2.0
48
package client import ( "bufio" "crypto/tls" "fmt" "net" "net/http" "net/http/httputil" "net/url" "strings" "time" "github.com/docker/docker/api/types" "github.com/docker/docker/pkg/tlsconfig" "github.com/docker/go-connections/sockets" "github.com/pkg/errors" "golang.org/x/net/context" ) // tlsClientCon holds tls information and a dialed connection. type tlsClientCon struct { *tls.Conn rawConn net.Conn } func (c *tlsClientCon) CloseWrite() error { // Go standard tls.Conn doesn't provide the CloseWrite() method so we do it // on its underlying connection. if conn, ok := c.rawConn.(types.CloseWriter); ok { return conn.CloseWrite() } return nil } // postHijacked sends a POST request and hijacks the connection. func (cli *Client) postHijacked(ctx context.Context, path string, query url.Values, body interface{}, headers map[string][]string) (types.HijackedResponse, error) { bodyEncoded, err := encodeData(body) if err != nil { return types.HijackedResponse{}, err } apiPath := cli.getAPIPath(path, query) req, err := http.NewRequest("POST", apiPath, bodyEncoded) if err != nil { return types.HijackedResponse{}, err } req = cli.addHeaders(req, headers) conn, err := cli.setupHijackConn(req, "tcp") if err != nil { return types.HijackedResponse{}, err } return types.HijackedResponse{Conn: conn, Reader: bufio.NewReader(conn)}, err } func tlsDial(network, addr string, config *tls.Config) (net.Conn, error) { return tlsDialWithDialer(new(net.Dialer), network, addr, config) } // We need to copy Go's implementation of tls.Dial (pkg/cryptor/tls/tls.go) in // order to return our custom tlsClientCon struct which holds both the tls.Conn // object _and_ its underlying raw connection. The rationale for this is that // we need to be able to close the write end of the connection when attaching, // which tls.Conn does not provide. func tlsDialWithDialer(dialer *net.Dialer, network, addr string, config *tls.Config) (net.Conn, error) { // We want the Timeout and Deadline values from dialer to cover the // whole process: TCP connection and TLS handshake. This means that we // also need to start our own timers now. timeout := dialer.Timeout if !dialer.Deadline.IsZero() { deadlineTimeout := dialer.Deadline.Sub(time.Now()) if timeout == 0 || deadlineTimeout < timeout { timeout = deadlineTimeout } } var errChannel chan error if timeout != 0 { errChannel = make(chan error, 2) time.AfterFunc(timeout, func() { errChannel <- errors.New("") }) } proxyDialer, err := sockets.DialerFromEnvironment(dialer) if err != nil { return nil, err } rawConn, err := proxyDialer.Dial(network, addr) if err != nil { return nil, err } // When we set up a TCP connection for hijack, there could be long periods // of inactivity (a long running command with no output) that in certain // network setups may cause ECONNTIMEOUT, leaving the client in an unknown // state. Setting TCP KeepAlive on the socket connection will prohibit // ECONNTIMEOUT unless the socket connection truly is broken if tcpConn, ok := rawConn.(*net.TCPConn); ok { tcpConn.SetKeepAlive(true) tcpConn.SetKeepAlivePeriod(30 * time.Second) } colonPos := strings.LastIndex(addr, ":") if colonPos == -1 { colonPos = len(addr) } hostname := addr[:colonPos] // If no ServerName is set, infer the ServerName // from the hostname we're connecting to. if config.ServerName == "" { // Make a copy to avoid polluting argument or default. config = tlsconfig.Clone(config) config.ServerName = hostname } conn := tls.Client(rawConn, config) if timeout == 0 { err = conn.Handshake() } else { go func() { errChannel <- conn.Handshake() }() err = <-errChannel } if err != nil { rawConn.Close() return nil, err } // This is Docker difference with standard's crypto/tls package: returned a // wrapper which holds both the TLS and raw connections. return &tlsClientCon{conn, rawConn}, nil } func dial(proto, addr string, tlsConfig *tls.Config) (net.Conn, error) { if tlsConfig != nil && proto != "unix" && proto != "npipe" { // Notice this isn't Go standard's tls.Dial function return tlsDial(proto, addr, tlsConfig) } if proto == "npipe" { return sockets.DialPipe(addr, 32*time.Second) } return net.Dial(proto, addr) } func (cli *Client) setupHijackConn(req *http.Request, proto string) (net.Conn, error) { req.Host = cli.addr req.Header.Set("Connection", "Upgrade") req.Header.Set("Upgrade", proto) conn, err := dial(cli.proto, cli.addr, resolveTLSConfig(cli.client.Transport)) if err != nil { return nil, errors.Wrap(err, "cannot connect to the Docker daemon. Is 'docker daemon' running on this host?") } // When we set up a TCP connection for hijack, there could be long periods // of inactivity (a long running command with no output) that in certain // network setups may cause ECONNTIMEOUT, leaving the client in an unknown // state. Setting TCP KeepAlive on the socket connection will prohibit // ECONNTIMEOUT unless the socket connection truly is broken if tcpConn, ok := conn.(*net.TCPConn); ok { tcpConn.SetKeepAlive(true) tcpConn.SetKeepAlivePeriod(30 * time.Second) } clientconn := httputil.NewClientConn(conn, nil) defer clientconn.Close() // Server hijacks the connection, error 'connection closed' expected resp, err := clientconn.Do(req) if err != httputil.ErrPersistEOF { if err != nil { return nil, err } if resp.StatusCode != http.StatusSwitchingProtocols { resp.Body.Close() return nil, fmt.Errorf("unable to upgrade to %s, received %d", proto, resp.StatusCode) } } c, br := clientconn.Hijack() if br.Buffered() > 0 { // If there is buffered content, wrap the connection c = &hijackedConn{c, br} } else { br.Reset(nil) } return c, nil } type hijackedConn struct { net.Conn r *bufio.Reader } func (c *hijackedConn) Read(b []byte) (int, error) { return c.r.Read(b) }
aleksandra-malinowska/autoscaler
vertical-pod-autoscaler/vendor/github.com/docker/docker/client/hijack.go
GO
apache-2.0
5,955
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Filter; use Traversable; class StringToUpper extends AbstractUnicode { /** * @var array */ protected $options = array( 'encoding' => null, ); /** * Constructor * * @param string|array|Traversable $encodingOrOptions OPTIONAL */ public function __construct($encodingOrOptions = null) { if ($encodingOrOptions !== null) { if (!static::isOptions($encodingOrOptions)) { $this->setEncoding($encodingOrOptions); } else { $this->setOptions($encodingOrOptions); } } } /** * Defined by Zend\Filter\FilterInterface * * Returns the string $value, converting characters to uppercase as necessary * * If the value provided is non-scalar, the value will remain unfiltered * * @param string $value * @return string|mixed */ public function filter($value) { if (!is_scalar($value)) { return $value; } $value = (string) $value; if ($this->options['encoding'] !== null) { return mb_strtoupper($value, $this->options['encoding']); } return strtoupper($value); } }
JorikVartanov/zf2
zf2_project/vendor/zendframework/zendframework/library/Zend/Filter/StringToUpper.php
PHP
bsd-3-clause
1,560
<?php /** * @package Joomla.Site * @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; jimport('joomla.application.categories'); /** * Build the route for the com_contact component * * @param array An array of URL arguments * * @return array The URL arguments to use to assemble the subsequent URL. */ function ContactBuildRoute(&$query){ $segments = array(); // get a menu item based on Itemid or currently active $app = JFactory::getApplication(); $menu = $app->getMenu(); $params = JComponentHelper::getParams('com_contact'); $advanced = $params->get('sef_advanced_link', 0); if (empty($query['Itemid'])) { $menuItem = $menu->getActive(); } else { $menuItem = $menu->getItem($query['Itemid']); } $mView = (empty($menuItem->query['view'])) ? null : $menuItem->query['view']; $mCatid = (empty($menuItem->query['catid'])) ? null : $menuItem->query['catid']; $mId = (empty($menuItem->query['id'])) ? null : $menuItem->query['id']; if (isset($query['view'])) { $view = $query['view']; if (empty($query['Itemid'])) { $segments[] = $query['view']; } unset($query['view']); }; // are we dealing with a contact that is attached to a menu item? if (isset($view) && ($mView == $view) and (isset($query['id'])) and ($mId == intval($query['id']))) { unset($query['view']); unset($query['catid']); unset($query['id']); return $segments; } if (isset($view) and ($view == 'category' or $view == 'contact')) { if ($mId != intval($query['id']) || $mView != $view) { if($view == 'contact' && isset($query['catid'])) { $catid = $query['catid']; } elseif(isset($query['id'])) { $catid = $query['id']; } $menuCatid = $mId; $categories = JCategories::getInstance('Contact'); $category = $categories->get($catid); if($category) { //TODO Throw error that the category either not exists or is unpublished $path = array_reverse($category->getPath()); $array = array(); foreach($path as $id) { if((int) $id == (int)$menuCatid) { break; } if($advanced) { list($tmp, $id) = explode(':', $id, 2); } $array[] = $id; } $segments = array_merge($segments, array_reverse($array)); } if($view == 'contact') { if($advanced) { list($tmp, $id) = explode(':', $query['id'], 2); } else { $id = $query['id']; } $segments[] = $id; } } unset($query['id']); unset($query['catid']); } if (isset($query['layout'])) { if (!empty($query['Itemid']) && isset($menuItem->query['layout'])) { if ($query['layout'] == $menuItem->query['layout']) { unset($query['layout']); } } else { if ($query['layout'] == 'default') { unset($query['layout']); } } }; return $segments; } /** * Parse the segments of a URL. * * @param array The segments of the URL to parse. * * @return array The URL attributes to be used by the application. */ function ContactParseRoute($segments) { $vars = array(); //Get the active menu item. $app = JFactory::getApplication(); $menu = $app->getMenu(); $item = $menu->getActive(); $params = JComponentHelper::getParams('com_contact'); $advanced = $params->get('sef_advanced_link', 0); // Count route segments $count = count($segments); // Standard routing for newsfeeds. if (!isset($item)) { $vars['view'] = $segments[0]; $vars['id'] = $segments[$count - 1]; return $vars; } // From the categories view, we can only jump to a category. $id = (isset($item->query['id']) && $item->query['id'] > 1) ? $item->query['id'] : 'root'; $contactCategory = JCategories::getInstance('Contact')->get($id); $categories = ($contactCategory) ? $contactCategory->getChildren() : array(); $vars['catid'] = $id; $vars['id'] = $id; $found = 0; foreach($segments as $segment) { $segment = $advanced ? str_replace(':', '-', $segment) : $segment; foreach($categories as $category) { if ($category->slug == $segment || $category->alias == $segment) { $vars['id'] = $category->id; $vars['catid'] = $category->id; $vars['view'] = 'category'; $categories = $category->getChildren(); $found = 1; break; } } if ($found == 0) { if($advanced) { $db = JFactory::getDBO(); $query = 'SELECT id FROM #__contact_details WHERE catid = '.$vars['catid'].' AND alias = '.$db->Quote($segment); $db->setQuery($query); $nid = $db->loadResult(); } else { $nid = $segment; } $vars['id'] = $nid; $vars['view'] = 'contact'; } $found = 0; } return $vars; }
baxri/cvote
tmp/install_54bd2998c811f/components/com_contact/router.php
PHP
gpl-2.0
4,706
var vows = require("vows"), _ = require("../../"), load = require("../load"), assert = require("../assert"); var suite = vows.describe("d3.max"); suite.addBatch({ "max": { topic: load("arrays/max").expression("d3.max"), "returns the greatest numeric value for numbers": function(max) { assert.equal(max([1]), 1); assert.equal(max([5, 1, 2, 3, 4]), 5); assert.equal(max([20, 3]), 20); assert.equal(max([3, 20]), 20); }, "returns the greatest lexicographic value for strings": function(max) { assert.equal(max(["c", "a", "b"]), "c"); assert.equal(max(["20", "3"]), "3"); assert.equal(max(["3", "20"]), "3"); }, "ignores null, undefined and NaN": function(max) { var o = {valueOf: function() { return NaN; }}; assert.equal(max([NaN, 1, 2, 3, 4, 5]), 5); assert.equal(max([o, 1, 2, 3, 4, 5]), 5); assert.equal(max([1, 2, 3, 4, 5, NaN]), 5); assert.equal(max([1, 2, 3, 4, 5, o]), 5); assert.equal(max([10, null, 3, undefined, 5, NaN]), 10); assert.equal(max([-1, null, -3, undefined, -5, NaN]), -1); }, "compares heterogenous types as numbers": function(max) { assert.strictEqual(max([20, "3"]), 20); assert.strictEqual(max(["20", 3]), "20"); assert.strictEqual(max([3, "20"]), "20"); assert.strictEqual(max(["3", 20]), 20); }, "returns undefined for empty array": function(max) { assert.isUndefined(max([])); assert.isUndefined(max([null])); assert.isUndefined(max([undefined])); assert.isUndefined(max([NaN])); assert.isUndefined(max([NaN, NaN])); }, "applies the optional accessor function": function(max) { assert.equal(max([[1, 2, 3, 4, 5], [2, 4, 6, 8, 10]], function(d) { return _.min(d); }), 2); assert.equal(max([1, 2, 3, 4, 5], function(d, i) { return i; }), 4); } } }); suite.export(module);
MoonApps/barelyalive
www/js/vendor/d3-master/test/arrays/max-test.js
JavaScript
gpl-2.0
1,919
require "openssl" module ActiveMerchant #:nodoc: module Billing #:nodoc: module Integrations #:nodoc: module Dwolla module Common def verify_signature(checkoutId, amount, notification_signature, secret) if secret.nil? raise ArgumentError, "You need to provide the Application secret as the option :credential3 to verify that the notification originated from Dwolla" end expected_signature = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA1.new, secret, "%s&%.2f" % [checkoutId, amount]) if notification_signature != expected_signature raise StandardError, "Dwolla signature verification failed." end end end end end end end
jinutm/silvfinal
vendor/bundle/ruby/2.1.0/gems/activemerchant-1.42.4/lib/active_merchant/billing/integrations/dwolla/common.rb
Ruby
mit
772
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.analysis; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.payloads.*; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.assistedinject.Assisted; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.env.Environment; import org.elasticsearch.index.Index; import org.elasticsearch.index.settings.IndexSettings; /** * */ public class DelimitedPayloadTokenFilterFactory extends AbstractTokenFilterFactory { public static final char DEFAULT_DELIMITER = '|'; public static final PayloadEncoder DEFAULT_ENCODER = new FloatEncoder(); static final String ENCODING = "encoding"; static final String DELIMITER = "delimiter"; char delimiter; PayloadEncoder encoder; @Inject public DelimitedPayloadTokenFilterFactory(Index index, @IndexSettings Settings indexSettings, Environment env, @Assisted String name, @Assisted Settings settings) { super(index, indexSettings, name, settings); String delimiterConf = settings.get(DELIMITER); if (delimiterConf != null) { delimiter = delimiterConf.charAt(0); } else { delimiter = DEFAULT_DELIMITER; } if (settings.get(ENCODING) != null) { if (settings.get(ENCODING).equals("float")) { encoder = new FloatEncoder(); } else if (settings.get(ENCODING).equals("int")) { encoder = new IntegerEncoder(); } else if (settings.get(ENCODING).equals("identity")) { encoder = new IdentityEncoder(); } } else { encoder = DEFAULT_ENCODER; } } @Override public TokenStream create(TokenStream tokenStream) { DelimitedPayloadTokenFilter filter = new DelimitedPayloadTokenFilter(tokenStream, delimiter, encoder); return filter; } }
mkis-/elasticsearch
src/main/java/org/elasticsearch/index/analysis/DelimitedPayloadTokenFilterFactory.java
Java
apache-2.0
2,762
var name; switch (name) { case "Kamol": doSomething(); default: doSomethingElse(); } switch (name) { default: doSomethingElse(); break; case "Kamol": doSomething(); }
bryantaylor/Epic
wp-content/themes/epic/node_modules/grunt-contrib-jshint/node_modules/jshint/tests/stable/unit/fixtures/switchDefaultFirst.js
JavaScript
gpl-2.0
173
require "language/java" class JavaRequirement < Requirement fatal true cask "java" download "http://www.oracle.com/technetwork/java/javase/downloads/index.html" satisfy :build_env => false do args = %w[--failfast] args << "--version" << "#{@version}" if @version @java_home = Utils.popen_read("/usr/libexec/java_home", *args).chomp $?.success? end env do java_home = Pathname.new(@java_home) ENV["JAVA_HOME"] = java_home ENV.prepend_path "PATH", java_home/"bin" if (java_home/"include").exist? # Oracle JVM ENV.append_to_cflags "-I#{java_home}/include" ENV.append_to_cflags "-I#{java_home}/include/darwin" else # Apple JVM ENV.append_to_cflags "-I/System/Library/Frameworks/JavaVM.framework/Versions/Current/Headers/" end end def initialize(tags) @version = tags.shift if /(\d\.)+\d/ === tags.first super end def message version_string = " #{@version}" if @version s = "Java#{version_string} is required to install this formula." s += super s end def inspect "#<#{self.class.name}: #{name.inspect} #{tags.inspect} version=#{@version.inspect}>" end end
rokn/Count_Words_2015
fetched_code/ruby/java_requirement.rb
Ruby
mit
1,171
// { dg-do assemble } // Copyright (C) 2000 Free Software Foundation // by Alexandre Oliva <aoliva@cygnus.com> // distilled from libg++'s Fix.cc struct Integer { ~Integer () {} }; void foo (const Integer& y); Integer bar (const Integer& x); void show (const Integer& x) { foo (bar (x)); }
SanDisk-Open-Source/SSD_Dashboard
uefi/gcc/gcc-4.6.3/gcc/testsuite/g++.old-deja/g++.oliva/stkalign.C
C++
gpl-2.0
299
// { dg-do assemble } // GROUPS passed patches // patches file // From: david.binderman@pmsr.philips.co.uk // Date: Wed, 6 Oct 93 17:05:54 BST // Subject: Reno 1.2 bug fix // Message-ID: <9310061605.AA04160@pmsr.philips.co.uk> int type(float) { return 1; } int type(double) { return 2; } int type(long double) { return 3; } extern "C" int printf( const char *, ...); int main() { int i = 0; if (type(0.0) != 2) ++i; if (i > 0) { printf ("FAIL\n"); return 1; } else printf ("PASS\n"); }
SanDisk-Open-Source/SSD_Dashboard
uefi/gcc/gcc-4.6.3/gcc/testsuite/g++.old-deja/g++.law/patches1.C
C++
gpl-2.0
546
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * This file contains the class for restore of this submission plugin * * @package assignsubmission_file * @copyright 2012 NetSpot {@link http://www.netspot.com.au} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ /** * Restore subplugin class. * * Provides the necessary information * needed to restore one assign_submission subplugin. * * @package assignsubmission_file * @copyright 2012 NetSpot {@link http://www.netspot.com.au} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class restore_assignsubmission_file_subplugin extends restore_subplugin { /** * Returns the paths to be handled by the subplugin at workshop level * @return array */ protected function define_submission_subplugin_structure() { $paths = array(); $elename = $this->get_namefor('submission'); $elepath = $this->get_pathfor('/submission_file'); // We used get_recommended_name() so this works. $paths[] = new restore_path_element($elename, $elepath); return $paths; } /** * Processes one submission_file element * @param mixed $data * @return void */ public function process_assignsubmission_file_submission($data) { global $DB; $data = (object)$data; $data->assignment = $this->get_new_parentid('assign'); $oldsubmissionid = $data->submission; // The mapping is set in the restore for the core assign activity // when a submission node is processed. $data->submission = $this->get_mappingid('submission', $data->submission); $DB->insert_record('assignsubmission_file', $data); $this->add_related_files('assignsubmission_file', 'submission_files', 'submission', null, $oldsubmissionid); } }
ernestovi/ups
moodle/mod/assign/submission/file/backup/moodle2/restore_assignsubmission_file_subplugin.class.php
PHP
gpl-3.0
2,645
<?php /* * This file is part of the Assetic package, an OpenSky project. * * (c) 2010-2013 OpenSky Project Inc * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Assetic\Factory\Resource; /** * A resource is something formulae can be loaded from. * * @author Kris Wallsmith <kris.wallsmith@gmail.com> */ interface IteratorResourceInterface extends ResourceInterface, \IteratorAggregate { }
nickopris/musicapp
www/core/vendor/kriswallsmith/assetic/src/Assetic/Factory/Resource/IteratorResourceInterface.php
PHP
apache-2.0
493
// Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "db/log_writer.h" #include <stdint.h> #include "leveldb/env.h" #include "util/coding.h" #include "util/crc32c.h" namespace leveldb { namespace log { Writer::Writer(WritableFile* dest) : dest_(dest), block_offset_(0) { for (int i = 0; i <= kMaxRecordType; i++) { char t = static_cast<char>(i); type_crc_[i] = crc32c::Value(&t, 1); } } Writer::~Writer() { } Status Writer::AddRecord(const Slice& slice) { const char* ptr = slice.data(); size_t left = slice.size(); // Fragment the record if necessary and emit it. Note that if slice // is empty, we still want to iterate once to emit a single // zero-length record Status s; bool begin = true; do { const int leftover = kBlockSize - block_offset_; assert(leftover >= 0); if (leftover < kHeaderSize) { // Switch to a new block if (leftover > 0) { // Fill the trailer (literal below relies on kHeaderSize being 7) assert(kHeaderSize == 7); dest_->Append(Slice("\x00\x00\x00\x00\x00\x00", leftover)); } block_offset_ = 0; } // Invariant: we never leave < kHeaderSize bytes in a block. assert(kBlockSize - block_offset_ - kHeaderSize >= 0); const size_t avail = kBlockSize - block_offset_ - kHeaderSize; const size_t fragment_length = (left < avail) ? left : avail; RecordType type; const bool end = (left == fragment_length); if (begin && end) { type = kFullType; } else if (begin) { type = kFirstType; } else if (end) { type = kLastType; } else { type = kMiddleType; } s = EmitPhysicalRecord(type, ptr, fragment_length); ptr += fragment_length; left -= fragment_length; begin = false; } while (s.ok() && left > 0); return s; } Status Writer::EmitPhysicalRecord(RecordType t, const char* ptr, size_t n) { assert(n <= 0xffff); // Must fit in two bytes assert(block_offset_ + kHeaderSize + n <= kBlockSize); // Format the header char buf[kHeaderSize]; buf[4] = static_cast<char>(n & 0xff); buf[5] = static_cast<char>(n >> 8); buf[6] = static_cast<char>(t); // Compute the crc of the record type and the payload. uint32_t crc = crc32c::Extend(type_crc_[t], ptr, n); crc = crc32c::Mask(crc); // Adjust for storage EncodeFixed32(buf, crc); // Write the header and the payload Status s = dest_->Append(Slice(buf, kHeaderSize)); if (s.ok()) { s = dest_->Append(Slice(ptr, n)); if (s.ok()) { s = dest_->Flush(); } } block_offset_ += kHeaderSize + n; return s; } } // namespace log } // namespace leveldb
february29/Learning
web/vue/AccountBook-Express/node_modules/.staging/leveldown-d5bd0bf6/deps/leveldb/leveldb-1.18.0/db/log_writer.cc
C++
mit
2,844
import { addFormatToken } from '../format/format'; import { addUnitAlias } from './aliases'; import { addUnitPriority } from './priorities'; import { addRegexToken, match1to2, matchWord, regexEscape } from '../parse/regex'; import { addWeekParseToken } from '../parse/token'; import toInt from '../utils/to-int'; import isArray from '../utils/is-array'; import indexOf from '../utils/index-of'; import hasOwnProp from '../utils/has-own-prop'; import { createUTC } from '../create/utc'; import getParsingFlags from '../create/parsing-flags'; // FORMATTING addFormatToken('d', 0, 'do', 'day'); addFormatToken('dd', 0, 0, function (format) { return this.localeData().weekdaysMin(this, format); }); addFormatToken('ddd', 0, 0, function (format) { return this.localeData().weekdaysShort(this, format); }); addFormatToken('dddd', 0, 0, function (format) { return this.localeData().weekdays(this, format); }); addFormatToken('e', 0, 0, 'weekday'); addFormatToken('E', 0, 0, 'isoWeekday'); // ALIASES addUnitAlias('day', 'd'); addUnitAlias('weekday', 'e'); addUnitAlias('isoWeekday', 'E'); // PRIORITY addUnitPriority('day', 11); addUnitPriority('weekday', 11); addUnitPriority('isoWeekday', 11); // PARSING addRegexToken('d', match1to2); addRegexToken('e', match1to2); addRegexToken('E', match1to2); addRegexToken('dd', function (isStrict, locale) { return locale.weekdaysMinRegex(isStrict); }); addRegexToken('ddd', function (isStrict, locale) { return locale.weekdaysShortRegex(isStrict); }); addRegexToken('dddd', function (isStrict, locale) { return locale.weekdaysRegex(isStrict); }); addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) { var weekday = config._locale.weekdaysParse(input, token, config._strict); // if we didn't get a weekday name, mark the date as invalid if (weekday != null) { week.d = weekday; } else { getParsingFlags(config).invalidWeekday = input; } }); addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) { week[token] = toInt(input); }); // HELPERS function parseWeekday(input, locale) { if (typeof input !== 'string') { return input; } if (!isNaN(input)) { return parseInt(input, 10); } input = locale.weekdaysParse(input); if (typeof input === 'number') { return input; } return null; } function parseIsoWeekday(input, locale) { if (typeof input === 'string') { return locale.weekdaysParse(input) % 7 || 7; } return isNaN(input) ? null : input; } // LOCALES export var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'); export function localeWeekdays (m, format) { return isArray(this._weekdays) ? this._weekdays[m.day()] : this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()]; } export var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'); export function localeWeekdaysShort (m) { return this._weekdaysShort[m.day()]; } export var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'); export function localeWeekdaysMin (m) { return this._weekdaysMin[m.day()]; } function handleStrictParse(weekdayName, format, strict) { var i, ii, mom, llc = weekdayName.toLocaleLowerCase(); if (!this._weekdaysParse) { this._weekdaysParse = []; this._shortWeekdaysParse = []; this._minWeekdaysParse = []; for (i = 0; i < 7; ++i) { mom = createUTC([2000, 1]).day(i); this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase(); this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase(); this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase(); } } if (strict) { if (format === 'dddd') { ii = indexOf.call(this._weekdaysParse, llc); return ii !== -1 ? ii : null; } else if (format === 'ddd') { ii = indexOf.call(this._shortWeekdaysParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } } else { if (format === 'dddd') { ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._shortWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } else if (format === 'ddd') { ii = indexOf.call(this._shortWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._minWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._shortWeekdaysParse, llc); return ii !== -1 ? ii : null; } } } export function localeWeekdaysParse (weekdayName, format, strict) { var i, mom, regex; if (this._weekdaysParseExact) { return handleStrictParse.call(this, weekdayName, format, strict); } if (!this._weekdaysParse) { this._weekdaysParse = []; this._minWeekdaysParse = []; this._shortWeekdaysParse = []; this._fullWeekdaysParse = []; } for (i = 0; i < 7; i++) { // make the regex if we don't have it already mom = createUTC([2000, 1]).day(i); if (strict && !this._fullWeekdaysParse[i]) { this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\.?') + '$', 'i'); this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\.?') + '$', 'i'); this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\.?') + '$', 'i'); } if (!this._weekdaysParse[i]) { regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) { return i; } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) { return i; } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) { return i; } else if (!strict && this._weekdaysParse[i].test(weekdayName)) { return i; } } } // MOMENTS export function getSetDayOfWeek (input) { if (!this.isValid()) { return input != null ? this : NaN; } var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); if (input != null) { input = parseWeekday(input, this.localeData()); return this.add(input - day, 'd'); } else { return day; } } export function getSetLocaleDayOfWeek (input) { if (!this.isValid()) { return input != null ? this : NaN; } var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; return input == null ? weekday : this.add(input - weekday, 'd'); } export function getSetISODayOfWeek (input) { if (!this.isValid()) { return input != null ? this : NaN; } // behaves the same as moment#day except // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) // as a setter, sunday should belong to the previous week. if (input != null) { var weekday = parseIsoWeekday(input, this.localeData()); return this.day(this.day() % 7 ? weekday : weekday - 7); } else { return this.day() || 7; } } var defaultWeekdaysRegex = matchWord; export function weekdaysRegex (isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, '_weekdaysRegex')) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysStrictRegex; } else { return this._weekdaysRegex; } } else { if (!hasOwnProp(this, '_weekdaysRegex')) { this._weekdaysRegex = defaultWeekdaysRegex; } return this._weekdaysStrictRegex && isStrict ? this._weekdaysStrictRegex : this._weekdaysRegex; } } var defaultWeekdaysShortRegex = matchWord; export function weekdaysShortRegex (isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, '_weekdaysRegex')) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysShortStrictRegex; } else { return this._weekdaysShortRegex; } } else { if (!hasOwnProp(this, '_weekdaysShortRegex')) { this._weekdaysShortRegex = defaultWeekdaysShortRegex; } return this._weekdaysShortStrictRegex && isStrict ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex; } } var defaultWeekdaysMinRegex = matchWord; export function weekdaysMinRegex (isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, '_weekdaysRegex')) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysMinStrictRegex; } else { return this._weekdaysMinRegex; } } else { if (!hasOwnProp(this, '_weekdaysMinRegex')) { this._weekdaysMinRegex = defaultWeekdaysMinRegex; } return this._weekdaysMinStrictRegex && isStrict ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex; } } function computeWeekdaysParse () { function cmpLenRev(a, b) { return b.length - a.length; } var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [], i, mom, minp, shortp, longp; for (i = 0; i < 7; i++) { // make the regex if we don't have it already mom = createUTC([2000, 1]).day(i); minp = this.weekdaysMin(mom, ''); shortp = this.weekdaysShort(mom, ''); longp = this.weekdays(mom, ''); minPieces.push(minp); shortPieces.push(shortp); longPieces.push(longp); mixedPieces.push(minp); mixedPieces.push(shortp); mixedPieces.push(longp); } // Sorting makes sure if one weekday (or abbr) is a prefix of another it // will match the longer piece. minPieces.sort(cmpLenRev); shortPieces.sort(cmpLenRev); longPieces.sort(cmpLenRev); mixedPieces.sort(cmpLenRev); for (i = 0; i < 7; i++) { shortPieces[i] = regexEscape(shortPieces[i]); longPieces[i] = regexEscape(longPieces[i]); mixedPieces[i] = regexEscape(mixedPieces[i]); } this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); this._weekdaysShortRegex = this._weekdaysRegex; this._weekdaysMinRegex = this._weekdaysRegex; this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i'); this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i'); this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i'); }
Nucleo-235/roupa-livre-ionic
www/lib/moment/src/lib/units/day-of-week.js
JavaScript
gpl-3.0
11,793
//! moment.js locale configuration //! locale : Chinese (Hong Kong) [zh-hk] //! author : Ben : https://github.com/ben-lin //! author : Chris Lam : https://github.com/hehachris //! author : Konstantin : https://github.com/skfd ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../moment')) : typeof define === 'function' && define.amd ? define(['../moment'], factory) : factory(global.moment) }(this, (function (moment) { 'use strict'; var zhHk = moment.defineLocale('zh-hk', { months : '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'), monthsShort : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), weekdays : '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'), weekdaysShort : '週日_週一_週二_週三_週四_週五_週六'.split('_'), weekdaysMin : '日_一_二_三_四_五_六'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'YYYY年MMMD日', LL : 'YYYY年MMMD日', LLL : 'YYYY年MMMD日 HH:mm', LLLL : 'YYYY年MMMD日dddd HH:mm', l : 'YYYY年MMMD日', ll : 'YYYY年MMMD日', lll : 'YYYY年MMMD日 HH:mm', llll : 'YYYY年MMMD日dddd HH:mm' }, meridiemParse: /凌晨|早上|上午|中午|下午|晚上/, meridiemHour : function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === '凌晨' || meridiem === '早上' || meridiem === '上午') { return hour; } else if (meridiem === '中午') { return hour >= 11 ? hour : hour + 12; } else if (meridiem === '下午' || meridiem === '晚上') { return hour + 12; } }, meridiem : function (hour, minute, isLower) { var hm = hour * 100 + minute; if (hm < 600) { return '凌晨'; } else if (hm < 900) { return '早上'; } else if (hm < 1130) { return '上午'; } else if (hm < 1230) { return '中午'; } else if (hm < 1800) { return '下午'; } else { return '晚上'; } }, calendar : { sameDay : '[今天]LT', nextDay : '[明天]LT', nextWeek : '[下]ddddLT', lastDay : '[昨天]LT', lastWeek : '[上]ddddLT', sameElse : 'L' }, dayOfMonthOrdinalParse: /\d{1,2}(日|月|週)/, ordinal : function (number, period) { switch (period) { case 'd' : case 'D' : case 'DDD' : return number + '日'; case 'M' : return number + '月'; case 'w' : case 'W' : return number + '週'; default : return number; } }, relativeTime : { future : '%s內', past : '%s前', s : '幾秒', m : '1 分鐘', mm : '%d 分鐘', h : '1 小時', hh : '%d 小時', d : '1 天', dd : '%d 天', M : '1 個月', MM : '%d 個月', y : '1 年', yy : '%d 年' } }); return zhHk; })));
stevemoore113/ch_web_-
資源/CCEI/handsontable/dist/moment/locale/zh-hk.js
JavaScript
mit
3,363
var assert = require('assert'); var cookie = require('..'); suite('parse'); test('basic', function() { assert.deepEqual({ foo: 'bar' }, cookie.parse('foo=bar')); assert.deepEqual({ foo: '123' }, cookie.parse('foo=123')); }); test('ignore spaces', function() { assert.deepEqual({ FOO: 'bar', baz: 'raz' }, cookie.parse('FOO = bar; baz = raz')); }); test('escaping', function() { assert.deepEqual({ foo: 'bar=123456789&name=Magic+Mouse' }, cookie.parse('foo="bar=123456789&name=Magic+Mouse"')); assert.deepEqual({ email: ' ",;/' }, cookie.parse('email=%20%22%2c%3b%2f')); }); test('ignore escaping error and return original value', function() { assert.deepEqual({ foo: '%1', bar: 'bar' }, cookie.parse('foo=%1;bar=bar')); });
BrowenChen/classroomDashboard
zzishwebsite/node_modules/express/node_modules/connect/node_modules/cookie/test/parse.js
JavaScript
mit
800
package reflectwalk //go:generate stringer -type=Location location.go type Location uint const ( None Location = iota Map MapKey MapValue Slice SliceElem Struct StructField WalkLoc )
bakins/terraform-provider-etcd
vendor/src/github.com/mitchellh/reflectwalk/location.go
GO
mpl-2.0
195
<?php /* * $Id: TarTask.php 220 2007-08-21 00:03:13Z hans $ * * 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 THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information please see * <http://phing.info>. */ require_once 'phing/tasks/system/MatchingTask.php'; include_once 'phing/util/SourceFileScanner.php'; include_once 'phing/mappers/MergeMapper.php'; include_once 'phing/util/StringHelper.php'; /** * Creates a tar archive using PEAR Archive_Tar. * * @author Hans Lellelid <hans@xmpl.org> (Phing) * @author Stefano Mazzocchi <stefano@apache.org> (Ant) * @author Stefan Bodewig <stefan.bodewig@epost.de> (Ant) * @author Magesh Umasankar * @version $Revision: 1.10 $ * @package phing.tasks.ext */ class TarTask extends MatchingTask { const TAR_NAMELEN = 100; const WARN = "warn"; const FAIL = "fail"; const OMIT = "omit"; private $tarFile; private $baseDir; private $includeEmpty = true; // Whether to include empty dirs in the TAR private $longFileMode = "warn"; private $filesets = array(); private $fileSetFiles = array(); /** * Indicates whether the user has been warned about long files already. */ private $longWarningGiven = false; /** * Compression mode. Available options "gzip", "bzip2", "none" (null). */ private $compression = null; /** * Ensures that PEAR lib exists. */ public function init() { include_once 'Archive/Tar.php'; if (!class_exists('Archive_Tar')) { throw new BuildException("You must have installed the PEAR Archive_Tar class in order to use TarTask."); } } /** * Add a new fileset * @return FileSet */ public function createTarFileSet() { $this->fileset = new TarFileSet(); $this->filesets[] = $this->fileset; return $this->fileset; } /** * Add a new fileset. Alias to createTarFileSet() for backwards compatibility. * @return FileSet * @see createTarFileSet() */ public function createFileSet() { $this->fileset = new TarFileSet(); $this->filesets[] = $this->fileset; return $this->fileset; } /** * Set is the name/location of where to create the tar file. * @param PhingFile $destFile The output of the tar */ public function setDestFile(PhingFile $destFile) { $this->tarFile = $destFile; } /** * This is the base directory to look in for things to tar. * @param PhingFile $baseDir */ public function setBasedir(PhingFile $baseDir) { $this->baseDir = $baseDir; } /** * Set the include empty dirs flag. * @param boolean Flag if empty dirs should be tarred too * @return void * @access public */ function setIncludeEmptyDirs($bool) { $this->includeEmpty = (boolean) $bool; } /** * Set how to handle long files, those with a path&gt;100 chars. * Optional, default=warn. * <p> * Allowable values are * <ul> * <li> truncate - paths are truncated to the maximum length * <li> fail - paths greater than the maximim cause a build exception * <li> warn - paths greater than the maximum cause a warning and GNU is used * <li> gnu - GNU extensions are used for any paths greater than the maximum. * <li> omit - paths greater than the maximum are omitted from the archive * </ul> */ public function setLongfile($mode) { $this->longFileMode = $mode; } /** * Set compression method. * Allowable values are * <ul> * <li> none - no compression * <li> gzip - Gzip compression * <li> bzip2 - Bzip2 compression * </ul> */ public function setCompression($mode) { switch($mode) { case "gzip": $this->compression = "gz"; break; case "bzip2": $this->compression = "bz2"; break; case "none": $this->compression = null; break; default: $this->log("Ignoring unknown compression mode: ".$mode, Project::MSG_WARN); $this->compression = null; } } /** * do the work * @throws BuildException */ public function main() { if ($this->tarFile === null) { throw new BuildException("tarfile attribute must be set!", $this->getLocation()); } if ($this->tarFile->exists() && $this->tarFile->isDirectory()) { throw new BuildException("tarfile is a directory!", $this->getLocation()); } if ($this->tarFile->exists() && !$this->tarFile->canWrite()) { throw new BuildException("Can not write to the specified tarfile!", $this->getLocation()); } // shouldn't need to clone, since the entries in filesets // themselves won't be modified -- only elements will be added $savedFileSets = $this->filesets; try { if ($this->baseDir !== null) { if (!$this->baseDir->exists()) { throw new BuildException("basedir does not exist!", $this->getLocation()); } if (empty($this->filesets)) { // if there weren't any explicit filesets specivied, then // create a default, all-inclusive fileset using the specified basedir. $mainFileSet = new TarFileSet($this->fileset); $mainFileSet->setDir($this->baseDir); $this->filesets[] = $mainFileSet; } } if (empty($this->filesets)) { throw new BuildException("You must supply either a basedir " . "attribute or some nested filesets.", $this->getLocation()); } // check if tar is out of date with respect to each fileset if($this->tarFile->exists()) { $upToDate = true; foreach($this->filesets as $fs) { $files = $fs->getFiles($this->project, $this->includeEmpty); if (!$this->archiveIsUpToDate($files, $fs->getDir($this->project))) { $upToDate = false; } for ($i=0, $fcount=count($files); $i < $fcount; $i++) { if ($this->tarFile->equals(new PhingFile($fs->getDir($this->project), $files[$i]))) { throw new BuildException("A tar file cannot include itself", $this->getLocation()); } } } if ($upToDate) { $this->log("Nothing to do: " . $this->tarFile->__toString() . " is up to date.", Project::MSG_INFO); return; } } $this->log("Building tar: " . $this->tarFile->__toString(), Project::MSG_INFO); $tar = new Archive_Tar($this->tarFile->getAbsolutePath(), $this->compression); // print errors $tar->setErrorHandling(PEAR_ERROR_PRINT); foreach($this->filesets as $fs) { $files = $fs->getFiles($this->project, $this->includeEmpty); if (count($files) > 1 && strlen($fs->getFullpath()) > 0) { throw new BuildException("fullpath attribute may only " . "be specified for " . "filesets that specify a " . "single file."); } $fsBasedir = $fs->getDir($this->project); $filesToTar = array(); for ($i=0, $fcount=count($files); $i < $fcount; $i++) { $f = new PhingFile($fsBasedir, $files[$i]); $filesToTar[] = $f->getAbsolutePath(); $this->log("Adding file " . $f->getPath() . " to archive.", Project::MSG_VERBOSE); } $tar->addModify($filesToTar, '', $fsBasedir->getAbsolutePath()); } } catch (IOException $ioe) { $msg = "Problem creating TAR: " . $ioe->getMessage(); $this->filesets = $savedFileSets; throw new BuildException($msg, $ioe, $this->getLocation()); } $this->filesets = $savedFileSets; } /** * @param array $files array of filenames * @param PhingFile $dir * @return boolean */ protected function archiveIsUpToDate($files, $dir) { $sfs = new SourceFileScanner($this); $mm = new MergeMapper(); $mm->setTo($this->tarFile->getAbsolutePath()); return count($sfs->restrict($files, $dir, null, $mm)) == 0; } } /** * This is a FileSet with the option to specify permissions. * * Permissions are currently not implemented by PEAR Archive_Tar, * but hopefully they will be in the future. * */ class TarFileSet extends FileSet { private $files = null; private $mode = 0100644; private $userName = ""; private $groupName = ""; private $prefix = ""; private $fullpath = ""; private $preserveLeadingSlashes = false; /** * Get a list of files and directories specified in the fileset. * @return array a list of file and directory names, relative to * the baseDir for the project. */ public function getFiles(Project $p, $includeEmpty = true) { if ($this->files === null) { $ds = $this->getDirectoryScanner($p); $this->files = $ds->getIncludedFiles(); if ($includeEmpty) { // first any empty directories that will not be implicitly added by any of the files $implicitDirs = array(); foreach($this->files as $file) { $implicitDirs[] = dirname($file); } $incDirs = $ds->getIncludedDirectories(); // we'll need to add to that list of implicit dirs any directories // that contain other *directories* (and not files), since otherwise // we get duplicate directories in the resulting tar foreach($incDirs as $dir) { foreach($incDirs as $dircheck) { if (!empty($dir) && $dir == dirname($dircheck)) { $implicitDirs[] = $dir; } } } $implicitDirs = array_unique($implicitDirs); // Now add any empty dirs (dirs not covered by the implicit dirs) // to the files array. foreach($incDirs as $dir) { // we cannot simply use array_diff() since we want to disregard empty/. dirs if ($dir != "" && $dir != "." && !in_array($dir, $implicitDirs)) { // it's an empty dir, so we'll add it. $this->files[] = $dir; } } } // if $includeEmpty } // if ($this->files===null) return $this->files; } /** * A 3 digit octal string, specify the user, group and * other modes in the standard Unix fashion; * optional, default=0644 * @param string $octalString */ public function setMode($octalString) { $octal = (int) $octalString; $this->mode = 0100000 | $octal; } public function getMode() { return $this->mode; } /** * The username for the tar entry * This is not the same as the UID, which is * not currently set by the task. */ public function setUserName($userName) { $this->userName = $userName; } public function getUserName() { return $this->userName; } /** * The groupname for the tar entry; optional, default="" * This is not the same as the GID, which is * not currently set by the task. */ public function setGroup($groupName) { $this->groupName = $groupName; } public function getGroup() { return $this->groupName; } /** * If the prefix attribute is set, all files in the fileset * are prefixed with that path in the archive. * optional. */ public function setPrefix($prefix) { $this->prefix = $prefix; } public function getPrefix() { return $this->prefix; } /** * If the fullpath attribute is set, the file in the fileset * is written with that path in the archive. The prefix attribute, * if specified, is ignored. It is an error to have more than one file specified in * such a fileset. */ public function setFullpath($fullpath) { $this->fullpath = $fullpath; } public function getFullpath() { return $this->fullpath; } /** * Flag to indicates whether leading `/'s should * be preserved in the file names. * Optional, default is <code>false</code>. * @return void */ public function setPreserveLeadingSlashes($b) { $this->preserveLeadingSlashes = (boolean) $b; } public function getPreserveLeadingSlashes() { return $this->preserveLeadingSlashes; } }
voota/voota
www/lib/vendor/symfony/lib/plugins/sfPropelPlugin/lib/vendor/phing/tasks/ext/TarTask.php
PHP
mit
14,247
// Boost.Assign library // // Copyright Thorsten Ottosen 2003-2004. Use, modification and // distribution is subject to the Boost Software License, Version // 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // For more information, see http://www.boost.org/libs/assign/ // #ifndef BOOST_ASSIGN_STD_MAP_HPP #define BOOST_ASSIGN_STD_MAP_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif #include <boost/assign/list_inserter.hpp> #include <boost/config.hpp> #include <map> namespace boost { namespace assign { template< class K, class V, class C, class A, class P > inline list_inserter< assign_detail::call_insert< std::map<K,V,C,A> >, P > operator+=( std::map<K,V,C,A>& m, const P& p ) { return insert( m )( p ); } template< class K, class V, class C, class A, class P > inline list_inserter< assign_detail::call_insert< std::multimap<K,V,C,A> >, P > operator+=( std::multimap<K,V,C,A>& m, const P& p ) { return insert( m )( p ); } } } #endif
hpl1nk/nonamegame
xray/SDK/include/boost/assign/std/map.hpp
C++
gpl-3.0
1,085
/*============================================================================= Copyright (c) 2001 Doug Gregor Copyright (c) 1999-2003 Jaakko Jarvi Copyright (c) 2001-2011 Joel de Guzman Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(FUSION_IGNORE_07192005_0329) #define FUSION_IGNORE_07192005_0329 #include <boost/fusion/support/config.hpp> namespace boost { namespace fusion { // Swallows any assignment (by Doug Gregor) namespace detail { struct swallow_assign { template<typename T> BOOST_FUSION_CONSTEXPR_THIS BOOST_FUSION_GPU_ENABLED swallow_assign const& operator=(const T&) const { return *this; } }; } // "ignore" allows tuple positions to be ignored when using "tie". BOOST_CONSTEXPR_OR_CONST detail::swallow_assign ignore = detail::swallow_assign(); }} #endif
gwq5210/litlib
thirdparty/sources/boost_1_60_0/boost/fusion/container/generation/ignore.hpp
C++
gpl-3.0
1,129
<?php namespace Drupal\system\Controller; use Drupal\Core\Cache\CacheBackendInterface; use Drupal\Core\Controller\ControllerBase; use Drupal\Core\Extension\ModuleHandlerInterface; use Drupal\Core\KeyValueStore\KeyValueExpirableFactoryInterface; use Drupal\Core\Render\BareHtmlPageRendererInterface; use Drupal\Core\Session\AccountInterface; use Drupal\Core\Site\Settings; use Drupal\Core\State\StateInterface; use Drupal\Core\Update\UpdateRegistry; use Drupal\Core\Url; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Request; /** * Controller routines for database update routes. */ class DbUpdateController extends ControllerBase { /** * The keyvalue expirable factory. * * @var \Drupal\Core\KeyValueStore\KeyValueExpirableFactoryInterface */ protected $keyValueExpirableFactory; /** * A cache backend interface. * * @var \Drupal\Core\Cache\CacheBackendInterface */ protected $cache; /** * The state service. * * @var \Drupal\Core\State\StateInterface */ protected $state; /** * The module handler. * * @var \Drupal\Core\Extension\ModuleHandlerInterface */ protected $moduleHandler; /** * The current user. * * @var \Drupal\Core\Session\AccountInterface */ protected $account; /** * The bare HTML page renderer. * * @var \Drupal\Core\Render\BareHtmlPageRendererInterface */ protected $bareHtmlPageRenderer; /** * The app root. * * @var string */ protected $root; /** * The post update registry. * * @var \Drupal\Core\Update\UpdateRegistry */ protected $postUpdateRegistry; /** * Constructs a new UpdateController. * * @param string $root * The app root. * @param \Drupal\Core\KeyValueStore\KeyValueExpirableFactoryInterface $key_value_expirable_factory * The keyvalue expirable factory. * @param \Drupal\Core\Cache\CacheBackendInterface $cache * A cache backend interface. * @param \Drupal\Core\State\StateInterface $state * The state service. * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler * The module handler. * @param \Drupal\Core\Session\AccountInterface $account * The current user. * @param \Drupal\Core\Render\BareHtmlPageRendererInterface $bare_html_page_renderer * The bare HTML page renderer. * @param \Drupal\Core\Update\UpdateRegistry $post_update_registry * The post update registry. */ public function __construct($root, KeyValueExpirableFactoryInterface $key_value_expirable_factory, CacheBackendInterface $cache, StateInterface $state, ModuleHandlerInterface $module_handler, AccountInterface $account, BareHtmlPageRendererInterface $bare_html_page_renderer, UpdateRegistry $post_update_registry) { $this->root = $root; $this->keyValueExpirableFactory = $key_value_expirable_factory; $this->cache = $cache; $this->state = $state; $this->moduleHandler = $module_handler; $this->account = $account; $this->bareHtmlPageRenderer = $bare_html_page_renderer; $this->postUpdateRegistry = $post_update_registry; } /** * {@inheritdoc} */ public static function create(ContainerInterface $container) { return new static( $container->get('app.root'), $container->get('keyvalue.expirable'), $container->get('cache.default'), $container->get('state'), $container->get('module_handler'), $container->get('current_user'), $container->get('bare_html_page_renderer'), $container->get('update.post_update_registry') ); } /** * Returns a database update page. * * @param string $op * The update operation to perform. Can be any of the below: * - info * - selection * - run * - results * @param \Symfony\Component\HttpFoundation\Request $request * The current request object. * * @return \Symfony\Component\HttpFoundation\Response * A response object object. */ public function handle($op, Request $request) { require_once $this->root . '/core/includes/install.inc'; require_once $this->root . '/core/includes/update.inc'; drupal_load_updates(); update_fix_compatibility(); if ($request->query->get('continue')) { $_SESSION['update_ignore_warnings'] = TRUE; } $regions = array(); $requirements = update_check_requirements(); $severity = drupal_requirements_severity($requirements); if ($severity == REQUIREMENT_ERROR || ($severity == REQUIREMENT_WARNING && empty($_SESSION['update_ignore_warnings']))) { $regions['sidebar_first'] = $this->updateTasksList('requirements'); $output = $this->requirements($severity, $requirements, $request); } else { switch ($op) { case 'selection': $regions['sidebar_first'] = $this->updateTasksList('selection'); $output = $this->selection($request); break; case 'run': $regions['sidebar_first'] = $this->updateTasksList('run'); $output = $this->triggerBatch($request); break; case 'info': $regions['sidebar_first'] = $this->updateTasksList('info'); $output = $this->info($request); break; case 'results': $regions['sidebar_first'] = $this->updateTasksList('results'); $output = $this->results($request); break; // Regular batch ops : defer to batch processing API. default: require_once $this->root . '/core/includes/batch.inc'; $regions['sidebar_first'] = $this->updateTasksList('run'); $output = _batch_page($request); break; } } if ($output instanceof Response) { return $output; } $title = isset($output['#title']) ? $output['#title'] : $this->t('Drupal database update'); return $this->bareHtmlPageRenderer->renderBarePage($output, $title, 'maintenance_page', $regions); } /** * Returns the info database update page. * * @param \Symfony\Component\HttpFoundation\Request $request * The current request. * * @return array * A render array. */ protected function info(Request $request) { // Change query-strings on css/js files to enforce reload for all users. _drupal_flush_css_js(); // Flush the cache of all data for the update status module. $this->keyValueExpirableFactory->get('update')->deleteAll(); $this->keyValueExpirableFactory->get('update_available_release')->deleteAll(); $build['info_header'] = array( '#markup' => '<p>' . $this->t('Use this utility to update your database whenever a new release of Drupal or a module is installed.') . '</p><p>' . $this->t('For more detailed information, see the <a href="https://www.drupal.org/upgrade">upgrading handbook</a>. If you are unsure what these terms mean you should probably contact your hosting provider.') . '</p>', ); $info[] = $this->t("<strong>Back up your code</strong>. Hint: when backing up module code, do not leave that backup in the 'modules' or 'sites/*/modules' directories as this may confuse Drupal's auto-discovery mechanism."); $info[] = $this->t('Put your site into <a href=":url">maintenance mode</a>.', array( ':url' => Url::fromRoute('system.site_maintenance_mode')->toString(TRUE)->getGeneratedUrl(), )); $info[] = $this->t('<strong>Back up your database</strong>. This process will change your database values and in case of emergency you may need to revert to a backup.'); $info[] = $this->t('Install your new files in the appropriate location, as described in the handbook.'); $build['info'] = array( '#theme' => 'item_list', '#list_type' => 'ol', '#items' => $info, ); $build['info_footer'] = array( '#markup' => '<p>' . $this->t('When you have performed the steps above, you may proceed.') . '</p>', ); $build['link'] = array( '#type' => 'link', '#title' => $this->t('Continue'), '#attributes' => array('class' => array('button', 'button--primary')), // @todo Revisit once https://www.drupal.org/node/2548095 is in. '#url' => Url::fromUri('base://selection'), ); return $build; } /** * Renders a list of available database updates. * * @param \Symfony\Component\HttpFoundation\Request $request * The current request. * * @return array * A render array. */ protected function selection(Request $request) { // Make sure there is no stale theme registry. $this->cache->deleteAll(); $count = 0; $incompatible_count = 0; $build['start'] = array( '#tree' => TRUE, '#type' => 'details', ); // Ensure system.module's updates appear first. $build['start']['system'] = array(); $starting_updates = array(); $incompatible_updates_exist = FALSE; $updates_per_module = []; foreach (['update', 'post_update'] as $update_type) { switch ($update_type) { case 'update': $updates = update_get_update_list(); break; case 'post_update': $updates = $this->postUpdateRegistry->getPendingUpdateInformation(); break; } foreach ($updates as $module => $update) { if (!isset($update['start'])) { $build['start'][$module] = array( '#type' => 'item', '#title' => $module . ' module', '#markup' => $update['warning'], '#prefix' => '<div class="messages messages--warning">', '#suffix' => '</div>', ); $incompatible_updates_exist = TRUE; continue; } if (!empty($update['pending'])) { $updates_per_module += [$module => []]; $updates_per_module[$module] = array_merge($updates_per_module[$module], $update['pending']); $build['start'][$module] = array( '#type' => 'hidden', '#value' => $update['start'], ); // Store the previous items in order to merge normal updates and // post_update functions together. $build['start'][$module] = array( '#theme' => 'item_list', '#items' => $updates_per_module[$module], '#title' => $module . ' module', ); if ($update_type === 'update') { $starting_updates[$module] = $update['start']; } } if (isset($update['pending'])) { $count = $count + count($update['pending']); } } } // Find and label any incompatible updates. foreach (update_resolve_dependencies($starting_updates) as $data) { if (!$data['allowed']) { $incompatible_updates_exist = TRUE; $incompatible_count++; $module_update_key = $data['module'] . '_updates'; if (isset($build['start'][$module_update_key]['#items'][$data['number']])) { if ($data['missing_dependencies']) { $text = $this->t('This update will been skipped due to the following missing dependencies:') . '<em>' . implode(', ', $data['missing_dependencies']) . '</em>'; } else { $text = $this->t("This update will be skipped due to an error in the module's code."); } $build['start'][$module_update_key]['#items'][$data['number']] .= '<div class="warning">' . $text . '</div>'; } // Move the module containing this update to the top of the list. $build['start'] = array($module_update_key => $build['start'][$module_update_key]) + $build['start']; } } // Warn the user if any updates were incompatible. if ($incompatible_updates_exist) { drupal_set_message($this->t('Some of the pending updates cannot be applied because their dependencies were not met.'), 'warning'); } if (empty($count)) { drupal_set_message($this->t('No pending updates.')); unset($build); $build['links'] = array( '#theme' => 'links', '#links' => $this->helpfulLinks($request), ); // No updates to run, so caches won't get flushed later. Clear them now. drupal_flush_all_caches(); } else { $build['help'] = array( '#markup' => '<p>' . $this->t('The version of Drupal you are updating from has been automatically detected.') . '</p>', '#weight' => -5, ); if ($incompatible_count) { $build['start']['#title'] = $this->formatPlural( $count, '1 pending update (@number_applied to be applied, @number_incompatible skipped)', '@count pending updates (@number_applied to be applied, @number_incompatible skipped)', array('@number_applied' => $count - $incompatible_count, '@number_incompatible' => $incompatible_count) ); } else { $build['start']['#title'] = $this->formatPlural($count, '1 pending update', '@count pending updates'); } // @todo Simplify with https://www.drupal.org/node/2548095 $base_url = str_replace('/update.php', '', $request->getBaseUrl()); $url = (new Url('system.db_update', array('op' => 'run')))->setOption('base_url', $base_url); $build['link'] = array( '#type' => 'link', '#title' => $this->t('Apply pending updates'), '#attributes' => array('class' => array('button', 'button--primary')), '#weight' => 5, '#url' => $url, '#access' => $url->access($this->currentUser()), ); } return $build; } /** * Displays results of the update script with any accompanying errors. * * @param \Symfony\Component\HttpFoundation\Request $request * The current request. * * @return array * A render array. */ protected function results(Request $request) { // @todo Simplify with https://www.drupal.org/node/2548095 $base_url = str_replace('/update.php', '', $request->getBaseUrl()); // Report end result. $dblog_exists = $this->moduleHandler->moduleExists('dblog'); if ($dblog_exists && $this->account->hasPermission('access site reports')) { $log_message = $this->t('All errors have been <a href=":url">logged</a>.', array( ':url' => Url::fromRoute('dblog.overview')->setOption('base_url', $base_url)->toString(TRUE)->getGeneratedUrl(), )); } else { $log_message = $this->t('All errors have been logged.'); } if (!empty($_SESSION['update_success'])) { $message = '<p>' . $this->t('Updates were attempted. If you see no failures below, you may proceed happily back to your <a href=":url">site</a>. Otherwise, you may need to update your database manually.', array(':url' => Url::fromRoute('<front>')->setOption('base_url', $base_url)->toString(TRUE)->getGeneratedUrl())) . ' ' . $log_message . '</p>'; } else { $last = reset($_SESSION['updates_remaining']); list($module, $version) = array_pop($last); $message = '<p class="error">' . $this->t('The update process was aborted prematurely while running <strong>update #@version in @module.module</strong>.', array( '@version' => $version, '@module' => $module, )) . ' ' . $log_message; if ($dblog_exists) { $message .= ' ' . $this->t('You may need to check the <code>watchdog</code> database table manually.'); } $message .= '</p>'; } if (Settings::get('update_free_access')) { $message .= '<p>' . $this->t("<strong>Reminder: don't forget to set the <code>\$settings['update_free_access']</code> value in your <code>settings.php</code> file back to <code>FALSE</code>.</strong>") . '</p>'; } $build['message'] = array( '#markup' => $message, ); $build['links'] = array( '#theme' => 'links', '#links' => $this->helpfulLinks($request), ); // Output a list of info messages. if (!empty($_SESSION['update_results'])) { $all_messages = array(); foreach ($_SESSION['update_results'] as $module => $updates) { if ($module != '#abort') { $module_has_message = FALSE; $info_messages = array(); foreach ($updates as $name => $queries) { $messages = array(); foreach ($queries as $query) { // If there is no message for this update, don't show anything. if (empty($query['query'])) { continue; } if ($query['success']) { $messages[] = array( '#wrapper_attributes' => array('class' => array('success')), '#markup' => $query['query'], ); } else { $messages[] = array( '#wrapper_attributes' => array('class' => array('failure')), '#markup' => '<strong>' . $this->t('Failed:') . '</strong> ' . $query['query'], ); } } if ($messages) { $module_has_message = TRUE; if (is_numeric($name)) { $title = $this->t('Update #@count', ['@count' => $name]); } else { $title = $this->t('Update @name', ['@name' => trim($name, '_')]); } $info_messages[] = array( '#theme' => 'item_list', '#items' => $messages, '#title' => $title, ); } } // If there were any messages then prefix them with the module name // and add it to the global message list. if ($module_has_message) { $all_messages[] = array( '#type' => 'container', '#prefix' => '<h3>' . $this->t('@module module', array('@module' => $module)) . '</h3>', '#children' => $info_messages, ); } } } if ($all_messages) { $build['query_messages'] = array( '#type' => 'container', '#children' => $all_messages, '#attributes' => array('class' => array('update-results')), '#prefix' => '<h2>' . $this->t('The following updates returned messages:') . '</h2>', ); } } unset($_SESSION['update_results']); unset($_SESSION['update_success']); unset($_SESSION['update_ignore_warnings']); return $build; } /** * Renders a list of requirement errors or warnings. * * @param \Symfony\Component\HttpFoundation\Request $request * The current request. * * @return array * A render array. */ public function requirements($severity, array $requirements, Request $request) { $options = $severity == REQUIREMENT_WARNING ? array('continue' => 1) : array(); // @todo Revisit once https://www.drupal.org/node/2548095 is in. Something // like Url::fromRoute('system.db_update')->setOptions() should then be // possible. $try_again_url = Url::fromUri($request->getUriForPath(''))->setOptions(['query' => $options])->toString(TRUE)->getGeneratedUrl(); $build['status_report'] = array( '#theme' => 'status_report', '#requirements' => $requirements, '#suffix' => $this->t('Check the messages and <a href=":url">try again</a>.', array(':url' => $try_again_url)) ); $build['#title'] = $this->t('Requirements problem'); return $build; } /** * Provides the update task list render array. * * @param string $active * The active task. * Can be one of 'requirements', 'info', 'selection', 'run', 'results'. * * @return array * A render array. */ protected function updateTasksList($active = NULL) { // Default list of tasks. $tasks = array( 'requirements' => $this->t('Verify requirements'), 'info' => $this->t('Overview'), 'selection' => $this->t('Review updates'), 'run' => $this->t('Run updates'), 'results' => $this->t('Review log'), ); $task_list = array( '#theme' => 'maintenance_task_list', '#items' => $tasks, '#active' => $active, ); return $task_list; } /** * Starts the database update batch process. * * @param \Symfony\Component\HttpFoundation\Request $request * The current request object. */ protected function triggerBatch(Request $request) { $maintenance_mode = $this->state->get('system.maintenance_mode', FALSE); // Store the current maintenance mode status in the session so that it can // be restored at the end of the batch. $_SESSION['maintenance_mode'] = $maintenance_mode; // During the update, always put the site into maintenance mode so that // in-progress schema changes do not affect visiting users. if (empty($maintenance_mode)) { $this->state->set('system.maintenance_mode', TRUE); } $operations = array(); // Resolve any update dependencies to determine the actual updates that will // be run and the order they will be run in. $start = $this->getModuleUpdates(); $updates = update_resolve_dependencies($start); // Store the dependencies for each update function in an array which the // batch API can pass in to the batch operation each time it is called. (We // do not store the entire update dependency array here because it is // potentially very large.) $dependency_map = array(); foreach ($updates as $function => $update) { $dependency_map[$function] = !empty($update['reverse_paths']) ? array_keys($update['reverse_paths']) : array(); } // Determine updates to be performed. foreach ($updates as $function => $update) { if ($update['allowed']) { // Set the installed version of each module so updates will start at the // correct place. (The updates are already sorted, so we can simply base // this on the first one we come across in the above foreach loop.) if (isset($start[$update['module']])) { drupal_set_installed_schema_version($update['module'], $update['number'] - 1); unset($start[$update['module']]); } $operations[] = array('update_do_one', array($update['module'], $update['number'], $dependency_map[$function])); } } $post_updates = $this->postUpdateRegistry->getPendingUpdateFunctions(); if ($post_updates) { // Now we rebuild all caches and after that execute the hook_post_update() // functions. $operations[] = ['drupal_flush_all_caches', []]; foreach ($post_updates as $function) { $operations[] = ['update_invoke_post_update', [$function]]; } } $batch['operations'] = $operations; $batch += array( 'title' => $this->t('Updating'), 'init_message' => $this->t('Starting updates'), 'error_message' => $this->t('An unrecoverable error has occurred. You can find the error message below. It is advised to copy it to the clipboard for reference.'), 'finished' => array('\Drupal\system\Controller\DbUpdateController', 'batchFinished'), ); batch_set($batch); // @todo Revisit once https://www.drupal.org/node/2548095 is in. return batch_process(Url::fromUri('base://results'), Url::fromUri('base://start')); } /** * Finishes the update process and stores the results for eventual display. * * After the updates run, all caches are flushed. The update results are * stored into the session (for example, to be displayed on the update results * page in update.php). Additionally, if the site was off-line, now that the * update process is completed, the site is set back online. * * @param $success * Indicate that the batch API tasks were all completed successfully. * @param array $results * An array of all the results that were updated in update_do_one(). * @param array $operations * A list of all the operations that had not been completed by the batch API. */ public static function batchFinished($success, $results, $operations) { // No updates to run, so caches won't get flushed later. Clear them now. drupal_flush_all_caches(); $_SESSION['update_results'] = $results; $_SESSION['update_success'] = $success; $_SESSION['updates_remaining'] = $operations; // Now that the update is done, we can put the site back online if it was // previously not in maintenance mode. if (empty($_SESSION['maintenance_mode'])) { \Drupal::state()->set('system.maintenance_mode', FALSE); } unset($_SESSION['maintenance_mode']); } /** * Provides links to the homepage and administration pages. * * @param \Symfony\Component\HttpFoundation\Request $request * The current request. * * @return array * An array of links. */ protected function helpfulLinks(Request $request) { // @todo Simplify with https://www.drupal.org/node/2548095 $base_url = str_replace('/update.php', '', $request->getBaseUrl()); $links['front'] = array( 'title' => $this->t('Front page'), 'url' => Url::fromRoute('<front>')->setOption('base_url', $base_url), ); if ($this->account->hasPermission('access administration pages')) { $links['admin-pages'] = array( 'title' => $this->t('Administration pages'), 'url' => Url::fromRoute('system.admin')->setOption('base_url', $base_url), ); } return $links; } /** * Retrieves module updates. * * @return array * The module updates that can be performed. */ protected function getModuleUpdates() { $return = array(); $updates = update_get_update_list(); foreach ($updates as $module => $update) { $return[$module] = $update['start']; } return $return; } }
windtrader/drupalvm-d8
web/core/modules/system/src/Controller/DbUpdateController.php
PHP
gpl-2.0
25,829
"use strict"; exports.__esModule = true; var _typeof2 = require("babel-runtime/helpers/typeof"); var _typeof3 = _interopRequireDefault(_typeof2); var _keys = require("babel-runtime/core-js/object/keys"); var _keys2 = _interopRequireDefault(_keys); var _getIterator2 = require("babel-runtime/core-js/get-iterator"); var _getIterator3 = _interopRequireDefault(_getIterator2); exports.explode = explode; exports.verify = verify; exports.merge = merge; var _virtualTypes = require("./path/lib/virtual-types"); var virtualTypes = _interopRequireWildcard(_virtualTypes); var _babelMessages = require("babel-messages"); var messages = _interopRequireWildcard(_babelMessages); var _babelTypes = require("babel-types"); var t = _interopRequireWildcard(_babelTypes); var _clone = require("lodash/clone"); var _clone2 = _interopRequireDefault(_clone); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function explode(visitor) { if (visitor._exploded) return visitor; visitor._exploded = true; for (var nodeType in visitor) { if (shouldIgnoreKey(nodeType)) continue; var parts = nodeType.split("|"); if (parts.length === 1) continue; var fns = visitor[nodeType]; delete visitor[nodeType]; for (var _iterator = parts, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var part = _ref; visitor[part] = fns; } } verify(visitor); delete visitor.__esModule; ensureEntranceObjects(visitor); ensureCallbackArrays(visitor); for (var _iterator2 = (0, _keys2.default)(visitor), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { var _ref2; if (_isArray2) { if (_i2 >= _iterator2.length) break; _ref2 = _iterator2[_i2++]; } else { _i2 = _iterator2.next(); if (_i2.done) break; _ref2 = _i2.value; } var _nodeType3 = _ref2; if (shouldIgnoreKey(_nodeType3)) continue; var wrapper = virtualTypes[_nodeType3]; if (!wrapper) continue; var _fns2 = visitor[_nodeType3]; for (var type in _fns2) { _fns2[type] = wrapCheck(wrapper, _fns2[type]); } delete visitor[_nodeType3]; if (wrapper.types) { for (var _iterator4 = wrapper.types, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { var _ref4; if (_isArray4) { if (_i4 >= _iterator4.length) break; _ref4 = _iterator4[_i4++]; } else { _i4 = _iterator4.next(); if (_i4.done) break; _ref4 = _i4.value; } var _type = _ref4; if (visitor[_type]) { mergePair(visitor[_type], _fns2); } else { visitor[_type] = _fns2; } } } else { mergePair(visitor, _fns2); } } for (var _nodeType in visitor) { if (shouldIgnoreKey(_nodeType)) continue; var _fns = visitor[_nodeType]; var aliases = t.FLIPPED_ALIAS_KEYS[_nodeType]; var deprecratedKey = t.DEPRECATED_KEYS[_nodeType]; if (deprecratedKey) { console.trace("Visitor defined for " + _nodeType + " but it has been renamed to " + deprecratedKey); aliases = [deprecratedKey]; } if (!aliases) continue; delete visitor[_nodeType]; for (var _iterator3 = aliases, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { var _ref3; if (_isArray3) { if (_i3 >= _iterator3.length) break; _ref3 = _iterator3[_i3++]; } else { _i3 = _iterator3.next(); if (_i3.done) break; _ref3 = _i3.value; } var alias = _ref3; var existing = visitor[alias]; if (existing) { mergePair(existing, _fns); } else { visitor[alias] = (0, _clone2.default)(_fns); } } } for (var _nodeType2 in visitor) { if (shouldIgnoreKey(_nodeType2)) continue; ensureCallbackArrays(visitor[_nodeType2]); } return visitor; } function verify(visitor) { if (visitor._verified) return; if (typeof visitor === "function") { throw new Error(messages.get("traverseVerifyRootFunction")); } for (var nodeType in visitor) { if (nodeType === "enter" || nodeType === "exit") { validateVisitorMethods(nodeType, visitor[nodeType]); } if (shouldIgnoreKey(nodeType)) continue; if (t.TYPES.indexOf(nodeType) < 0) { throw new Error(messages.get("traverseVerifyNodeType", nodeType)); } var visitors = visitor[nodeType]; if ((typeof visitors === "undefined" ? "undefined" : (0, _typeof3.default)(visitors)) === "object") { for (var visitorKey in visitors) { if (visitorKey === "enter" || visitorKey === "exit") { validateVisitorMethods(nodeType + "." + visitorKey, visitors[visitorKey]); } else { throw new Error(messages.get("traverseVerifyVisitorProperty", nodeType, visitorKey)); } } } } visitor._verified = true; } function validateVisitorMethods(path, val) { var fns = [].concat(val); for (var _iterator5 = fns, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { var _ref5; if (_isArray5) { if (_i5 >= _iterator5.length) break; _ref5 = _iterator5[_i5++]; } else { _i5 = _iterator5.next(); if (_i5.done) break; _ref5 = _i5.value; } var fn = _ref5; if (typeof fn !== "function") { throw new TypeError("Non-function found defined in " + path + " with type " + (typeof fn === "undefined" ? "undefined" : (0, _typeof3.default)(fn))); } } } function merge(visitors) { var states = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1]; var wrapper = arguments[2]; var rootVisitor = {}; for (var i = 0; i < visitors.length; i++) { var visitor = visitors[i]; var state = states[i]; explode(visitor); for (var type in visitor) { var visitorType = visitor[type]; if (state || wrapper) { visitorType = wrapWithStateOrWrapper(visitorType, state, wrapper); } var nodeVisitor = rootVisitor[type] = rootVisitor[type] || {}; mergePair(nodeVisitor, visitorType); } } return rootVisitor; } function wrapWithStateOrWrapper(oldVisitor, state, wrapper) { var newVisitor = {}; var _loop = function _loop(key) { var fns = oldVisitor[key]; if (!Array.isArray(fns)) return "continue"; fns = fns.map(function (fn) { var newFn = fn; if (state) { newFn = function newFn(path) { return fn.call(state, path, state); }; } if (wrapper) { newFn = wrapper(state.key, key, newFn); } return newFn; }); newVisitor[key] = fns; }; for (var key in oldVisitor) { var _ret = _loop(key); if (_ret === "continue") continue; } return newVisitor; } function ensureEntranceObjects(obj) { for (var key in obj) { if (shouldIgnoreKey(key)) continue; var fns = obj[key]; if (typeof fns === "function") { obj[key] = { enter: fns }; } } } function ensureCallbackArrays(obj) { if (obj.enter && !Array.isArray(obj.enter)) obj.enter = [obj.enter]; if (obj.exit && !Array.isArray(obj.exit)) obj.exit = [obj.exit]; } function wrapCheck(wrapper, fn) { var newFn = function newFn(path) { if (wrapper.checkPath(path)) { return fn.apply(this, arguments); } }; newFn.toString = function () { return fn.toString(); }; return newFn; } function shouldIgnoreKey(key) { if (key[0] === "_") return true; if (key === "enter" || key === "exit" || key === "shouldSkip") return true; if (key === "blacklist" || key === "noScope" || key === "skipKeys") return true; return false; } function mergePair(dest, src) { for (var key in src) { dest[key] = [].concat(dest[key] || [], src[key]); } }
jintoppy/react-training
step8-unittest/node_modules/babel-plugin-transform-decorators/node_modules/babel-traverse/lib/visitors.js
JavaScript
mit
8,665
var gulp = require('gulp'); var paths = require('../paths'); var del = require('del'); var vinylPaths = require('vinyl-paths'); // deletes all files in the output path gulp.task('clean', function() { return gulp.src([paths.output]) .pipe(vinylPaths(del)); });
victorzki/doclify
workspace/build/tasks/clean.js
JavaScript
mit
267
var test = require('tap').test var server = require('./lib/server.js') var common = require('./lib/common.js') var client = common.freshClient() function nop () {} var URI = 'http://localhost:1337/rewrite' var TOKEN = 'b00b00feed' var PARAMS = { auth: { token: TOKEN } } test('logout call contract', function (t) { t.throws(function () { client.logout(undefined, PARAMS, nop) }, 'requires a URI') t.throws(function () { client.logout([], PARAMS, nop) }, 'requires URI to be a string') t.throws(function () { client.logout(URI, undefined, nop) }, 'requires params object') t.throws(function () { client.logout(URI, '', nop) }, 'params must be object') t.throws(function () { client.logout(URI, PARAMS, undefined) }, 'requires callback') t.throws(function () { client.logout(URI, PARAMS, 'callback') }, 'callback must be function') t.throws( function () { var params = { auth: {} } client.logout(URI, params, nop) }, { name: 'AssertionError', message: 'can only log out for token auth' }, 'auth must include token' ) t.end() }) test('log out from a token-based registry', function (t) { server.expect('DELETE', '/-/user/token/' + TOKEN, function (req, res) { t.equal(req.method, 'DELETE') t.equal(req.headers.authorization, 'Bearer ' + TOKEN, 'request is authed') res.json({message: 'ok'}) }) client.logout(URI, PARAMS, function (er) { t.ifError(er, 'no errors') t.end() }) }) test('cleanup', function (t) { server.close() t.end() })
markredballoon/clivemizen
wp-content/themes/redballoon/bootstrap/npm/node_modules/npm-registry-client/test/logout.js
JavaScript
gpl-2.0
1,584
/* Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ //>>built define("dojo/store/JsonRest",["../_base/xhr","../_base/lang","../json","../_base/declare","./util/QueryResults"],function(_1,_2,_3,_4,_5){ var _6=null; return _4("dojo.store.JsonRest",_6,{constructor:function(_7){ this.headers={}; _4.safeMixin(this,_7); },headers:{},target:"",idProperty:"id",ascendingPrefix:"+",descendingPrefix:"-",_getTarget:function(id){ var _8=this.target; if(typeof id!="undefined"){ if(_8.charAt(_8.length-1)=="/"){ _8+=id; }else{ _8+="/"+id; } } return _8; },get:function(id,_9){ _9=_9||{}; var _a=_2.mixin({Accept:this.accepts},this.headers,_9.headers||_9); return _1("GET",{url:this._getTarget(id),handleAs:"json",headers:_a}); },accepts:"application/javascript, application/json",getIdentity:function(_b){ return _b[this.idProperty]; },put:function(_c,_d){ _d=_d||{}; var id=("id" in _d)?_d.id:this.getIdentity(_c); var _e=typeof id!="undefined"; return _1(_e&&!_d.incremental?"PUT":"POST",{url:this._getTarget(id),postData:_3.stringify(_c),handleAs:"json",headers:_2.mixin({"Content-Type":"application/json",Accept:this.accepts,"If-Match":_d.overwrite===true?"*":null,"If-None-Match":_d.overwrite===false?"*":null},this.headers,_d.headers)}); },add:function(_f,_10){ _10=_10||{}; _10.overwrite=false; return this.put(_f,_10); },remove:function(id,_11){ _11=_11||{}; return _1("DELETE",{url:this._getTarget(id),headers:_2.mixin({},this.headers,_11.headers)}); },query:function(_12,_13){ _13=_13||{}; var _14=_2.mixin({Accept:this.accepts},this.headers,_13.headers); var _15=this.target.indexOf("?")>-1; if(_12&&typeof _12=="object"){ _12=_1.objectToQuery(_12); _12=_12?(_15?"&":"?")+_12:""; } if(_13.start>=0||_13.count>=0){ _14["X-Range"]="items="+(_13.start||"0")+"-"+(("count" in _13&&_13.count!=Infinity)?(_13.count+(_13.start||0)-1):""); if(this.rangeParam){ _12+=(_12||_15?"&":"?")+this.rangeParam+"="+_14["X-Range"]; _15=true; }else{ _14.Range=_14["X-Range"]; } } if(_13&&_13.sort){ var _16=this.sortParam; _12+=(_12||_15?"&":"?")+(_16?_16+"=":"sort("); for(var i=0;i<_13.sort.length;i++){ var _17=_13.sort[i]; _12+=(i>0?",":"")+(_17.descending?this.descendingPrefix:this.ascendingPrefix)+encodeURIComponent(_17.attribute); } if(!_16){ _12+=")"; } } var _18=_1("GET",{url:this.target+(_12||""),handleAs:"json",headers:_14}); _18.total=_18.then(function(){ var _19=_18.ioArgs.xhr.getResponseHeader("Content-Range"); if(!_19){ _19=_18.ioArgs.xhr.getResponseHeader("X-Content-Range"); } return _19&&(_19=_19.match(/\/(.*)/))&&+_19[1]; }); return _5(_18); }}); });
mbouami/pme
web/js/dojo/store/JsonRest.js
JavaScript
mit
2,702
require File.expand_path('../helper', __FILE__) require 'open3' class TestRakeReduceCompat < Rake::TestCase include RubyRunner def invoke_normal(task_name) rake task_name.to_s @out end def test_no_deprecated_dsl rakefile %q{ task :check_task do Module.new { p defined?(task) } end task :check_file do Module.new { p defined?(file) } end } assert_equal "nil", invoke_normal(:check_task).chomp assert_equal "nil", invoke_normal(:check_file).chomp end end
emineKoc/WiseWit
wisewitapi/vendor/bundle/gems/rake-11.1.2/test/test_rake_reduce_compat.rb
Ruby
gpl-3.0
532
#!/usr/bin/env python import os import re import subprocess import sys import tempfile CC = "gcc" CFLAGS = "-fmax-errors=4 -std=c99 -pipe -D_POSIX_C_SOURCE=200809L -W -Wall -Wno-unused-variable -Wno-unused-parameter -Wno-unused-label -Wno-unused-value -Wno-unused-but-set-variable -Wno-unused-function -Wno-main".split(" ") class Table(): pass class TestMode(): pass_ = 0 fail_compile_parse = 1 fail_compile_sem = 2 fail_compile_ice = 3 fail_c = 4 fail_run = 5 fail_output = 6 fail_other = 7 disable = 8 test_modes = [TestMode.pass_, TestMode.fail_compile_parse, TestMode.fail_compile_sem, TestMode.fail_compile_ice, TestMode.fail_c, TestMode.fail_run, TestMode.fail_output, TestMode.fail_other, TestMode.disable] test_mode_names = { TestMode.pass_: ("pass", "Passed"), TestMode.fail_compile_parse: ("fail_compile_parse", "Compilation failed (parsing)"), TestMode.fail_compile_sem: ("fail_compile_sem", "Compilation failed (semantics)"), TestMode.fail_compile_ice: ("fail_compile_ice", "Compilation failed (ICE)"), TestMode.fail_c: ("fail_c", "C compilation/linking failed"), TestMode.fail_run: ("fail_run", "Run failed"), TestMode.fail_output: ("fail_output", "Output mismatched"), TestMode.fail_other: ("fail_other", "Expected failure didn't happen"), TestMode.disable: ("disable", "Disabled"), } test_stats = dict([(m, 0) for m in test_modes]) test_mode_values = {} for m, (s, _) in test_mode_names.iteritems(): test_mode_values[s] = m def pick(v, m): if v not in m: raise Exception("Unknown value '%s'" % v) return m[v] def run_test(filename): testname = os.path.basename(filename) print("Test '%s'..." % testname) workdir = tempfile.mkdtemp(prefix="boringtest") tempfiles = [] src = open(filename) headers = Table() headers.mode = TestMode.pass_ headers.is_expr = False headers.stdout = None while True: hline = src.readline() if not hline: break m = re.match("(?://|/\*) ([A-Z]+):(.*)", hline) if not m: break name, value = m.group(1), m.group(2) value = value.strip() if name == "TEST": headers.mode = pick(value, test_mode_values) elif name == "TYPE": headers.is_expr = pick(value, {"normal": False, "expr": True}) elif name == "STDOUT": term = value + "*/" stdout = "" while True: line = src.readline() if not line: raise Exception("unterminated STDOUT header") if line.strip() == term: break stdout += line headers.stdout = stdout else: raise Exception("Unknown header '%s'" % name) src.close() def do_run(): if headers.mode == TestMode.disable: return TestMode.disable # make is for fags tc = os.path.join(workdir, "t.c") tcf = open(tc, "w") tempfiles.append(tc) res = subprocess.call(["./main", "cg_c", filename], stdout=tcf) tcf.close() if res != 0: if res == 1: return TestMode.fail_compile_parse if res == 2: return TestMode.fail_compile_sem return TestMode.fail_compile_ice t = os.path.join(workdir, "t") tempfiles.append(t) res = subprocess.call([CC] + CFLAGS + [tc, "-o", t]) if res != 0: return TestMode.fail_c p = subprocess.Popen([t], stdout=subprocess.PIPE) output, _ = p.communicate() res = p.wait() if res != 0: return TestMode.fail_run if headers.stdout is not None and headers.stdout != output: print("Program output: >\n%s<\nExpected: >\n%s<" % (output, headers.stdout)) return TestMode.fail_output return TestMode.pass_ actual_res = do_run() for f in tempfiles: try: os.unlink(f) except OSError: pass os.rmdir(workdir) res = actual_res if res == TestMode.disable: pass elif res == headers.mode: res = TestMode.pass_ else: if headers.mode != TestMode.pass_: res = TestMode.fail_other test_stats[res] += 1 print("Test '%s': %s (expected %s, got %s)" % (testname, test_mode_names[res][0], test_mode_names[headers.mode][0], test_mode_names[actual_res][0])) def run_tests(list_file_name): base = os.path.dirname(list_file_name) for f in [x.strip() for x in open(argv[1])]: run_test(os.path.join(base, f)) print("SUMMARY:") test_sum = 0 for m in test_modes: print(" %s: %d" % (test_mode_names[m][1], test_stats[m])) test_sum += test_stats[m] passed_tests = test_stats[TestMode.pass_] failed_tests = test_sum - passed_tests - test_stats[TestMode.disable] print("Passed/failed: %s/%d" % (passed_tests, failed_tests)) if failed_tests: print("OMG OMG OMG ------- Some tests have failed ------- OMG OMG OMG") sys.exit(1) if __name__ == "__main__": argv = sys.argv if len(argv) != 2: print("Usage: %s tests.lst" % argv[0]) sys.exit(1) #subprocess.check_call(["make", "main"]) run_tests(argv[1])
wm4/boringlang
run_tests.py
Python
isc
5,430
var cx = require('classnames'); var blacklist = require('blacklist'); var React = require('react'); module.exports = React.createClass({ displayName: 'Field', getDefaultProps() { return { d: null, t: null, m: null, label: '' } }, renderError() { if(!this.props.error) return null; return <span className="error">{this.props.error}</span>; }, renderLabel() { var cn = cx('label', this.props.d ? `g-${this.props.d}` : null); if(!this.props.label) { return ( <label className={cn}>&nbsp;</label> ); } return ( <label className={cn}> {this.props.label} </label> ); }, render() { var props = blacklist(this.props, 'label', 'error', 'children', 'd', 't', 'm'); props.className = cx('u-field', { 'g-row': this.props.d, 'u-field-row': this.props.d, 'u-field-err': this.props.error }); return ( <div {... props}> {this.renderLabel()} {this.props.d ? ( <div className={`g-${24 - this.props.d}`}> {this.props.children} </div> ) : this.props.children} {this.renderError()} </div> ); } });
wangzuo/feng-ui
react/field.js
JavaScript
isc
1,218
package info.faceland.loot.data; public class PriceData { private int price; private boolean rare; public PriceData (int price, boolean rare) { this.price = price; this.rare = rare; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public boolean isRare() { return rare; } public void setRare(boolean rare) { this.rare = rare; } }
TealCube/loot
src/main/java/info/faceland/loot/data/PriceData.java
Java
isc
435
#include "kvazaarfilter.h" #include "statisticsinterface.h" #include "common.h" #include "settingskeys.h" #include "logger.h" #include <kvazaar.h> #include <QtDebug> #include <QTime> #include <QSize> enum RETURN_STATUS {C_SUCCESS = 0, C_FAILURE = -1}; KvazaarFilter::KvazaarFilter(QString id, StatisticsInterface *stats, std::shared_ptr<HWResourceManager> hwResources): Filter(id, "Kvazaar", stats, hwResources, DT_YUV420VIDEO, DT_HEVCVIDEO), api_(nullptr), config_(nullptr), enc_(nullptr), pts_(0), input_pic_(nullptr), framerate_num_(30), framerate_denom_(1), encodingFrames_() { maxBufferSize_ = 3; } void KvazaarFilter::updateSettings() { Logger::getLogger()->printNormal(this, "Updating kvazaar settings"); stop(); while(isRunning()) { sleep(1); } close(); encodingFrames_.clear(); if(init()) { Logger::getLogger()->printNormal(this, "Resolution change successful"); } else { Logger::getLogger()->printNormal(this, "Failed to change resolution"); } start(); Filter::updateSettings(); } bool KvazaarFilter::init() { Logger::getLogger()->printNormal(this, "Iniating Kvazaar"); // input picture should not exist at this point if(!input_pic_ && !api_) { api_ = kvz_api_get(8); if(!api_) { Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this, "Failed to retrieve Kvazaar API."); return false; } config_ = api_->config_alloc(); enc_ = nullptr; if(!config_) { Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this, "Failed to allocate Kvazaar config."); return false; } QSettings settings(settingsFile, settingsFileFormat); api_->config_init(config_); api_->config_parse(config_, "preset", settings.value(SettingsKey::videoPreset).toString().toUtf8()); // input #ifdef __linux__ if (settingEnabled(SettingsKey::screenShareStatus)) { config_->width = settings.value(SettingsKey::videoResultionWidth).toInt(); config_->height = settings.value(SettingsKey::videoResultionHeight).toInt(); framerate_num_ = settings.value(SettingsKey::videoFramerate).toFloat(); config_->framerate_num = framerate_num_; } else { // On Linux the Camerafilter seems to have a Qt bug that causes not being able to set resolution config_->width = 640; config_->height = 480; config_->framerate_num = 30; } #else config_->width = settings.value(SettingsKey::videoResultionWidth).toInt(); config_->height = settings.value(SettingsKey::videoResultionHeight).toInt(); convertFramerate(settings.value(SettingsKey::videoFramerate).toReal()); config_->framerate_num = framerate_num_; #endif config_->framerate_denom = framerate_denom_; // parallelization if (settings.value(SettingsKey::videoKvzThreads) == "auto") { config_->threads = QThread::idealThreadCount(); } else if (settings.value(SettingsKey::videoKvzThreads) == "Main") { config_->threads = 0; } else { config_->threads = settings.value(SettingsKey::videoKvzThreads).toInt(); } config_->owf = settings.value(SettingsKey::videoOWF).toInt(); config_->wpp = settings.value(SettingsKey::videoWPP).toInt(); bool tiles = false; if (tiles) { std::string dimensions = settings.value(SettingsKey::videoTileDimensions).toString().toStdString(); api_->config_parse(config_, "tiles", dimensions.c_str()); } // this does not work with uvgRTP at the moment. Avoid using slices. if(settings.value(SettingsKey::videoSlices).toInt() == 1) { if(config_->wpp) { config_->slices = KVZ_SLICES_WPP; } else if (tiles) { config_->slices = KVZ_SLICES_TILES; } } // Structure config_->qp = settings.value(SettingsKey::videoQP).toInt(); config_->intra_period = settings.value(SettingsKey::videoIntra).toInt(); config_->vps_period = settings.value(SettingsKey::videoVPS).toInt(); config_->target_bitrate = settings.value(SettingsKey::videoBitrate).toInt(); if (config_->target_bitrate != 0) { QString rcAlgo = settings.value(SettingsKey::videoRCAlgorithm).toString(); if (rcAlgo == "lambda") { config_->rc_algorithm = KVZ_LAMBDA; } else if (rcAlgo == "oba") { config_->rc_algorithm = KVZ_OBA; config_->clip_neighbour = settings.value(SettingsKey::videoOBAClipNeighbours).toInt(); } else { Logger::getLogger()->printWarning(this, "Some carbage in rc algorithm setting"); config_->rc_algorithm = KVZ_NO_RC; } } else { config_->rc_algorithm = KVZ_NO_RC; } config_->gop_lowdelay = 1; if (settings.value(SettingsKey::videoScalingList).toInt() == 0) { config_->scaling_list = KVZ_SCALING_LIST_OFF; } else { config_->scaling_list = KVZ_SCALING_LIST_DEFAULT; } config_->lossless = settings.value(SettingsKey::videoLossless).toInt(); QString constraint = settings.value(SettingsKey::videoMVConstraint).toString(); if (constraint == "frame") { config_->mv_constraint = KVZ_MV_CONSTRAIN_FRAME; } else if (constraint == "tile") { config_->mv_constraint = KVZ_MV_CONSTRAIN_TILE; } else if (constraint == "frametile") { config_->mv_constraint = KVZ_MV_CONSTRAIN_FRAME_AND_TILE; } else if (constraint == "frametilemargin") { config_->mv_constraint = KVZ_MV_CONSTRAIN_FRAME_AND_TILE_MARGIN; } else { config_->mv_constraint = KVZ_MV_CONSTRAIN_NONE; } config_->set_qp_in_cu = settings.value(SettingsKey::videoQPInCU).toInt(); config_->vaq = settings.value(SettingsKey::videoVAQ).toInt(); // compression-tab customParameters(settings); config_->hash = KVZ_HASH_NONE; enc_ = api_->encoder_open(config_); if(!enc_) { Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this, "Failed to open Kvazaar encoder."); return false; } input_pic_ = api_->picture_alloc(config_->width, config_->height); if(!input_pic_) { Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this, "Could not allocate input picture."); return false; } Logger::getLogger()->printNormal(this, "Kvazaar iniation succeeded"); } return true; } void KvazaarFilter::close() { if(api_) { api_->encoder_close(enc_); api_->config_destroy(config_); enc_ = nullptr; config_ = nullptr; api_->picture_free(input_pic_); input_pic_ = nullptr; api_ = nullptr; } pts_ = 0; Logger::getLogger()->printNormal(this, "Closed Kvazaar"); } void KvazaarFilter::process() { Q_ASSERT(enc_); Q_ASSERT(config_); std::unique_ptr<Data> input = getInput(); while(input) { if(!input_pic_) { Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this, "Input picture was not allocated correctly."); break; } feedInput(std::move(input)); input = getInput(); } } void KvazaarFilter::customParameters(QSettings& settings) { int size = settings.beginReadArray(SettingsKey::videoCustomParameters); Logger::getLogger()->printNormal(this, "Getting custom Kvazaar parameters", "Amount", QString::number(size)); for(int i = 0; i < size; ++i) { settings.setArrayIndex(i); QString name = settings.value("Name").toString(); QString value = settings.value("Value").toString(); if (api_->config_parse(config_, name.toStdString().c_str(), value.toStdString().c_str()) != 1) { Logger::getLogger()->printWarning(this, "Invalid custom parameter for kvazaar", "Amount", QString::number(size)); } } settings.endArray(); } void KvazaarFilter::feedInput(std::unique_ptr<Data> input) { kvz_picture *recon_pic = nullptr; kvz_frame_info frame_info; kvz_data_chunk *data_out = nullptr; uint32_t len_out = 0; if (config_->width != input->vInfo->width || config_->height != input->vInfo->height || (double)(config_->framerate_num/config_->framerate_denom) != input->vInfo->framerate) { // This should not happen. Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this, "Input resolution or framerate differs from settings", {"Settings", "Input"}, {QString::number(config_->width) + "x" + QString::number(config_->height) + "p" + QString::number(config_->framerate_num), QString::number(input->vInfo->width) + "x" + QString::number(input->vInfo->height) + "p" + QString::number(input->vInfo->framerate)}); return; } // copy input to kvazaar picture memcpy(input_pic_->y, input->data.get(), input->vInfo->width*input->vInfo->height); memcpy(input_pic_->u, &(input->data.get()[input->vInfo->width*input->vInfo->height]), input->vInfo->width*input->vInfo->height/4); memcpy(input_pic_->v, &(input->data.get()[input->vInfo->width*input->vInfo->height + input->vInfo->width*input->vInfo->height/4]), input->vInfo->width*input->vInfo->height/4); input_pic_->pts = pts_; ++pts_; encodingFrames_.push_front(std::move(input)); api_->encoder_encode(enc_, input_pic_, &data_out, &len_out, &recon_pic, nullptr, &frame_info ); while(data_out != nullptr) { parseEncodedFrame(data_out, len_out, recon_pic); // see if there is more output ready api_->encoder_encode(enc_, nullptr, &data_out, &len_out, &recon_pic, nullptr, &frame_info ); } } void KvazaarFilter::parseEncodedFrame(kvz_data_chunk *data_out, uint32_t len_out, kvz_picture *recon_pic) { std::unique_ptr<Data> encodedFrame = std::move(encodingFrames_.back()); encodingFrames_.pop_back(); std::unique_ptr<uchar[]> hevc_frame(new uchar[len_out]); uint8_t* writer = hevc_frame.get(); uint32_t dataWritten = 0; for (kvz_data_chunk *chunk = data_out; chunk != nullptr; chunk = chunk->next) { if(chunk->len > 3 && chunk->data[0] == 0 && chunk->data[1] == 0 && ( chunk->data[2] == 1 || (chunk->data[2] == 0 && chunk->data[3] == 1 )) && dataWritten != 0 && config_->slices != KVZ_SLICES_NONE) { // send previous packet if this is not the first std::unique_ptr<Data> slice(shallowDataCopy(encodedFrame.get())); sendEncodedFrame(std::move(slice), std::move(hevc_frame), dataWritten); hevc_frame = std::unique_ptr<uchar[]>(new uchar[len_out - dataWritten]); writer = hevc_frame.get(); dataWritten = 0; } memcpy(writer, chunk->data, chunk->len); writer += chunk->len; dataWritten += chunk->len; } api_->chunk_free(data_out); api_->picture_free(recon_pic); uint32_t delay = QDateTime::currentMSecsSinceEpoch() - encodedFrame->presentationTime; getStats()->sendDelay("video", delay); getStats()->addEncodedPacket("video", len_out); // send last packet reusing input structure sendEncodedFrame(std::move(encodedFrame), std::move(hevc_frame), dataWritten); } void KvazaarFilter::sendEncodedFrame(std::unique_ptr<Data> input, std::unique_ptr<uchar[]> hevc_frame, uint32_t dataWritten) { input->type = DT_HEVCVIDEO; input->data_size = dataWritten; input->data = std::move(hevc_frame); sendOutput(std::move(input)); } void KvazaarFilter::convertFramerate(double framerate) { uint32_t wholeNumber = (uint32_t)framerate; double remainder = framerate - wholeNumber; if (remainder > 0.0) { uint32_t multiplier = 1.0 /remainder; framerate_num_ = framerate*multiplier; framerate_denom_ = multiplier; } else { framerate_num_ = wholeNumber; framerate_denom_ = 1; } Logger::getLogger()->printNormal(this, "Got framerate num and denum", "Framerate", {QString::number(framerate_num_) + "/" + QString::number(framerate_denom_) }); }
ultravideo/kvazzup
src/media/processing/kvazaarfilter.cpp
C++
isc
12,600
/* @flow */ import { PropTypes } from 'react' export default PropTypes.oneOfType([ // [Number, Number] PropTypes.arrayOf(PropTypes.number), // {lat: Number, lng: Number} PropTypes.shape({ lat: PropTypes.number, lng: PropTypes.number, }), // {lat: Number, lon: Number} PropTypes.shape({ lat: PropTypes.number, lon: PropTypes.number, }), ])
wxtiles/wxtiles-map
node_modules/react-leaflet/src/types/latlng.js
JavaScript
isc
373
// Arguments: Doubles, Doubles, Doubles #include <stan/math/prim/scal.hpp> using std::vector; using std::numeric_limits; using stan::math::var; class AgradCdfGumbel : public AgradCdfTest { public: void valid_values(vector<vector<double> >& parameters, vector<double>& cdf) { vector<double> param(3); param[0] = 0.0; // y param[1] = 0.0; // mu param[2] = 1.0; // beta parameters.push_back(param); cdf.push_back(0.3678794411714423215955237701614608674458111310317678); // expected cdf param[0] = 1.0; // y param[1] = 0.0; // mu param[2] = 1.0; // beta parameters.push_back(param); cdf.push_back(0.6922006275553463538654219971827897614906780292975447); // expected cdf param[0] = -2.0; // y param[1] = 0.0; // mu param[2] = 1.0; // beta parameters.push_back(param); cdf.push_back(0.0006179789893310934986195216040530260548886143651007); // expected cdf param[0] = -3.5; // y param[1] = 1.9; // mu param[2] = 7.2; // beta parameters.push_back(param); cdf.push_back(0.1203922620798295861862650786832089422663975274508450); // expected cdf } void invalid_values(vector<size_t>& index, vector<double>& value) { // y // mu index.push_back(1U); value.push_back(numeric_limits<double>::infinity()); index.push_back(1U); value.push_back(-numeric_limits<double>::infinity()); // beta index.push_back(2U); value.push_back(0.0); index.push_back(2U); value.push_back(-1.0); index.push_back(2U); value.push_back(-numeric_limits<double>::infinity()); } bool has_lower_bound() { return false; } bool has_upper_bound() { return false; } template <typename T_y, typename T_loc, typename T_scale, typename T3, typename T4, typename T5> typename stan::return_type<T_y, T_loc, T_scale>::type cdf(const T_y& y, const T_loc& mu, const T_scale& beta, const T3&, const T4&, const T5&) { return stan::math::gumbel_cdf(y, mu, beta); } template <typename T_y, typename T_loc, typename T_scale, typename T3, typename T4, typename T5> typename stan::return_type<T_y, T_loc, T_scale>::type cdf_function(const T_y& y, const T_loc& mu, const T_scale& beta, const T3&, const T4&, const T5&) { return exp(-exp(-(y - mu) / beta)); } };
ariddell/httpstan
httpstan/lib/stan/lib/stan_math/test/prob/gumbel/gumbel_cdf_test.hpp
C++
isc
2,497
module Users::FollowHelper end
smlsml/snappitt
app/helpers/users/follow_helper.rb
Ruby
isc
31
import { modulo } from './Math.js' export function random(x) { return modulo(Math.sin(x) * 43758.5453123, 1) }
damienmortini/dlib
packages/core/math/PRNG.js
JavaScript
isc
114
'use strict'; var main = { expand:true, cwd: './build/styles/', src:['*.css'], dest: './build/styles/' }; module.exports = { main:main };
ariosejs/bui
grunt/config/cssmin.js
JavaScript
isc
161
package de.klimek.spacecurl.activities; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.content.Context; import android.content.pm.ActivityInfo; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.sothree.slidinguppanel.SlidingUpPanelLayout; import com.sothree.slidinguppanel.SlidingUpPanelLayout.PanelSlideListener; import java.util.ArrayList; import java.util.List; import de.klimek.spacecurl.Database; import de.klimek.spacecurl.R; import de.klimek.spacecurl.game.GameCallBackListener; import de.klimek.spacecurl.game.GameDescription; import de.klimek.spacecurl.game.GameFragment; import de.klimek.spacecurl.util.ColorGradient; import de.klimek.spacecurl.util.cards.StatusCard; import de.klimek.spacecurl.util.collection.GameStatus; import de.klimek.spacecurl.util.collection.Training; import de.klimek.spacecurl.util.collection.TrainingStatus; import it.gmariotti.cardslib.library.internal.Card; import it.gmariotti.cardslib.library.internal.CardArrayAdapter; import it.gmariotti.cardslib.library.view.CardListView; import it.gmariotti.cardslib.library.view.CardView; /** * This abstract class loads a training and provides functionality to * subclasses, e. g. usage of the status panel, switching games, and showing a * pause screen. <br/> * A Training must be loaded with {@link #loadTraining(Training)}. In order to * use the status-panel {@link #useStatusPanel()} has to be called. * * @author Mike Klimek * @see <a href="http://developer.android.com/reference/packages.html">Android * API</a> */ public abstract class BasicTrainingActivity extends FragmentActivity implements OnClickListener, GameCallBackListener { public static final String TAG = BasicTrainingActivity.class.getName(); // Status panel private boolean mUsesStatus = false; private TrainingStatus mTrainingStatus; private GameStatus mCurGameStatus; private int mStatusColor; private ColorGradient mStatusGradient = new ColorGradient(Color.RED, Color.YELLOW, Color.GREEN); private FrameLayout mStatusIndicator; private ImageButton mSlidingToggleButton; private boolean mButtonImageIsExpand = true; private SlidingUpPanelLayout mSlidingUpPanel; private CardListView mCardListView; private CardArrayAdapter mCardArrayAdapter; private List<Card> mCards = new ArrayList<Card>(); private GameFragment mGameFragment; private FrameLayout mGameFrame; private Training mTraining; private Database mDatabase; // Pause Frame private FrameLayout mPauseFrame; private LinearLayout mInstructionLayout; private ImageView mResumeButton; private TextView mInstructionsTextView; private String mInstructions = ""; private int mShortAnimationDuration; private State mState = State.Paused; public static enum State { Paused, Pausing, Running } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mDatabase = Database.getInstance(this); setContentView(R.layout.activity_base); setupPauseView(); } /** * Dialog with instructions for the current game or pause/play icon. Shows * when the user interacts with the App. */ private void setupPauseView() { mGameFrame = (FrameLayout) findViewById(R.id.game_frame); mGameFrame.setOnClickListener(this); // hide initially mPauseFrame = (FrameLayout) findViewById(R.id.pause_layout); mPauseFrame.setAlpha(0.0f); mPauseFrame.setVisibility(View.GONE); mInstructionLayout = (LinearLayout) findViewById(R.id.instruction_layout); mResumeButton = (ImageView) findViewById(R.id.resume_button); mInstructionsTextView = (TextView) findViewById(R.id.instructions_textview); mShortAnimationDuration = getResources().getInteger( android.R.integer.config_shortAnimTime); } @Override protected void onResume() { super.onResume(); if (mDatabase.isOrientationLandscape()) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } /** * Subclasses must load a Training with this method. * * @param training */ protected final void loadTraining(Training training) { mTraining = training; } /** * Subclasses can use this method to enable the status-panel. */ protected final void useStatusPanel() { mTrainingStatus = mTraining.createTrainingStatus(); mUsesStatus = true; mStatusIndicator = (FrameLayout) findViewById(R.id.status_indicator); mSlidingToggleButton = (ImageButton) findViewById(R.id.panel_button); mSlidingUpPanel = (SlidingUpPanelLayout) findViewById(R.id.content_frame); mSlidingUpPanel.setPanelSlideListener(new PanelSlideListener() { @Override public void onPanelSlide(View panel, float slideOffset) { if (slideOffset > 0.5f && mButtonImageIsExpand) { mSlidingToggleButton.setImageResource(R.drawable.ic_collapse); mButtonImageIsExpand = false; } else if (slideOffset < 0.5f && !mButtonImageIsExpand) { mSlidingToggleButton.setImageResource(R.drawable.ic_expand); mButtonImageIsExpand = true; } } @Override public void onPanelCollapsed(View panel) { } @Override public void onPanelExpanded(View panel) { } @Override public void onPanelAnchored(View panel) { } @Override public void onPanelHidden(View panel) { } }); int statusIndicatorHeight = (int) (getResources() .getDimension(R.dimen.status_indicator_height)); mSlidingUpPanel.setPanelHeight(statusIndicatorHeight); // delegate clicks to underlying panel mSlidingToggleButton.setClickable(false); mSlidingUpPanel.setEnabled(true); // setup cardlist mCardArrayAdapter = new FixedCardArrayAdapter(this, mCards); mCardListView = (CardListView) findViewById(R.id.card_list); mCardListView.setAdapter(mCardArrayAdapter); } protected final void updateCurGameStatus(final float status) { // graph mCurGameStatus.addStatus(status); // indicator color mStatusColor = mStatusGradient.getColorForFraction(status); mStatusIndicator.setBackgroundColor(mStatusColor); } protected final void expandSlidingPane() { if (mState == State.Running) { pause(); mState = State.Paused; } mSlidingUpPanel.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED); } protected final void collapseSlidingPane() { mSlidingUpPanel.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED); } protected final void showStatusIndicator() { mStatusIndicator.setVisibility(View.VISIBLE); } protected final void hideStatusIndicator() { mStatusIndicator.setVisibility(View.GONE); } protected final void lockSlidingPane() { mSlidingToggleButton.setVisibility(View.GONE); } protected final void unlockSlidingPane() { mSlidingToggleButton.setVisibility(View.VISIBLE); } /** * Creates a new GameFragment from a gameDescriptionIndex and displays it. * Switches to the associated gameStatus from a previous game (overwriting * it) or creates a new one. * * @param gameDescriptionIndex the game to start * @param enterAnimation how the fragment should enter * @param exitAnimation how the previous fragment should be removed */ protected final void switchToGame(int gameDescriptionIndex, int enterAnimation, int exitAnimation) { mState = State.Paused; pause(); // get Fragment GameDescription newGameDescription = mTraining.get(gameDescriptionIndex); mGameFragment = newGameDescription.createFragment(); // Transaction getSupportFragmentManager().beginTransaction() .setCustomAnimations(enterAnimation, exitAnimation) .replace(R.id.game_frame, mGameFragment) .commit(); // enable callback mGameFragment.registerGameCallBackListener(this); // update pause view mInstructions = newGameDescription.getInstructions(); if (mInstructions == null || mInstructions.isEmpty()) { // only show pause/play icon mInstructionLayout.setVisibility(View.GONE); mResumeButton.setVisibility(View.VISIBLE); } else { // only show instructions mResumeButton.setVisibility(View.GONE); mInstructionLayout.setVisibility(View.VISIBLE); mInstructionsTextView.setText(mInstructions); } if (mUsesStatus) { // switch to status associated with current game mCurGameStatus = mTrainingStatus.get(gameDescriptionIndex); if (mCurGameStatus == null) { // create new mCurGameStatus = new GameStatus(newGameDescription.getTitle()); mTrainingStatus.append(gameDescriptionIndex, mCurGameStatus); mCards.add(gameDescriptionIndex, new StatusCard(this, mCurGameStatus)); mCardArrayAdapter.notifyDataSetChanged(); } else { // reset existing mCurGameStatus.reset(); mCardArrayAdapter.notifyDataSetChanged(); } } } /** * Convenience method. Same as * {@link #switchToGame(int gameDescriptionIndex, int enterAnimation, int exitAnimation)} * but uses standard fade_in/fade_out animations. * * @param gameDescriptionIndex the game to start */ protected final void switchToGame(int gameDescriptionIndex) { switchToGame(gameDescriptionIndex, android.R.anim.fade_in, android.R.anim.fade_out); } @Override protected void onPause() { super.onPause(); if (mState == State.Running) { pause(); } mState = State.Paused; } @Override public void onUserInteraction() { // Pause on every user interaction if (mState == State.Running) { mState = State.Pausing; pause(); } else if (mState == State.Pausing) { // Previously clicked outside of gameframe and now possibly on // gameframe again to resume mState = State.Paused; } super.onUserInteraction(); } /** * Called when clicking inside the game frame (after onUserInteraction) */ @Override public void onClick(View v) { if (mState == State.Paused) { // Resume when paused resume(); mState = State.Running; } else if (mState == State.Pausing) { // We have just paused in onUserInteraction -> don't resume mState = State.Paused; } } private void pause() { Log.v(TAG, "Paused"); // pause game if (mGameFragment != null) { mGameFragment.onPauseGame(); } // Show pause view and grey out screen mPauseFrame.setVisibility(View.VISIBLE); mPauseFrame.animate() .alpha(1f) .setDuration(mShortAnimationDuration) .setListener(null); // Show navigation bar getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE); } private void resume() { Log.v(TAG, "Resumed"); // hide pause view mPauseFrame.animate() .alpha(0f) .setDuration(mShortAnimationDuration) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mPauseFrame.setVisibility(View.GONE); } }); // resume game if (mGameFragment != null) { mGameFragment.onResumeGame(); } // Grey out navigation bar getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); } /** * Fixes bug in {@link CardArrayAdapter CardArrayAdapter's} Viewholder * pattern. Otherwise the cards innerViewElements would not be replaced * (Title and Graph from previous Graph is shown). * * @author Mike Klimek */ private class FixedCardArrayAdapter extends CardArrayAdapter { public FixedCardArrayAdapter(Context context, List<Card> cards) { super(context, cards); } @Override public View getView(int position, View convertView, ViewGroup parent) { Card card = (Card) getItem(position); if (convertView == null) { LayoutInflater layoutInflater = LayoutInflater.from(getContext()); convertView = layoutInflater.inflate(R.layout.list_card_layout, parent, false); } CardView view = (CardView) convertView.findViewById(R.id.list_cardId); view.setForceReplaceInnerLayout(true); view.setCard(card); return convertView; } } }
Tetr4/Spacecurl
app/src/main/java/de/klimek/spacecurl/activities/BasicTrainingActivity.java
Java
isc
14,055
// C++ entry point #include "Elf32.h" // autogen.h contains the full kernel binary in a char array #include "autogen.h" extern "C" { volatile unsigned char *uart1 = (volatile unsigned char*) 0x4806A000; volatile unsigned char *uart2 = (volatile unsigned char*) 0x4806C000; volatile unsigned char *uart3 = (volatile unsigned char*) 0x49020000; extern int memset(void *buf, int c, size_t len); }; // http://www.simtec.co.uk/products/SWLINUX/files/booting_article.html // http://www.arm.linux.org.uk/developer/booting.php #define ATAG_NONE 0 #define ATAG_CORE 0x54410001 #define ATAG_MEM 0x54410002 #define ATAG_VIDEOTEXT 0x54410003 #define ATAG_RAMDISK 0x54410004 #define ATAG_INITRD2 0x54410005 #define ATAG_SERIAL 0x54410006 #define ATAG_REVISION 0x54410007 #define ATAG_VIDEOLFB 0x54410008 #define ATAG_CMDLINE 0x54410009 struct atag_header { uint32_t size; uint32_t tag; }; struct atag_core { uint32_t flags; uint32_t pagesize; uint32_t rootdev; }; struct atag_mem { uint32_t size; uint32_t start; }; struct atag_videotext { unsigned char x; unsigned char y; unsigned short video_page; unsigned char video_mode; unsigned char video_cols; unsigned short video_ega_bx; unsigned char video_lines; unsigned char video_isvga; unsigned short video_points; }; struct atag_ramdisk { uint32_t flags; uint32_t size; uint32_t start; }; struct atag_initrd2 { uint32_t start; uint32_t size; }; struct atag_serialnr { uint32_t low; uint32_t high; }; struct atag_revision { uint32_t rev; }; struct atag_videolfb { unsigned short lfb_width; unsigned short lfb_height; unsigned short lfb_depth; unsigned short lfb_linelength; uint32_t lfb_base; uint32_t lfb_size; unsigned char red_size; unsigned char red_pos; unsigned char green_size; unsigned char green_pos; unsigned char blue_size; unsigned char blue_pos; unsigned char rsvd_size; unsigned char rsvd_pos; }; struct atag_cmdline { char cmdline[1]; // Minimum size. }; struct atag { struct atag_header hdr; union { struct atag_core core; struct atag_mem mem; struct atag_videotext videotext; struct atag_ramdisk ramdisk; struct atag_initrd2 initrd2; struct atag_serialnr serialnr; struct atag_revision revision; struct atag_videolfb videolfb; struct atag_cmdline cmdline; } u; }; /// Bootstrap structure passed to the kernel entry point. struct BootstrapStruct_t { uint32_t flags; uint32_t mem_lower; uint32_t mem_upper; uint32_t boot_device; uint32_t cmdline; uint32_t mods_count; uint32_t mods_addr; /* ELF information */ uint32_t num; uint32_t size; uint32_t addr; uint32_t shndx; uint32_t mmap_length; uint32_t mmap_addr; uint32_t drives_length; uint32_t drives_addr; uint32_t config_table; uint32_t boot_loader_name; uint32_t apm_table; uint32_t vbe_control_info; uint32_t vbe_mode_info; uint32_t vbe_mode; uint32_t vbe_interface_seg; uint32_t vbe_interface_off; uint32_t vbe_interface_len; } __attribute__((packed)); /// \note Page/section references are from the OMAP35xx Technical Reference Manual /** UART/IrDA/CIR Registers */ #define DLL_REG 0x00 // R/W #define RHR_REG 0x00 // R #define THR_REG 0x00 // W #define DLH_REG 0x04 // R/W #define IER_REG 0x04 // R/W #define IIR_REG 0x08 // R #define FCR_REG 0x08 // W #define EFR_REG 0x08 // RW #define LCR_REG 0x0C // RW #define MCR_REG 0x10 // RW #define XON1_ADDR1_REG 0x10 // RW #define LSR_REG 0x14 // R #define XON2_ADDR2_REG 0x14 // RW #define MSR_REG 0x18 // R #define TCR_REG 0x18 // RW #define XOFF1_REG 0x18 // RW #define SPR_REG 0x1C // RW #define TLR_REG 0x1C // RW #define XOFF2_REG 0x1C // RW #define MDR1_REG 0x20 // RW #define MDR2_REG 0x24 // RW #define USAR_REG 0x38 // R #define SCR_REG 0x40 // RW #define SSR_REG 0x44 // R #define MVR_REG 0x50 // R #define SYSC_REG 0x54 // RW #define SYSS_REG 0x58 // R #define WER_REG 0x5C // RW /// Gets a uart MMIO block given a number extern "C" volatile unsigned char *uart_get(int n) { if(n == 1) return uart1; else if(n == 2) return uart2; else if(n == 3) return uart3; else return 0; } /// Perform a software reset of a given UART extern "C" bool uart_softreset(int n) { volatile unsigned char *uart = uart_get(n); if(!uart) return false; /** Reset the UART. Page 2677, section 17.5.1.1.1 **/ // 1. Initiate a software reset uart[SYSC_REG] |= 0x2; // 2. Wait for the end of the reset operation while(!(uart[SYSS_REG] & 0x1)); return true; } /// Configure FIFOs and DMA to default values extern "C" bool uart_fifodefaults(int n) { volatile unsigned char *uart = uart_get(n); if(!uart) return false; /** Configure FIFOs and DMA **/ // 1. Switch to configuration mode B to access the EFR_REG register unsigned char old_lcr_reg = uart[LCR_REG]; uart[LCR_REG] = 0xBF; // 2. Enable submode TCR_TLR to access TLR_REG (part 1 of 2) unsigned char efr_reg = uart[EFR_REG]; unsigned char old_enhanced_en = efr_reg & 0x8; if(!(efr_reg & 0x8)) // Set ENHANCED_EN (bit 4) if not set efr_reg |= 0x8; uart[EFR_REG] = efr_reg; // Write back to the register // 3. Switch to configuration mode A uart[LCR_REG] = 0x80; // 4. Enable submode TCL_TLR to access TLR_REG (part 2 of 2) unsigned char mcr_reg = uart[MCR_REG]; unsigned char old_tcl_tlr = mcr_reg & 0x20; if(!(mcr_reg & 0x20)) mcr_reg |= 0x20; uart[MCR_REG] = mcr_reg; // 5. Enable FIFO, load new FIFO triggers (part 1 of 3), and the new DMA mode (part 1 of 2) uart[FCR_REG] = 1; // TX and RX FIFO triggers at 8 characters, no DMA mode // 6. Switch to configuration mode B to access EFR_REG uart[LCR_REG] = 0xBF; // 7. Load new FIFO triggers (part 2 of 3) uart[TLR_REG] = 0; // 8. Load new FIFO triggers (part 3 of 3) and the new DMA mode (part 2 of 2) uart[SCR_REG] = 0; // 9. Restore the ENHANCED_EN value saved in step 2 if(!old_enhanced_en) uart[EFR_REG] = uart[EFR_REG] ^ 0x8; // 10. Switch to configuration mode A to access the MCR_REG register uart[LCR_REG] = 0x80; // 11. Restore the MCR_REG TCR_TLR value saved in step 4 if(!old_tcl_tlr) uart[MCR_REG] = uart[MCR_REG] ^ 0x20; // 12. Restore the LCR_REG value stored in step 1 uart[LCR_REG] = old_lcr_reg; return true; } /// Configure the UART protocol (to defaults - 115200 baud, 8 character bits, /// no paruart_protoconfigity, 1 stop bit). Will also enable the UART for output as a side /// effect. extern "C" bool uart_protoconfig(int n) { volatile unsigned char *uart = uart_get(n); if(!uart) return false; /** Configure protocol, baud and interrupts **/ // 1. Disable UART to access DLL_REG and DLH_REG uart[MDR1_REG] = (uart[MDR1_REG] & ~0x7) | 0x7; // 2. Switch to configuration mode B to access the EFR_REG register uart[LCR_REG] = 0xBF; // 3. Enable access to IER_REG unsigned char efr_reg = uart[EFR_REG]; unsigned char old_enhanced_en = efr_reg & 0x8; if(!(efr_reg & 0x8)) // Set ENHANCED_EN (bit 4) if not set efr_reg |= 0x8; uart[EFR_REG] = efr_reg; // Write back to the register // 4. Switch to operational mode to access the IER_REG register uart[LCR_REG] = 0; // 5. Clear IER_REG uart[IER_REG] = 0; // 6. Switch to configuration mode B to access DLL_REG and DLH_REG uart[LCR_REG] = 0xBF; // 7. Load the new divisor value (looking for 115200 baud) uart[0x0] = 0x1A; // divisor low byte uart[0x4] = 0; // divisor high byte // 8. Switch to operational mode to access the IER_REG register uart[LCR_REG] = 0; // 9. Load new interrupt configuration uart[IER_REG] = 0; // No interrupts wanted at this stage // 10. Switch to configuration mode B to access the EFR_REG register uart[LCR_REG] = 0xBF; // 11. Restore the ENHANCED_EN value saved in step 3 if(old_enhanced_en) uart[EFR_REG] = uart[EFR_REG] ^ 0x8; // 12. Load the new protocol formatting (parity, stop bit, character length) // and enter operational mode uart[LCR_REG] = 0x3; // 8 bit characters, no parity, one stop bit // 13. Load the new UART mode uart[MDR1_REG] = 0; return true; } /// Completely disable flow control on the UART extern "C" bool uart_disableflowctl(int n) { volatile unsigned char *uart = uart_get(n); if(!uart) return false; /** Configure hardware flow control */ // 1. Switch to configuration mode A to access the MCR_REG register unsigned char old_lcr_reg = uart[LCR_REG]; uart[LCR_REG] = 0x80; // 2. Enable submode TCR_TLR to access TCR_REG (part 1 of 2) unsigned char mcr_reg = uart[MCR_REG]; unsigned char old_tcl_tlr = mcr_reg & 0x20; if(!(mcr_reg & 0x20)) mcr_reg |= 0x20; uart[MCR_REG] = mcr_reg; // 3. Switch to configuration mode B to access the EFR_REG register uart[LCR_REG] = 0xBF; // 4. Enable submode TCR_TLR to access the TCR_REG register (part 2 of 2) unsigned char efr_reg = uart[EFR_REG]; unsigned char old_enhanced_en = efr_reg & 0x8; if(!(efr_reg & 0x8)) // Set ENHANCED_EN (bit 4) if not set efr_reg |= 0x8; uart[EFR_REG] = efr_reg; // Write back to the register // 5. Load new start and halt trigger values uart[TCR_REG] = 0; // 6. Disable RX/TX hardware flow control mode, and restore the ENHANCED_EN // values stored in step 4 uart[EFR_REG] = 0; // 7. Switch to configuration mode A to access MCR_REG uart[LCR_REG] = 0x80; // 8. Restore the MCR_REG TCR_TLR value stored in step 2 if(!old_tcl_tlr) uart[MCR_REG] = uart[MCR_REG] ^ 0x20; // 9. Restore the LCR_REG value saved in step 1 uart[LCR_REG] = old_lcr_reg; return true; } extern "C" void uart_write(int n, char c) { volatile unsigned char *uart = uart_get(n); if(!uart) return; // Wait until the hold register is empty while(!(uart[LSR_REG] & 0x20)); uart[THR_REG] = c; } extern "C" char uart_read(int n) { volatile unsigned char *uart = uart_get(n); if(!uart) return 0; // Wait for data in the receive FIFO while(!(uart[LSR_REG] & 0x1)); return uart[RHR_REG]; } extern "C" inline void writeStr(int n, const char *str) { char c; while ((c = *str++)) uart_write(n, c); } extern "C" void writeHex(int uart, unsigned int n) { bool noZeroes = true; int i; unsigned int tmp; for (i = 28; i > 0; i -= 4) { tmp = (n >> i) & 0xF; if (tmp == 0 && noZeroes) continue; if (tmp >= 0xA) { noZeroes = false; uart_write(uart, tmp-0xA+'a'); } else { noZeroes = false; uart_write(uart, tmp+'0'); } } tmp = n & 0xF; if (tmp >= 0xA) uart_write(uart, tmp-0xA+'a'); else uart_write(uart, tmp+'0'); } /** GPIO implementation for the BeagleBoard */ class BeagleGpio { public: BeagleGpio() {} ~BeagleGpio() {} void initialise() { m_gpio1 = (volatile unsigned int *) 0x48310000; initspecific(1, m_gpio1); m_gpio2 = (volatile unsigned int *) 0x49050000; initspecific(2, m_gpio2); m_gpio3 = (volatile unsigned int *) 0x49052000; initspecific(3, m_gpio3); m_gpio4 = (volatile unsigned int *) 0x49054000; initspecific(4, m_gpio4); m_gpio5 = (volatile unsigned int *) 0x49056000; initspecific(5, m_gpio5); m_gpio6 = (volatile unsigned int *) 0x49058000; initspecific(6, m_gpio6); } void clearpin(int pin) { // Grab the GPIO MMIO range for the pin int base = 0; volatile unsigned int *gpio = getGpioForPin(pin, &base); if(!gpio) { writeStr(3, "BeagleGpio::drivepin : No GPIO found for pin "); writeHex(3, pin); writeStr(3, "!\r\n"); return; } // Write to the CLEARDATAOUT register gpio[0x24] = (1 << base); } void drivepin(int pin) { // Grab the GPIO MMIO range for the pin int base = 0; volatile unsigned int *gpio = getGpioForPin(pin, &base); if(!gpio) { writeStr(3, "BeagleGpio::drivepin : No GPIO found for pin "); writeHex(3, pin); writeStr(3, "!\r\n"); return; } // Write to the SETDATAOUT register. We can set a specific bit in // this register without needing to maintain the state of a full // 32-bit register (zeroes have no effect). gpio[0x25] = (1 << base); } bool pinstate(int pin) { // Grab the GPIO MMIO range for the pin int base = 0; volatile unsigned int *gpio = getGpioForPin(pin, &base); if(!gpio) { writeStr(3, "BeagleGpio::pinstate : No GPIO found for pin "); writeHex(3, pin); writeStr(3, "!\r\n"); return false; } return (gpio[0x25] & (1 << base)); } int capturepin(int pin) { // Grab the GPIO MMIO range for the pin int base = 0; volatile unsigned int *gpio = getGpioForPin(pin, &base); if(!gpio) { writeStr(3, "BeagleGpio::capturepin :No GPIO found for pin "); writeHex(3, pin); writeStr(3, "!\r\n"); return 0; } // Read the data from the pin return (gpio[0xE] & (1 << base)) >> (base ? base - 1 : 0); } void enableoutput(int pin) { // Grab the GPIO MMIO range for the pin int base = 0; volatile unsigned int *gpio = getGpioForPin(pin, &base); if(!gpio) { writeStr(3, "BeagleGpio::enableoutput :No GPIO found for pin "); writeHex(3, pin); writeStr(3, "!\r\n"); return; } // Set the pin as an output (if it's an input, the bit is set) if(gpio[0xD] & (1 << base)) gpio[0xD] ^= (1 << base); } private: /// Initialises a specific GPIO to a given set of defaults void initspecific(int n, volatile unsigned int *gpio) { if(!gpio) return; // Write information about it /// \todo When implementing within Pedigree, we'll have a much nicer /// interface for string manipulation and writing stuff to the /// UART. unsigned int rev = gpio[0]; writeStr(3, "GPIO"); writeHex(3, n); writeStr(3, ": revision "); writeHex(3, (rev & 0xF0) >> 4); writeStr(3, "."); writeHex(3, rev & 0x0F); writeStr(3, " - initialising: "); // 1. Perform a software reset of the GPIO. gpio[0x4] = 2; while(!(gpio[0x5] & 1)); // Poll GPIO_SYSSTATUS, bit 0 // 2. Disable all IRQs gpio[0x7] = 0; // GPIO_IRQENABLE1 gpio[0xB] = 0; // GPIO_IRQENABLE2 // 3. Enable the module gpio[0xC] = 0; // Completed the reset and initialisation. writeStr(3, "Done.\r\n"); } /// Gets the correct GPIO MMIO range for a given GPIO pin. The base /// indicates which bit represents this pin in registers, where relevant volatile unsigned int *getGpioForPin(int pin, int *bit) { volatile unsigned int *gpio = 0; if(pin < 32) { *bit = pin; gpio = m_gpio1; } else if((pin >= 34) && (pin < 64)) { *bit = pin - 34; gpio = m_gpio2; } else if((pin >= 64) && (pin < 96)) { *bit = pin - 64; gpio = m_gpio3; } else if((pin >= 96) && (pin < 128)) { *bit = pin - 96; gpio = m_gpio4; } else if((pin >= 128) && (pin < 160)) { *bit = pin - 128; gpio = m_gpio5; } else if((pin >= 160) && (pin < 192)) { *bit = pin - 160; gpio = m_gpio6; } else gpio = 0; return gpio; } volatile unsigned int *m_gpio1; volatile unsigned int *m_gpio2; volatile unsigned int *m_gpio3; volatile unsigned int *m_gpio4; volatile unsigned int *m_gpio5; volatile unsigned int *m_gpio6; }; /// First level descriptor - roughly equivalent to a page directory entry /// on x86 struct FirstLevelDescriptor { /// Type field for descriptors /// 0 = fault /// 1 = page table /// 2 = section or supersection /// 3 = reserved union { struct { uint32_t type : 2; uint32_t ignore : 30; } PACKED fault; struct { uint32_t type : 2; uint32_t sbz1 : 1; uint32_t ns : 1; uint32_t sbz2 : 1; uint32_t domain : 4; uint32_t imp : 1; uint32_t baseaddr : 22; } PACKED pageTable; struct { uint32_t type : 2; uint32_t b : 1; uint32_t c : 1; uint32_t xn : 1; uint32_t domain : 4; /// extended base address for supersection uint32_t imp : 1; uint32_t ap1 : 2; uint32_t tex : 3; uint32_t ap2 : 1; uint32_t s : 1; uint32_t nG : 1; uint32_t sectiontype : 1; /// = 0 for section, 1 for supersection uint32_t ns : 1; uint32_t base : 12; } PACKED section; uint32_t entry; } descriptor; } PACKED; /// Second level descriptor - roughly equivalent to a page table entry /// on x86 struct SecondLevelDescriptor { /// Type field for descriptors /// 0 = fault /// 1 = large page /// >2 = small page (NX at bit 0) union { struct { uint32_t type : 2; uint32_t ignore : 30; } PACKED fault; struct { uint32_t type : 2; uint32_t b : 1; uint32_t c : 1; uint32_t ap1 : 2; uint32_t sbz : 3; uint32_t ap2 : 1; uint32_t s : 1; uint32_t nG : 1; uint32_t tex : 3; uint32_t xn : 1; uint32_t base : 16; } PACKED largepage; struct { uint32_t type : 2; uint32_t b : 1; uint32_t c : 1; uint32_t ap1 : 2; uint32_t sbz : 3; uint32_t ap2 : 1; uint32_t s : 1; uint32_t nG : 1; uint32_t base : 20; } PACKED smallpage; uint32_t entry; } descriptor; } PACKED; extern "C" void __start(uint32_t r0, uint32_t machineType, struct atag *tagList) { BeagleGpio gpio; bool b = uart_softreset(3); if(!b) while(1); b = uart_fifodefaults(3); if(!b) while(1); b = uart_protoconfig(3); if(!b) while(1); b = uart_disableflowctl(3); if(!b) while(1); writeStr(3, "Pedigree for the BeagleBoard\r\n\r\n"); gpio.initialise(); gpio.enableoutput(149); gpio.enableoutput(150); gpio.drivepin(149); // Switch on the USR1 LED to show we're active and thinking gpio.clearpin(150); writeStr(3, "\r\nPlease press the USER button on the board to continue.\r\n"); while(!gpio.capturepin(7)); writeStr(3, "USER button pressed, continuing...\r\n\r\n"); writeStr(3, "Press 1 to toggle the USR0 LED, and 2 to toggle the USR1 LED.\r\nPress 0 to clear both LEDs. Hit ENTER to boot the kernel.\r\n"); while(1) { char c = uart_read(3); if(c == '1') { writeStr(3, "Toggling USR0 LED\r\n"); if(gpio.pinstate(150)) gpio.clearpin(150); else gpio.drivepin(150); } else if(c == '2') { writeStr(3, "Toggling USR1 LED\r\n"); if(gpio.pinstate(149)) gpio.clearpin(149); else gpio.drivepin(149); } else if(c == '0') { writeStr(3, "Clearing both USR0 and USR1 LEDs\r\n"); gpio.clearpin(149); gpio.clearpin(150); } else if((c == 13) || (c == 10)) break; } #if 0 // Set to 1 to enable the MMU test instead of loading the kernel. writeStr(3, "\r\n\r\nVirtual memory test starting...\r\n"); FirstLevelDescriptor *pdir = (FirstLevelDescriptor*) 0x80100000; memset(pdir, 0, 0x4000); uint32_t base1 = 0x80000000; // Currently running code uint32_t base2 = 0x49000000; // UART3 // First section covers the current code, identity mapped. uint32_t pdir_offset = base1 >> 20; pdir[pdir_offset].descriptor.entry = base1; pdir[pdir_offset].descriptor.section.type = 2; pdir[pdir_offset].descriptor.section.b = 0; pdir[pdir_offset].descriptor.section.c = 0; pdir[pdir_offset].descriptor.section.xn = 0; pdir[pdir_offset].descriptor.section.domain = 0; pdir[pdir_offset].descriptor.section.imp = 0; pdir[pdir_offset].descriptor.section.ap1 = 3; pdir[pdir_offset].descriptor.section.ap2 = 0; pdir[pdir_offset].descriptor.section.tex = 0; pdir[pdir_offset].descriptor.section.s = 1; pdir[pdir_offset].descriptor.section.nG = 0; pdir[pdir_offset].descriptor.section.sectiontype = 0; pdir[pdir_offset].descriptor.section.ns = 0; // Second section covers the UART, identity mapped. pdir_offset = base2 >> 20; pdir[pdir_offset].descriptor.entry = base2; pdir[pdir_offset].descriptor.section.type = 2; pdir[pdir_offset].descriptor.section.b = 0; pdir[pdir_offset].descriptor.section.c = 0; pdir[pdir_offset].descriptor.section.xn = 0; pdir[pdir_offset].descriptor.section.domain = 0; pdir[pdir_offset].descriptor.section.imp = 0; pdir[pdir_offset].descriptor.section.ap1 = 3; pdir[pdir_offset].descriptor.section.ap2 = 0; pdir[pdir_offset].descriptor.section.tex = 0; pdir[pdir_offset].descriptor.section.s = 1; pdir[pdir_offset].descriptor.section.nG = 0; pdir[pdir_offset].descriptor.section.sectiontype = 0; pdir[pdir_offset].descriptor.section.ns = 0; writeStr(3, "Writing to TTBR0 and enabling access to domain 0...\r\n"); asm volatile("MCR p15,0,%0,c2,c0,0" : : "r" (0x80100000)); asm volatile("MCR p15,0,%0,c3,c0,0" : : "r" (0xFFFFFFFF)); // Manager access to all domains for now // Enable the MMU uint32_t sctlr = 0; asm volatile("MRC p15,0,%0,c1,c0,0" : "=r" (sctlr)); if(!(sctlr & 1)) sctlr |= 1; else writeStr(3, "It seems the MMU is already enabled?\r\n"); writeStr(3, "Enabling the MMU...\r\n"); asm volatile("MCR p15,0,%0,c1,c0,0" : : "r" (sctlr)); // If you can see the string, the identity map is complete and working. writeStr(3, "\r\n\r\nTest completed without errors.\r\n"); while(1) { asm volatile("wfi"); } #else writeStr(3, "\r\n\r\nPlease wait while the kernel is loaded...\r\n"); Elf32 elf("kernel"); writeStr(3, "Preparing file... "); elf.load((uint8_t*)file, 0); writeStr(3, "Done!\r\n"); writeStr(3, "Loading file into memory (please wait) "); elf.writeSections(); writeStr(3, " Done!\r\n"); int (*main)(struct BootstrapStruct_t*) = (int (*)(struct BootstrapStruct_t*)) elf.getEntryPoint(); struct BootstrapStruct_t *bs = reinterpret_cast<struct BootstrapStruct_t *>(0x80008000); writeStr(3, "Creating bootstrap information structure... "); memset(bs, 0, sizeof(bs)); bs->shndx = elf.m_pHeader->shstrndx; bs->num = elf.m_pHeader->shnum; bs->size = elf.m_pHeader->shentsize; bs->addr = (unsigned int)elf.m_pSectionHeaders; // Repurpose these variables a little.... bs->mods_addr = reinterpret_cast<uint32_t>(elf.m_pBuffer); bs->mods_count = (sizeof file) + 0x1000; // For every section header, set .addr = .offset + m_pBuffer. for (int i = 0; i < elf.m_pHeader->shnum; i++) { elf.m_pSectionHeaders[i].addr = elf.m_pSectionHeaders[i].offset + (uint32_t)elf.m_pBuffer; } writeStr(3, "Done!\r\n"); // Just before running the kernel proper, turn off both LEDs so we can use // their states for debugging the kernel. gpio.clearpin(149); gpio.clearpin(150); // Run the kernel, finally writeStr(3, "Now starting the Pedigree kernel (can take a while, please wait).\r\n\r\n"); main(bs); #endif while (1) { asm volatile("wfi"); } }
jmolloy/pedigree
src/system/boot/arm/main_beagle.cc
C++
isc
26,018
/** * QUnit v1.3.0pre - A JavaScript Unit Testing Framework * * http://docs.jquery.com/QUnit * * Copyright (c) 2011 John Resig, Jörn Zaefferer * Dual licensed under the MIT (MIT-LICENSE.txt) * or GPL (GPL-LICENSE.txt) licenses. * Pulled Live from Git Sat Jan 14 01:10:01 UTC 2012 * Last Commit: 0712230bb203c262211649b32bd712ec7df5f857 */ (function(window) { var defined = { setTimeout: typeof window.setTimeout !== "undefined", sessionStorage: (function() { try { return !!sessionStorage.getItem; } catch(e) { return false; } })() }; var testId = 0, toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty; var Test = function(name, testName, expected, testEnvironmentArg, async, callback) { this.name = name; this.testName = testName; this.expected = expected; this.testEnvironmentArg = testEnvironmentArg; this.async = async; this.callback = callback; this.assertions = []; }; Test.prototype = { init: function() { var tests = id("qunit-tests"); if (tests) { var b = document.createElement("strong"); b.innerHTML = "Running " + this.name; var li = document.createElement("li"); li.appendChild( b ); li.className = "running"; li.id = this.id = "test-output" + testId++; tests.appendChild( li ); } }, setup: function() { if (this.module != config.previousModule) { if ( config.previousModule ) { runLoggingCallbacks('moduleDone', QUnit, { name: config.previousModule, failed: config.moduleStats.bad, passed: config.moduleStats.all - config.moduleStats.bad, total: config.moduleStats.all } ); } config.previousModule = this.module; config.moduleStats = { all: 0, bad: 0 }; runLoggingCallbacks( 'moduleStart', QUnit, { name: this.module } ); } config.current = this; this.testEnvironment = extend({ setup: function() {}, teardown: function() {} }, this.moduleTestEnvironment); if (this.testEnvironmentArg) { extend(this.testEnvironment, this.testEnvironmentArg); } runLoggingCallbacks( 'testStart', QUnit, { name: this.testName, module: this.module }); // allow utility functions to access the current test environment // TODO why?? QUnit.current_testEnvironment = this.testEnvironment; try { if ( !config.pollution ) { saveGlobal(); } this.testEnvironment.setup.call(this.testEnvironment); } catch(e) { QUnit.ok( false, "Setup failed on " + this.testName + ": " + e.message ); } }, run: function() { config.current = this; if ( this.async ) { QUnit.stop(); } if ( config.notrycatch ) { this.callback.call(this.testEnvironment); return; } try { this.callback.call(this.testEnvironment); } catch(e) { fail("Test " + this.testName + " died, exception and test follows", e, this.callback); QUnit.ok( false, "Died on test #" + (this.assertions.length + 1) + ": " + e.message + " - " + QUnit.jsDump.parse(e) ); // else next test will carry the responsibility saveGlobal(); // Restart the tests if they're blocking if ( config.blocking ) { QUnit.start(); } } }, teardown: function() { config.current = this; try { this.testEnvironment.teardown.call(this.testEnvironment); checkPollution(); } catch(e) { QUnit.ok( false, "Teardown failed on " + this.testName + ": " + e.message ); } }, finish: function() { config.current = this; if ( this.expected != null && this.expected != this.assertions.length ) { QUnit.ok( false, "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run" ); } var good = 0, bad = 0, tests = id("qunit-tests"); config.stats.all += this.assertions.length; config.moduleStats.all += this.assertions.length; if ( tests ) { var ol = document.createElement("ol"); for ( var i = 0; i < this.assertions.length; i++ ) { var assertion = this.assertions[i]; var li = document.createElement("li"); li.className = assertion.result ? "pass" : "fail"; li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed"); ol.appendChild( li ); if ( assertion.result ) { good++; } else { bad++; config.stats.bad++; config.moduleStats.bad++; } } // store result when possible if ( QUnit.config.reorder && defined.sessionStorage ) { if (bad) { sessionStorage.setItem("qunit-" + this.module + "-" + this.testName, bad); } else { sessionStorage.removeItem("qunit-" + this.module + "-" + this.testName); } } if (bad == 0) { ol.style.display = "none"; } var b = document.createElement("strong"); b.innerHTML = this.name + " <b class='counts'>(<b class='failed'>" + bad + "</b>, <b class='passed'>" + good + "</b>, " + this.assertions.length + ")</b>"; var a = document.createElement("a"); a.innerHTML = "Rerun"; a.href = QUnit.url({ filter: getText([b]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") }); addEvent(b, "click", function() { var next = b.nextSibling.nextSibling, display = next.style.display; next.style.display = display === "none" ? "block" : "none"; }); addEvent(b, "dblclick", function(e) { var target = e && e.target ? e.target : window.event.srcElement; if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) { target = target.parentNode; } if ( window.location && target.nodeName.toLowerCase() === "strong" ) { window.location = QUnit.url({ filter: getText([target]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") }); } }); var li = id(this.id); li.className = bad ? "fail" : "pass"; li.removeChild( li.firstChild ); li.appendChild( b ); li.appendChild( a ); li.appendChild( ol ); } else { for ( var i = 0; i < this.assertions.length; i++ ) { if ( !this.assertions[i].result ) { bad++; config.stats.bad++; config.moduleStats.bad++; } } } try { QUnit.reset(); } catch(e) { fail("reset() failed, following Test " + this.testName + ", exception and reset fn follows", e, QUnit.reset); } runLoggingCallbacks( 'testDone', QUnit, { name: this.testName, module: this.module, failed: bad, passed: this.assertions.length - bad, total: this.assertions.length } ); }, queue: function() { var test = this; synchronize(function() { test.init(); }); function run() { // each of these can by async synchronize(function() { test.setup(); }); synchronize(function() { test.run(); }); synchronize(function() { test.teardown(); }); synchronize(function() { test.finish(); }); } // defer when previous test run passed, if storage is available var bad = QUnit.config.reorder && defined.sessionStorage && +sessionStorage.getItem("qunit-" + this.module + "-" + this.testName); if (bad) { run(); } else { synchronize(run, true); }; } }; var QUnit = { // call on start of module test to prepend name to all tests module: function(name, testEnvironment) { config.currentModule = name; config.currentModuleTestEnviroment = testEnvironment; }, asyncTest: function(testName, expected, callback) { if ( arguments.length === 2 ) { callback = expected; expected = null; } QUnit.test(testName, expected, callback, true); }, test: function(testName, expected, callback, async) { var name = '<span class="test-name">' + escapeInnerText(testName) + '</span>', testEnvironmentArg; if ( arguments.length === 2 ) { callback = expected; expected = null; } // is 2nd argument a testEnvironment? if ( expected && typeof expected === 'object') { testEnvironmentArg = expected; expected = null; } if ( config.currentModule ) { name = '<span class="module-name">' + config.currentModule + "</span>: " + name; } if ( !validTest(config.currentModule + ": " + testName) ) { return; } var test = new Test(name, testName, expected, testEnvironmentArg, async, callback); test.module = config.currentModule; test.moduleTestEnvironment = config.currentModuleTestEnviroment; test.queue(); }, /** * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through. */ expect: function(asserts) { config.current.expected = asserts; }, /** * Asserts true. * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); */ ok: function(a, msg) { a = !!a; var details = { result: a, message: msg }; msg = escapeInnerText(msg); runLoggingCallbacks( 'log', QUnit, details ); config.current.assertions.push({ result: a, message: msg }); }, /** * Checks that the first two arguments are equal, with an optional message. * Prints out both actual and expected values. * * Prefered to ok( actual == expected, message ) * * @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." ); * * @param Object actual * @param Object expected * @param String message (optional) */ equal: function(actual, expected, message) { QUnit.push(expected == actual, actual, expected, message); }, notEqual: function(actual, expected, message) { QUnit.push(expected != actual, actual, expected, message); }, deepEqual: function(actual, expected, message) { QUnit.push(QUnit.equiv(actual, expected), actual, expected, message); }, notDeepEqual: function(actual, expected, message) { QUnit.push(!QUnit.equiv(actual, expected), actual, expected, message); }, strictEqual: function(actual, expected, message) { QUnit.push(expected === actual, actual, expected, message); }, notStrictEqual: function(actual, expected, message) { QUnit.push(expected !== actual, actual, expected, message); }, raises: function(block, expected, message) { var actual, ok = false; if (typeof expected === 'string') { message = expected; expected = null; } try { block(); } catch (e) { actual = e; } if (actual) { // we don't want to validate thrown error if (!expected) { ok = true; // expected is a regexp } else if (QUnit.objectType(expected) === "regexp") { ok = expected.test(actual); // expected is a constructor } else if (actual instanceof expected) { ok = true; // expected is a validation function which returns true is validation passed } else if (expected.call({}, actual) === true) { ok = true; } } QUnit.ok(ok, message); }, start: function(count) { config.semaphore -= count || 1; if (config.semaphore > 0) { // don't start until equal number of stop-calls return; } if (config.semaphore < 0) { // ignore if start is called more often then stop config.semaphore = 0; } // A slight delay, to avoid any current callbacks if ( defined.setTimeout ) { window.setTimeout(function() { if (config.semaphore > 0) { return; } if ( config.timeout ) { clearTimeout(config.timeout); } config.blocking = false; process(true); }, 13); } else { config.blocking = false; process(true); } }, stop: function(count) { config.semaphore += count || 1; config.blocking = true; if ( config.testTimeout && defined.setTimeout ) { clearTimeout(config.timeout); config.timeout = window.setTimeout(function() { QUnit.ok( false, "Test timed out" ); config.semaphore = 1; QUnit.start(); }, config.testTimeout); } } }; //We want access to the constructor's prototype (function() { function F(){}; F.prototype = QUnit; QUnit = new F(); //Make F QUnit's constructor so that we can add to the prototype later QUnit.constructor = F; })(); // Backwards compatibility, deprecated QUnit.equals = QUnit.equal; QUnit.same = QUnit.deepEqual; // Maintain internal state var config = { // The queue of tests to run queue: [], // block until document ready blocking: true, // when enabled, show only failing tests // gets persisted through sessionStorage and can be changed in UI via checkbox hidepassed: false, // by default, run previously failed tests first // very useful in combination with "Hide passed tests" checked reorder: true, // by default, modify document.title when suite is done altertitle: true, urlConfig: ['noglobals', 'notrycatch'], //logging callback queues begin: [], done: [], log: [], testStart: [], testDone: [], moduleStart: [], moduleDone: [] }; // Load paramaters (function() { var location = window.location || { search: "", protocol: "file:" }, params = location.search.slice( 1 ).split( "&" ), length = params.length, urlParams = {}, current; if ( params[ 0 ] ) { for ( var i = 0; i < length; i++ ) { current = params[ i ].split( "=" ); current[ 0 ] = decodeURIComponent( current[ 0 ] ); // allow just a key to turn on a flag, e.g., test.html?noglobals current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true; urlParams[ current[ 0 ] ] = current[ 1 ]; } } QUnit.urlParams = urlParams; config.filter = urlParams.filter; // Figure out if we're running the tests from a server or not QUnit.isLocal = !!(location.protocol === 'file:'); })(); // Expose the API as global variables, unless an 'exports' // object exists, in that case we assume we're in CommonJS if ( typeof exports === "undefined" || typeof require === "undefined" ) { extend(window, QUnit); window.QUnit = QUnit; } else { extend(exports, QUnit); exports.QUnit = QUnit; } // define these after exposing globals to keep them in these QUnit namespace only extend(QUnit, { config: config, // Initialize the configuration options init: function() { extend(config, { stats: { all: 0, bad: 0 }, moduleStats: { all: 0, bad: 0 }, started: +new Date, updateRate: 1000, blocking: false, autostart: true, autorun: false, filter: "", queue: [], semaphore: 0 }); var tests = id( "qunit-tests" ), banner = id( "qunit-banner" ), result = id( "qunit-testresult" ); if ( tests ) { tests.innerHTML = ""; } if ( banner ) { banner.className = ""; } if ( result ) { result.parentNode.removeChild( result ); } if ( tests ) { result = document.createElement( "p" ); result.id = "qunit-testresult"; result.className = "result"; tests.parentNode.insertBefore( result, tests ); result.innerHTML = 'Running...<br/>&nbsp;'; } }, /** * Resets the test setup. Useful for tests that modify the DOM. * * If jQuery is available, uses jQuery's html(), otherwise just innerHTML. */ reset: function() { if ( window.jQuery ) { jQuery( "#qunit-fixture" ).html( config.fixture ); } else { var main = id( 'qunit-fixture' ); if ( main ) { main.innerHTML = config.fixture; } } }, /** * Trigger an event on an element. * * @example triggerEvent( document.body, "click" ); * * @param DOMElement elem * @param String type */ triggerEvent: function( elem, type, event ) { if ( document.createEvent ) { event = document.createEvent("MouseEvents"); event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, null); elem.dispatchEvent( event ); } else if ( elem.fireEvent ) { elem.fireEvent("on"+type); } }, // Safe object type checking is: function( type, obj ) { return QUnit.objectType( obj ) == type; }, objectType: function( obj ) { if (typeof obj === "undefined") { return "undefined"; // consider: typeof null === object } if (obj === null) { return "null"; } var type = toString.call( obj ).match(/^\[object\s(.*)\]$/)[1] || ''; switch (type) { case 'Number': if (isNaN(obj)) { return "nan"; } else { return "number"; } case 'String': case 'Boolean': case 'Array': case 'Date': case 'RegExp': case 'Function': return type.toLowerCase(); } if (typeof obj === "object") { return "object"; } return undefined; }, push: function(result, actual, expected, message) { var details = { result: result, message: message, actual: actual, expected: expected }; message = escapeInnerText(message) || (result ? "okay" : "failed"); message = '<span class="test-message">' + message + "</span>"; expected = escapeInnerText(QUnit.jsDump.parse(expected)); actual = escapeInnerText(QUnit.jsDump.parse(actual)); var output = message + '<table><tr class="test-expected"><th>Expected: </th><td><pre>' + expected + '</pre></td></tr>'; if (actual != expected) { output += '<tr class="test-actual"><th>Result: </th><td><pre>' + actual + '</pre></td></tr>'; output += '<tr class="test-diff"><th>Diff: </th><td><pre>' + QUnit.diff(expected, actual) +'</pre></td></tr>'; } if (!result) { var source = sourceFromStacktrace(); if (source) { details.source = source; output += '<tr class="test-source"><th>Source: </th><td><pre>' + escapeInnerText(source) + '</pre></td></tr>'; } } output += "</table>"; runLoggingCallbacks( 'log', QUnit, details ); config.current.assertions.push({ result: !!result, message: output }); }, url: function( params ) { params = extend( extend( {}, QUnit.urlParams ), params ); var querystring = "?", key; for ( key in params ) { if ( !hasOwn.call( params, key ) ) { continue; } querystring += encodeURIComponent( key ) + "=" + encodeURIComponent( params[ key ] ) + "&"; } return window.location.pathname + querystring.slice( 0, -1 ); }, extend: extend, id: id, addEvent: addEvent }); //QUnit.constructor is set to the empty F() above so that we can add to it's prototype later //Doing this allows us to tell if the following methods have been overwritten on the actual //QUnit object, which is a deprecated way of using the callbacks. extend(QUnit.constructor.prototype, { // Logging callbacks; all receive a single argument with the listed properties // run test/logs.html for any related changes begin: registerLoggingCallback('begin'), // done: { failed, passed, total, runtime } done: registerLoggingCallback('done'), // log: { result, actual, expected, message } log: registerLoggingCallback('log'), // testStart: { name } testStart: registerLoggingCallback('testStart'), // testDone: { name, failed, passed, total } testDone: registerLoggingCallback('testDone'), // moduleStart: { name } moduleStart: registerLoggingCallback('moduleStart'), // moduleDone: { name, failed, passed, total } moduleDone: registerLoggingCallback('moduleDone') }); if ( typeof document === "undefined" || document.readyState === "complete" ) { config.autorun = true; } QUnit.load = function() { runLoggingCallbacks( 'begin', QUnit, {} ); // Initialize the config, saving the execution queue var oldconfig = extend({}, config); QUnit.init(); extend(config, oldconfig); config.blocking = false; var urlConfigHtml = '', len = config.urlConfig.length; for ( var i = 0, val; i < len, val = config.urlConfig[i]; i++ ) { config[val] = QUnit.urlParams[val]; urlConfigHtml += '<label><input name="' + val + '" type="checkbox"' + ( config[val] ? ' checked="checked"' : '' ) + '>' + val + '</label>'; } var userAgent = id("qunit-userAgent"); if ( userAgent ) { userAgent.innerHTML = navigator.userAgent; } var banner = id("qunit-header"); if ( banner ) { banner.innerHTML = '<a href="' + QUnit.url({ filter: undefined }) + '"> ' + banner.innerHTML + '</a> ' + urlConfigHtml; addEvent( banner, "change", function( event ) { var params = {}; params[ event.target.name ] = event.target.checked ? true : undefined; window.location = QUnit.url( params ); }); } var toolbar = id("qunit-testrunner-toolbar"); if ( toolbar ) { var filter = document.createElement("input"); filter.type = "checkbox"; filter.id = "qunit-filter-pass"; addEvent( filter, "click", function() { var ol = document.getElementById("qunit-tests"); if ( filter.checked ) { ol.className = ol.className + " hidepass"; } else { var tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " "; ol.className = tmp.replace(/ hidepass /, " "); } if ( defined.sessionStorage ) { if (filter.checked) { sessionStorage.setItem("qunit-filter-passed-tests", "true"); } else { sessionStorage.removeItem("qunit-filter-passed-tests"); } } }); if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem("qunit-filter-passed-tests") ) { filter.checked = true; var ol = document.getElementById("qunit-tests"); ol.className = ol.className + " hidepass"; } toolbar.appendChild( filter ); var label = document.createElement("label"); label.setAttribute("for", "qunit-filter-pass"); label.innerHTML = "Hide passed tests"; toolbar.appendChild( label ); } var main = id('qunit-fixture'); if ( main ) { config.fixture = main.innerHTML; } if (config.autostart) { QUnit.start(); } }; addEvent(window, "load", QUnit.load); // addEvent(window, "error") gives us a useless event object window.onerror = function( message, file, line ) { if ( QUnit.config.current ) { ok( false, message + ", " + file + ":" + line ); } else { test( "global failure", function() { ok( false, message + ", " + file + ":" + line ); }); } }; function done() { config.autorun = true; // Log the last module results if ( config.currentModule ) { runLoggingCallbacks( 'moduleDone', QUnit, { name: config.currentModule, failed: config.moduleStats.bad, passed: config.moduleStats.all - config.moduleStats.bad, total: config.moduleStats.all } ); } var banner = id("qunit-banner"), tests = id("qunit-tests"), runtime = +new Date - config.started, passed = config.stats.all - config.stats.bad, html = [ 'Tests completed in ', runtime, ' milliseconds.<br/>', '<span class="passed">', passed, '</span> tests of <span class="total">', config.stats.all, '</span> passed, <span class="failed">', config.stats.bad, '</span> failed.' ].join(''); if ( banner ) { banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass"); } if ( tests ) { id( "qunit-testresult" ).innerHTML = html; } if ( config.altertitle && typeof document !== "undefined" && document.title ) { // show ✖ for good, ✔ for bad suite result in title // use escape sequences in case file gets loaded with non-utf-8-charset document.title = [ (config.stats.bad ? "\u2716" : "\u2714"), document.title.replace(/^[\u2714\u2716] /i, "") ].join(" "); } runLoggingCallbacks( 'done', QUnit, { failed: config.stats.bad, passed: passed, total: config.stats.all, runtime: runtime } ); } function validTest( name ) { var filter = config.filter, run = false; if ( !filter ) { return true; } var not = filter.charAt( 0 ) === "!"; if ( not ) { filter = filter.slice( 1 ); } if ( name.indexOf( filter ) !== -1 ) { return !not; } if ( not ) { run = true; } return run; } // so far supports only Firefox, Chrome and Opera (buggy) // could be extended in the future to use something like https://github.com/csnover/TraceKit function sourceFromStacktrace() { try { throw new Error(); } catch ( e ) { if (e.stacktrace) { // Opera return e.stacktrace.split("\n")[6]; } else if (e.stack) { // Firefox, Chrome return e.stack.split("\n")[4]; } else if (e.sourceURL) { // Safari, PhantomJS // TODO sourceURL points at the 'throw new Error' line above, useless //return e.sourceURL + ":" + e.line; } } } function escapeInnerText(s) { if (!s) { return ""; } s = s + ""; return s.replace(/[\&<>]/g, function(s) { switch(s) { case "&": return "&amp;"; case "<": return "&lt;"; case ">": return "&gt;"; default: return s; } }); } function synchronize( callback, last ) { config.queue.push( callback ); if ( config.autorun && !config.blocking ) { process(last); } } function process( last ) { var start = new Date().getTime(); config.depth = config.depth ? config.depth + 1 : 1; while ( config.queue.length && !config.blocking ) { if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) { config.queue.shift()(); } else { window.setTimeout( function(){ process( last ); }, 13 ); break; } } config.depth--; if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) { done(); } } function saveGlobal() { config.pollution = []; if ( config.noglobals ) { for ( var key in window ) { if ( !hasOwn.call( window, key ) ) { continue; } config.pollution.push( key ); } } } function checkPollution( name ) { var old = config.pollution; saveGlobal(); var newGlobals = diff( config.pollution, old ); if ( newGlobals.length > 0 ) { ok( false, "Introduced global variable(s): " + newGlobals.join(", ") ); } var deletedGlobals = diff( old, config.pollution ); if ( deletedGlobals.length > 0 ) { ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") ); } } // returns a new Array with the elements that are in a but not in b function diff( a, b ) { var result = a.slice(); for ( var i = 0; i < result.length; i++ ) { for ( var j = 0; j < b.length; j++ ) { if ( result[i] === b[j] ) { result.splice(i, 1); i--; break; } } } return result; } function fail(message, exception, callback) { if ( typeof console !== "undefined" && console.error && console.warn ) { console.error(message); console.error(exception); console.error(exception.stack); console.warn(callback.toString()); } else if ( window.opera && opera.postError ) { opera.postError(message, exception, callback.toString); } } function extend(a, b) { for ( var prop in b ) { if ( b[prop] === undefined ) { delete a[prop]; // Avoid "Member not found" error in IE8 caused by setting window.constructor } else if ( prop !== "constructor" || a !== window ) { a[prop] = b[prop]; } } return a; } function addEvent(elem, type, fn) { if ( elem.addEventListener ) { elem.addEventListener( type, fn, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, fn ); } else { fn(); } } function id(name) { return !!(typeof document !== "undefined" && document && document.getElementById) && document.getElementById( name ); } function registerLoggingCallback(key){ return function(callback){ config[key].push( callback ); }; } // Supports deprecated method of completely overwriting logging callbacks function runLoggingCallbacks(key, scope, args) { //debugger; var callbacks; if ( QUnit.hasOwnProperty(key) ) { QUnit[key].call(scope, args); } else { callbacks = config[key]; for( var i = 0; i < callbacks.length; i++ ) { callbacks[i].call( scope, args ); } } } // Test for equality any JavaScript type. // Author: Philippe Rathé <prathe@gmail.com> QUnit.equiv = function () { var innerEquiv; // the real equiv function var callers = []; // stack to decide between skip/abort functions var parents = []; // stack to avoiding loops from circular referencing // Call the o related callback with the given arguments. function bindCallbacks(o, callbacks, args) { var prop = QUnit.objectType(o); if (prop) { if (QUnit.objectType(callbacks[prop]) === "function") { return callbacks[prop].apply(callbacks, args); } else { return callbacks[prop]; // or undefined } } } var getProto = Object.getPrototypeOf || function (obj) { return obj.__proto__; }; var callbacks = function () { // for string, boolean, number and null function useStrictEquality(b, a) { if (b instanceof a.constructor || a instanceof b.constructor) { // to catch short annotaion VS 'new' annotation of a // declaration // e.g. var i = 1; // var j = new Number(1); return a == b; } else { return a === b; } } return { "string" : useStrictEquality, "boolean" : useStrictEquality, "number" : useStrictEquality, "null" : useStrictEquality, "undefined" : useStrictEquality, "nan" : function(b) { return isNaN(b); }, "date" : function(b, a) { return QUnit.objectType(b) === "date" && a.valueOf() === b.valueOf(); }, "regexp" : function(b, a) { return QUnit.objectType(b) === "regexp" && a.source === b.source && // the regex itself a.global === b.global && // and its modifers // (gmi) ... a.ignoreCase === b.ignoreCase && a.multiline === b.multiline; }, // - skip when the property is a method of an instance (OOP) // - abort otherwise, // initial === would have catch identical references anyway "function" : function() { var caller = callers[callers.length - 1]; return caller !== Object && typeof caller !== "undefined"; }, "array" : function(b, a) { var i, j, loop; var len; // b could be an object literal here if (!(QUnit.objectType(b) === "array")) { return false; } len = a.length; if (len !== b.length) { // safe and faster return false; } // track reference to avoid circular references parents.push(a); for (i = 0; i < len; i++) { loop = false; for (j = 0; j < parents.length; j++) { if (parents[j] === a[i]) { loop = true;// dont rewalk array } } if (!loop && !innerEquiv(a[i], b[i])) { parents.pop(); return false; } } parents.pop(); return true; }, "object" : function(b, a) { var i, j, loop; var eq = true; // unless we can proove it var aProperties = [], bProperties = []; // collection of // strings // comparing constructors is more strict than using // instanceof if (a.constructor !== b.constructor) { // Allow objects with no prototype to be equivalent to // objects with Object as their constructor. if (!((getProto(a) === null && getProto(b) === Object.prototype) || (getProto(b) === null && getProto(a) === Object.prototype))) { return false; } } // stack constructor before traversing properties callers.push(a.constructor); // track reference to avoid circular references parents.push(a); for (i in a) { // be strict: don't ensures hasOwnProperty // and go deep loop = false; for (j = 0; j < parents.length; j++) { if (parents[j] === a[i]) loop = true; // don't go down the same path // twice } aProperties.push(i); // collect a's properties if (!loop && !innerEquiv(a[i], b[i])) { eq = false; break; } } callers.pop(); // unstack, we are done parents.pop(); for (i in b) { bProperties.push(i); // collect b's properties } // Ensures identical properties name return eq && innerEquiv(aProperties.sort(), bProperties .sort()); } }; }(); innerEquiv = function() { // can take multiple arguments var args = Array.prototype.slice.apply(arguments); if (args.length < 2) { return true; // end transition } return (function(a, b) { if (a === b) { return true; // catch the most you can } else if (a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || QUnit.objectType(a) !== QUnit.objectType(b)) { return false; // don't lose time with error prone cases } else { return bindCallbacks(a, callbacks, [ b, a ]); } // apply transition with (1..n) arguments })(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length - 1)); }; return innerEquiv; }(); /** * jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | * http://flesler.blogspot.com Licensed under BSD * (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008 * * @projectDescription Advanced and extensible data dumping for Javascript. * @version 1.0.0 * @author Ariel Flesler * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html} */ QUnit.jsDump = (function() { function quote( str ) { return '"' + str.toString().replace(/"/g, '\\"') + '"'; }; function literal( o ) { return o + ''; }; function join( pre, arr, post ) { var s = jsDump.separator(), base = jsDump.indent(), inner = jsDump.indent(1); if ( arr.join ) arr = arr.join( ',' + s + inner ); if ( !arr ) return pre + post; return [ pre, inner + arr, base + post ].join(s); }; function array( arr, stack ) { var i = arr.length, ret = Array(i); this.up(); while ( i-- ) ret[i] = this.parse( arr[i] , undefined , stack); this.down(); return join( '[', ret, ']' ); }; var reName = /^function (\w+)/; var jsDump = { parse:function( obj, type, stack ) { //type is used mostly internally, you can fix a (custom)type in advance stack = stack || [ ]; var parser = this.parsers[ type || this.typeOf(obj) ]; type = typeof parser; var inStack = inArray(obj, stack); if (inStack != -1) { return 'recursion('+(inStack - stack.length)+')'; } //else if (type == 'function') { stack.push(obj); var res = parser.call( this, obj, stack ); stack.pop(); return res; } // else return (type == 'string') ? parser : this.parsers.error; }, typeOf:function( obj ) { var type; if ( obj === null ) { type = "null"; } else if (typeof obj === "undefined") { type = "undefined"; } else if (QUnit.is("RegExp", obj)) { type = "regexp"; } else if (QUnit.is("Date", obj)) { type = "date"; } else if (QUnit.is("Function", obj)) { type = "function"; } else if (typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined") { type = "window"; } else if (obj.nodeType === 9) { type = "document"; } else if (obj.nodeType) { type = "node"; } else if ( // native arrays toString.call( obj ) === "[object Array]" || // NodeList objects ( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) ) ) { type = "array"; } else { type = typeof obj; } return type; }, separator:function() { return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? '&nbsp;' : ' '; }, indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing if ( !this.multiline ) return ''; var chr = this.indentChar; if ( this.HTML ) chr = chr.replace(/\t/g,' ').replace(/ /g,'&nbsp;'); return Array( this._depth_ + (extra||0) ).join(chr); }, up:function( a ) { this._depth_ += a || 1; }, down:function( a ) { this._depth_ -= a || 1; }, setParser:function( name, parser ) { this.parsers[name] = parser; }, // The next 3 are exposed so you can use them quote:quote, literal:literal, join:join, // _depth_: 1, // This is the list of parsers, to modify them, use jsDump.setParser parsers:{ window: '[Window]', document: '[Document]', error:'[ERROR]', //when no parser is found, shouldn't happen unknown: '[Unknown]', 'null':'null', 'undefined':'undefined', 'function':function( fn ) { var ret = 'function', name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE if ( name ) ret += ' ' + name; ret += '('; ret = [ ret, QUnit.jsDump.parse( fn, 'functionArgs' ), '){'].join(''); return join( ret, QUnit.jsDump.parse(fn,'functionCode'), '}' ); }, array: array, nodelist: array, arguments: array, object:function( map, stack ) { var ret = [ ]; QUnit.jsDump.up(); for ( var key in map ) { var val = map[key]; ret.push( QUnit.jsDump.parse(key,'key') + ': ' + QUnit.jsDump.parse(val, undefined, stack)); } QUnit.jsDump.down(); return join( '{', ret, '}' ); }, node:function( node ) { var open = QUnit.jsDump.HTML ? '&lt;' : '<', close = QUnit.jsDump.HTML ? '&gt;' : '>'; var tag = node.nodeName.toLowerCase(), ret = open + tag; for ( var a in QUnit.jsDump.DOMAttrs ) { var val = node[QUnit.jsDump.DOMAttrs[a]]; if ( val ) ret += ' ' + a + '=' + QUnit.jsDump.parse( val, 'attribute' ); } return ret + close + open + '/' + tag + close; }, functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function var l = fn.length; if ( !l ) return ''; var args = Array(l); while ( l-- ) args[l] = String.fromCharCode(97+l);//97 is 'a' return ' ' + args.join(', ') + ' '; }, key:quote, //object calls it internally, the key part of an item in a map functionCode:'[code]', //function calls it internally, it's the content of the function attribute:quote, //node calls it internally, it's an html attribute value string:quote, date:quote, regexp:literal, //regex number:literal, 'boolean':literal }, DOMAttrs:{//attributes to dump from nodes, name=>realName id:'id', name:'name', 'class':'className' }, HTML:false,//if true, entities are escaped ( <, >, \t, space and \n ) indentChar:' ',//indentation unit multiline:true //if true, items in a collection, are separated by a \n, else just a space. }; return jsDump; })(); // from Sizzle.js function getText( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += getText( elem.childNodes ); } } return ret; }; //from jquery.js function inArray( elem, array ) { if ( array.indexOf ) { return array.indexOf( elem ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === elem ) { return i; } } return -1; } /* * Javascript Diff Algorithm * By John Resig (http://ejohn.org/) * Modified by Chu Alan "sprite" * * Released under the MIT license. * * More Info: * http://ejohn.org/projects/javascript-diff-algorithm/ * * Usage: QUnit.diff(expected, actual) * * QUnit.diff("the quick brown fox jumped over", "the quick fox jumps over") == "the quick <del>brown </del> fox <del>jumped </del><ins>jumps </ins> over" */ QUnit.diff = (function() { function diff(o, n) { var ns = {}; var os = {}; for (var i = 0; i < n.length; i++) { if (ns[n[i]] == null) ns[n[i]] = { rows: [], o: null }; ns[n[i]].rows.push(i); } for (var i = 0; i < o.length; i++) { if (os[o[i]] == null) os[o[i]] = { rows: [], n: null }; os[o[i]].rows.push(i); } for (var i in ns) { if ( !hasOwn.call( ns, i ) ) { continue; } if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) { n[ns[i].rows[0]] = { text: n[ns[i].rows[0]], row: os[i].rows[0] }; o[os[i].rows[0]] = { text: o[os[i].rows[0]], row: ns[i].rows[0] }; } } for (var i = 0; i < n.length - 1; i++) { if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null && n[i + 1] == o[n[i].row + 1]) { n[i + 1] = { text: n[i + 1], row: n[i].row + 1 }; o[n[i].row + 1] = { text: o[n[i].row + 1], row: i + 1 }; } } for (var i = n.length - 1; i > 0; i--) { if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null && n[i - 1] == o[n[i].row - 1]) { n[i - 1] = { text: n[i - 1], row: n[i].row - 1 }; o[n[i].row - 1] = { text: o[n[i].row - 1], row: i - 1 }; } } return { o: o, n: n }; } return function(o, n) { o = o.replace(/\s+$/, ''); n = n.replace(/\s+$/, ''); var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/)); var str = ""; var oSpace = o.match(/\s+/g); if (oSpace == null) { oSpace = [" "]; } else { oSpace.push(" "); } var nSpace = n.match(/\s+/g); if (nSpace == null) { nSpace = [" "]; } else { nSpace.push(" "); } if (out.n.length == 0) { for (var i = 0; i < out.o.length; i++) { str += '<del>' + out.o[i] + oSpace[i] + "</del>"; } } else { if (out.n[0].text == null) { for (n = 0; n < out.o.length && out.o[n].text == null; n++) { str += '<del>' + out.o[n] + oSpace[n] + "</del>"; } } for (var i = 0; i < out.n.length; i++) { if (out.n[i].text == null) { str += '<ins>' + out.n[i] + nSpace[i] + "</ins>"; } else { var pre = ""; for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) { pre += '<del>' + out.o[n] + oSpace[n] + "</del>"; } str += " " + out.n[i].text + nSpace[i] + pre; } } } return str; }; })(); })(this);
crgwbr/flakeyjs
tests/qunit.js
JavaScript
isc
41,188
import AddLearningToStoryDescription from '../../../../src/content_scripts/pivotal_tracker/use_cases/add_learning_to_story_description' import WWLTWRepository from '../../../../src/content_scripts/repositories/wwltw_repository'; import StoryTitleProvider from '../../../../src/content_scripts/utilities/story_title_provider'; import ProjectIdProvider from '../../../../src/content_scripts/utilities/project_id_provider'; describe('AddLearningToStoryDescription', function () { let wwltwRepositorySpy; let foundStory; let execute; const projectId = 'some project id'; const storyTitle = 'some story title'; beforeEach(function () { wwltwRepositorySpy = new WWLTWRepository(); foundStory = {id: '1234'}; spyOn(chrome.runtime, 'sendMessage'); spyOn(wwltwRepositorySpy, 'findByTitle').and.returnValue(Promise.resolve([foundStory])); spyOn(wwltwRepositorySpy, 'update').and.returnValue(Promise.resolve()); spyOn(StoryTitleProvider, 'currentStoryTitle').and.returnValue(storyTitle); spyOn(ProjectIdProvider, 'getProjectId').and.returnValue(projectId); const useCase = new AddLearningToStoryDescription(wwltwRepositorySpy); execute = useCase.execute; }); describe('execute', function () { describe('when called outside of AddLearningToStoryDescription instance', function () { it('finds the story', function () { execute('some tag, some other tag', 'some body'); expect(wwltwRepositorySpy.findByTitle).toHaveBeenCalledWith( projectId, storyTitle ); }); it('sends analytics data', function () { execute(); expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ eventType: 'submit' }); }); it('updates the found story', function (done) { const body = 'some body'; const tags = 'some tag, some other tag'; execute(tags, body).then(function () { expect(wwltwRepositorySpy.update).toHaveBeenCalledWith( projectId, foundStory, tags, body ); done(); }); }); }); }); });
oliverswitzer/wwltw-for-pivotal-tracker
test/content_scripts/pivotal_tracker/use_cases/add_learning_to_story_description_spec.js
JavaScript
isc
2,332
# ignore-together.py - a distributed ignore list engine for IRC. from __future__ import print_function import os import sys import yaml weechat_is_fake = False try: import weechat except: class FakeWeechat: def command(self, cmd): print(cmd) weechat = FakeWeechat() weechat_is_fake = True class IgnoreRule: """An ignore rule. This provides instrumentation for converting ignore rules into weechat filters. It handles both types of ignore-together ignore rules. """ def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]): self.ignorelist = ignorelist self.rulename = rulename.replace(' ', '_') self.rationale = rationale self.typename = typename self.hostmasks = hostmasks self.accountnames = accountnames self.patterns = patterns def install(self): "Install an ignore rule." subrule_ctr = 0 if self.typename == 'ignore': for pattern in self.hostmasks: weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format( ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern)) subrule_ctr += 1 # XXX - accountnames elif self.typename == 'message': for pattern in self.patterns: weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format( ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern)) subrule_ctr += 1 def uninstall(self): "Uninstall an ignore rule." subrule_ctr = 0 if self.typename == 'ignore': for pattern in self.hostmasks: weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format( ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr)) subrule_ctr += 1 elif self.typename == 'message': for pattern in self.patterns: weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format( ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr)) subrule_ctr += 1 class IgnoreRuleSet: """A downloaded collection of rules. Handles merging updates vs current state, and so on.""" def __init__(self, name, uri): self.name = name self.uri = uri self.rules = [] def load(self): def build_rules(s): for k, v in s.items(): self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', []))) def test_load_cb(payload): build_rules(yaml.load(payload)) if weechat_is_fake: d = open(self.uri, 'r') return test_load_cb(d.read()) def install(self): [r.install() for r in self.rules] def uninstall(self): [r.uninstall() for r in self.rules] rules = {}
kaniini/ignore-together
ignoretogether.py
Python
isc
3,250
"use strict"; var Template = function (options) { this._pageTitle = ''; this._titleSeparator = options.title_separator; this._siteTitle = options.site_title; this._req = null; this._res = null; }; Template.prototype.bindMiddleware = function(req, res) { this._req = req; this._res = res; }; Template.prototype.setPageTitle = function(pageTitle) { this._pageTitle = pageTitle; }; Template.prototype.setSiteTitle = function(siteTitle) { this._siteTitle = siteTitle; }; Template.prototype.setTitleSeparator = function(separator) { this._titleSeparator = separator; }; Template.prototype.getTitle = function() { if (this._pageTitle !== '') { return this._pageTitle + ' ' + this._titleSeparator + ' ' + this._siteTitle; } else { return this._siteTitle; } }; Template.prototype.getPageTitle = function() { return this._pageTitle; }; Template.prototype.getSiteTitle = function() { return this._siteTitle; }; Template.prototype.render = function(path, params) { this._res.render('partials/' + path, params); }; module.exports = Template;
mythos-framework/mythos-lib-template
Template.js
JavaScript
isc
1,091
/* eslint-env mocha */ const mockBot = require('../mockBot') const assert = require('assert') const mockery = require('mockery') const sinon = require('sinon') const json = JSON.stringify({ state: 'normal', nowTitle: 'Midnight News', nowInfo: '20/03/2019', nextStart: '2019-03-20T00:30:00Z', nextTitle: 'Book of the Week' }) describe('radio module', function () { let sandbox before(function () { // mockery mocks the entire require() mockery.enable() mockery.registerMock('request-promise', { get: () => Promise.resolve(json) }) // sinon stubs individual functions sandbox = sinon.sandbox.create() mockBot.loadModule('radio') }) it('should parse the API correctly', async function () { sandbox.useFakeTimers({ now: 1553040900000 }) // 2019-03-20T00:15:00Z const promise = await mockBot.runCommand('!r4') assert.strictEqual(promise, 'Now: \u000300Midnight News\u000f \u000315(20/03/2019)\u000f followed by Book of the Week in 15 minutes (12:30 am)') }) after(function (done) { mockery.disable() mockery.deregisterAll() done() }) })
zuzakistan/civilservant
test/modules/radio.js
JavaScript
isc
1,122
/* * Copyright (c) 2012 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <stdint.h> #include <set> #include <string> #include <iostream> #include <oriutil/debug.h> #include <ori/localrepo.h> using namespace std; extern LocalRepo repository; int cmd_listobj(int argc, char * const argv[]) { set<ObjectInfo> objects = repository.listObjects(); set<ObjectInfo>::iterator it; for (it = objects.begin(); it != objects.end(); it++) { const char *type; switch ((*it).type) { case ObjectInfo::Commit: type = "Commit"; break; case ObjectInfo::Tree: type = "Tree"; break; case ObjectInfo::Blob: type = "Blob"; break; case ObjectInfo::LargeBlob: type = "LargeBlob"; break; case ObjectInfo::Purged: type = "Purged"; break; default: cout << "Unknown object type (id " << (*it).hash.hex() << ")!" << endl; PANIC(); } cout << (*it).hash.hex() << " # " << type << endl; } return 0; }
BBBSnowball/ori
oridbg/cmd_listobj.cc
C++
isc
1,918
package com.evanbyrne.vending_machine_kata.ui; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Map; import java.util.Scanner; import java.util.SortedMap; import org.jooq.lambda.tuple.Tuple2; import com.evanbyrne.vending_machine_kata.coin.Cents; import com.evanbyrne.vending_machine_kata.coin.Coin; import com.evanbyrne.vending_machine_kata.coin.CoinCollection; import com.evanbyrne.vending_machine_kata.coin.CoinFactory; import com.evanbyrne.vending_machine_kata.inventory.IInventoryService; import com.evanbyrne.vending_machine_kata.inventory.InventoryProduct; /** * Manages console input and output. */ public class Console { /** * Get change display for terminal output. * * @param Change. * @return Formatted message. */ public String getChangeDisplay(final CoinCollection change) { final ArrayList<String> display = new ArrayList<String>(); final LinkedHashMap<Coin, Integer> coinMap = new LinkedHashMap<Coin, Integer>(); display.add("THANK YOU"); for(final Coin coin : change.getList()) { if(coinMap.containsKey(coin)) { coinMap.put(coin, coinMap.get(coin) + 1); } else { coinMap.put(coin, 1); } } if(!coinMap.isEmpty()) { final ArrayList<String> displayReturn = new ArrayList<String>(); for(final Map.Entry<Coin, Integer> entry : coinMap.entrySet()) { final String name = entry.getKey().name().toLowerCase(); final int count = entry.getValue(); displayReturn.add(String.format("%s (x%d)", name, count)); } display.add("RETURN: " + String.join(", ", displayReturn)); } return String.join("\n", display); } /** * Get product listing display for terminal output. * * @param Sorted map of all inventory. * @return Formatted message. */ public String getProductDisplay(final SortedMap<String, InventoryProduct> inventory) { if(!inventory.isEmpty()) { final ArrayList<String> display = new ArrayList<String>(); for(final Map.Entry<String, InventoryProduct> entry : inventory.entrySet()) { final String centsString = Cents.toString(entry.getValue().getCents()); final String name = entry.getValue().getName(); final String key = entry.getKey(); display.add(String.format("%s\t%s\t%s", key, centsString, name)); } return String.join("\n", display); } return "No items in vending machine."; } /** * Prompt user for payment. * * Loops until payment >= selected product cost. * * @param Scanner. * @param A product representing their selection. * @return Payment. */ public CoinCollection promptForPayment(final Scanner scanner, final InventoryProduct selection) { final CoinCollection paid = new CoinCollection(); Coin insert; String input; do { System.out.println("PRICE: " + Cents.toString(selection.getCents())); do { System.out.print(String.format("INSERT COIN (%s): ", Cents.toString(paid.getTotal()))); input = scanner.nextLine(); insert = CoinFactory.getByName(input); if(insert == null) { System.out.println("Invalid coin. This machine accepts: quarter, dime, nickel."); } } while(insert == null); paid.addCoin(insert); } while(paid.getTotal() < selection.getCents()); return paid; } /** * Prompt for product selection. * * Loops until a valid product has been selected. * * @param Scanner * @param An implementation of IInventoryService. * @return A tuple with the product key and product. */ public Tuple2<String, InventoryProduct> promptForSelection(final Scanner scanner, final IInventoryService inventoryService) { InventoryProduct selection; String input; do { System.out.print("SELECT: "); input = scanner.nextLine(); selection = inventoryService.getProduct(input); if( selection == null ) { System.out.println("Invalid selection."); } } while(selection == null); return new Tuple2<String, InventoryProduct>(input, selection); } }
evantbyrne/vending-machine-kata
src/main/java/com/evanbyrne/vending_machine_kata/ui/Console.java
Java
isc
4,553
import { Accessor, AnimationSampler, Document, Root, Transform, TransformContext } from '@gltf-transform/core'; import { createTransform, isTransformPending } from './utils'; const NAME = 'resample'; export interface ResampleOptions {tolerance?: number} const RESAMPLE_DEFAULTS: Required<ResampleOptions> = {tolerance: 1e-4}; /** * Resample {@link Animation}s, losslessly deduplicating keyframes to reduce file size. Duplicate * keyframes are commonly present in animation 'baked' by the authoring software to apply IK * constraints or other software-specific features. Based on THREE.KeyframeTrack.optimize(). * * Example: (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0) */ export const resample = (_options: ResampleOptions = RESAMPLE_DEFAULTS): Transform => { const options = {...RESAMPLE_DEFAULTS, ..._options} as Required<ResampleOptions>; return createTransform(NAME, (doc: Document, context?: TransformContext): void => { const accessorsVisited = new Set<Accessor>(); const accessorsCountPrev = doc.getRoot().listAccessors().length; const logger = doc.getLogger(); let didSkipMorphTargets = false; for (const animation of doc.getRoot().listAnimations()) { // Skip morph targets, see https://github.com/donmccurdy/glTF-Transform/issues/290. const morphTargetSamplers = new Set<AnimationSampler>(); for (const channel of animation.listChannels()) { if (channel.getSampler() && channel.getTargetPath() === 'weights') { morphTargetSamplers.add(channel.getSampler()!); } } for (const sampler of animation.listSamplers()) { if (morphTargetSamplers.has(sampler)) { didSkipMorphTargets = true; continue; } if (sampler.getInterpolation() === 'STEP' || sampler.getInterpolation() === 'LINEAR') { accessorsVisited.add(sampler.getInput()!); accessorsVisited.add(sampler.getOutput()!); optimize(sampler, options); } } } for (const accessor of Array.from(accessorsVisited.values())) { const used = accessor.listParents().some((p) => !(p instanceof Root)); if (!used) accessor.dispose(); } if (doc.getRoot().listAccessors().length > accessorsCountPrev && !isTransformPending(context, NAME, 'dedup')) { logger.warn( `${NAME}: Resampling required copying accessors, some of which may be duplicates.` + ' Consider using "dedup" to consolidate any duplicates.' ); } if (didSkipMorphTargets) { logger.warn(`${NAME}: Skipped optimizing morph target keyframes, not yet supported.`); } logger.debug(`${NAME}: Complete.`); }); }; function optimize (sampler: AnimationSampler, options: ResampleOptions): void { const input = sampler.getInput()!.clone(); const output = sampler.getOutput()!.clone(); const tolerance = options.tolerance as number; const lastIndex = input.getCount() - 1; const tmp: number[] = []; let writeIndex = 1; for (let i = 1; i < lastIndex; ++ i) { const time = input.getScalar(i); const timePrev = input.getScalar(i - 1); const timeNext = input.getScalar(i + 1); const timeMix = (time - timePrev) / (timeNext - timePrev); let keep = false; // Remove unnecessary adjacent keyframes. if (time !== timeNext && (i !== 1 || time !== input.getScalar(0))) { for (let j = 0; j < output.getElementSize(); j++) { const value = output.getElement(i, tmp)[j]; const valuePrev = output.getElement(i - 1, tmp)[j]; const valueNext = output.getElement(i + 1, tmp)[j]; if (sampler.getInterpolation() === 'LINEAR') { // Prune keyframes that are colinear with prev/next keyframes. if (Math.abs(value - lerp(valuePrev, valueNext, timeMix)) > tolerance) { keep = true; break; } } else if (sampler.getInterpolation() === 'STEP') { // Prune keyframes that are identical to prev/next keyframes. if (value !== valuePrev || value !== valueNext) { keep = true; break; } } } } // In-place compaction. if (keep) { if (i !== writeIndex) { input.setScalar(writeIndex, input.getScalar(i)); output.setElement(writeIndex, output.getElement(i, tmp)); } writeIndex++; } } // Flush last keyframe (compaction looks ahead). if (lastIndex > 0) { input.setScalar(writeIndex, input.getScalar(lastIndex)); output.setElement(writeIndex, output.getElement(lastIndex, tmp)); writeIndex++; } // If the sampler was optimized, truncate and save the results. If not, clean up. if (writeIndex !== input.getCount()) { input.setArray(input.getArray()!.slice(0, writeIndex)); output.setArray(output.getArray()!.slice(0, writeIndex * output.getElementSize())); sampler.setInput(input); sampler.setOutput(output); } else { input.dispose(); output.dispose(); } } function lerp (v0: number, v1: number, t: number): number { return v0 * (1 - t) + v1 * t; }
damienmortini/dlib
node_modules/@gltf-transform/functions/src/resample.ts
TypeScript
isc
4,825
describe("Membrane Panel Operations with flat files:", function() { "use strict"; var window; beforeEach(async function() { await getDocumentLoadPromise("base/gui/index.html"); window = testFrame.contentWindow; window.LoadPanel.testMode = {fakeFiles: true}; let p1 = MessageEventPromise(window, "MembranePanel initialized"); let p2 = MessageEventPromise( window, "MembranePanel cached configuration reset" ); window.OuterGridManager.membranePanelRadio.click(); await Promise.all([p1, p2]); }); function getErrorMessage() { let output = window.OuterGridManager.currentErrorOutput; if (!output.firstChild) return null; return output.firstChild.nodeValue; } it("starts with no graph names and two rows", function() { // two delete buttons and one add button { let buttons = window.HandlerNames.grid.getElementsByTagName("button"); expect(buttons.length).toBe(3); for (let i = 0; i < buttons.length; i++) { expect(buttons[i].disabled).toBe(i < buttons.length - 1); } } const [graphNames, graphSymbolLists] = window.HandlerNames.serializableNames(); expect(Array.isArray(graphNames)).toBe(true); expect(Array.isArray(graphSymbolLists)).toBe(true); expect(graphNames.length).toBe(0); expect(graphSymbolLists.length).toBe(0); expect(getErrorMessage()).toBe(null); }); it("supports the pass-through function for the membrane", function() { const editor = window.MembranePanel.passThroughEditor; { expect(window.MembranePanel.passThroughCheckbox.checked).toBe(false); expect(window.MembranePanel.primordialsCheckbox.checked).toBe(false); expect(window.MembranePanel.primordialsCheckbox.disabled).toBe(true); expect(window.CodeMirrorManager.getEditorEnabled(editor)).toBe(false); } { window.MembranePanel.passThroughCheckbox.click(); expect(window.MembranePanel.passThroughCheckbox.checked).toBe(true); expect(window.MembranePanel.primordialsCheckbox.disabled).toBe(false); expect(window.CodeMirrorManager.getEditorEnabled(editor)).toBe(true); } { window.MembranePanel.primordialsCheckbox.click(); expect(window.MembranePanel.passThroughCheckbox.checked).toBe(true); expect(window.MembranePanel.primordialsCheckbox.checked).toBe(true); expect(window.MembranePanel.primordialsCheckbox.disabled).toBe(false); expect(window.CodeMirrorManager.getEditorEnabled(editor)).toBe(true); const prelim = "(function() {\n const items = Membrane.Primordials.slice(0);\n\n"; const value = window.MembranePanel.getPassThrough(true); expect(value.startsWith(prelim)).toBe(true); } { window.MembranePanel.primordialsCheckbox.click(); expect(window.MembranePanel.passThroughCheckbox.checked).toBe(true); expect(window.MembranePanel.primordialsCheckbox.checked).toBe(false); expect(window.MembranePanel.primordialsCheckbox.disabled).toBe(false); expect(window.CodeMirrorManager.getEditorEnabled(editor)).toBe(true); } { window.MembranePanel.passThroughCheckbox.click(); expect(window.MembranePanel.passThroughCheckbox.checked).toBe(false); expect(window.MembranePanel.primordialsCheckbox.checked).toBe(false); expect(window.MembranePanel.primordialsCheckbox.disabled).toBe(true); expect(window.CodeMirrorManager.getEditorEnabled(editor)).toBe(false); } }); describe( "The graph handler names API requires at least two distinct names (either symbols or strings)", function() { function validateControls() { window.HandlerNames.update(); const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name"); const rv = []; const length = inputs.length; for (let i = 0; i < length; i++) { rv.push(inputs[i].checkValidity()); expect(inputs[i].nextElementSibling.disabled).toBe(length == 2); } return rv; } it("initial state is disallowed for two inputs", function() { const states = validateControls(); expect(states.length).toBe(2); expect(states[0]).toBe(false); expect(states[1]).toBe(false); }); it("allows a name to be an unique string", function() { const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name"); inputs[0].value = "foo"; inputs[1].value = "bar"; const states = validateControls(); expect(states.length).toBe(2); expect(states[0]).toBe(true); expect(states[1]).toBe(true); }); it("clicking on the addRow button really does add a new row", function() { window.HandlerNames.addRow(); const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name"); inputs[0].value = "foo"; inputs[1].value = "bar"; const states = validateControls(); expect(states.length).toBe(3); expect(states[0]).toBe(true); expect(states[1]).toBe(true); expect(states[2]).toBe(false); }); it("disallows non-unique strings", function() { window.HandlerNames.addRow(); const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name"); inputs[0].value = "foo"; inputs[1].value = "bar"; inputs[2].value = "foo"; const states = validateControls(); expect(states.length).toBe(3); expect(states[0]).toBe(true); expect(states[1]).toBe(true); expect(states[2]).toBe(false); }); it("allows removing a row", function() { window.HandlerNames.addRow(); const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name"); inputs[0].value = "foo"; inputs[1].value = "bar"; inputs[2].value = "baz"; inputs[0].nextElementSibling.click(); expect(inputs.length).toBe(2); expect(inputs[0].value).toBe("bar"); expect(inputs[1].value).toBe("baz"); const states = validateControls(); expect(states.length).toBe(2); expect(states[0]).toBe(true); expect(states[1]).toBe(true); }); it("allows a symbol to share a name with a string", function() { window.HandlerNames.addRow(); const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name"); inputs[0].value = "foo"; inputs[1].value = "bar"; inputs[2].value = "foo"; inputs[2].previousElementSibling.firstElementChild.checked = true; // symbol const states = validateControls(); expect(states.length).toBe(3); expect(states[0]).toBe(true); expect(states[1]).toBe(true); expect(states[2]).toBe(true); }); it("allows two symbols to share a name", function() { window.HandlerNames.addRow(); const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name"); inputs[0].value = "foo"; inputs[1].value = "bar"; inputs[2].value = "foo"; inputs[0].previousElementSibling.firstElementChild.checked = true; // symbol inputs[2].previousElementSibling.firstElementChild.checked = true; // symbol const states = validateControls(); expect(states.length).toBe(3); expect(states[0]).toBe(true); expect(states[1]).toBe(true); expect(states[2]).toBe(true); }); } ); }); it("Membrane Panel supports pass-through function", async function() { await getDocumentLoadPromise("base/gui/index.html"); const window = testFrame.contentWindow; window.LoadPanel.testMode = { fakeFiles: true, configSource: `{ "configurationSetup": { "useZip": false, "commonFiles": [], "formatVersion": 1, "lastUpdated": "Mon, 19 Feb 2018 20:56:56 GMT" }, "membrane": { "passThroughSource": " // hello world", "passThroughEnabled": true, "primordialsPass": true }, "graphs": [ { "name": "wet", "isSymbol": false, "passThroughSource": "", "passThroughEnabled": false, "primordialsPass": false, "distortions": [] }, { "name": "dry", "isSymbol": false, "passThroughSource": "", "passThroughEnabled": false, "primordialsPass": false, "distortions": [] } ] }` }; let p1 = MessageEventPromise(window, "MembranePanel initialized"); let p2 = MessageEventPromise( window, "MembranePanel cached configuration reset", "MembranePanel exception thrown in reset" ); window.OuterGridManager.membranePanelRadio.click(); await Promise.all([p1, p2]); expect(window.MembranePanel.passThroughCheckbox.checked).toBe(true); expect(window.MembranePanel.primordialsCheckbox.checked).toBe(true); expect(window.MembranePanel.getPassThrough()).toContain("// hello world"); });
ajvincent/es7-membrane
docs/gui/tests/membranePanel.js
JavaScript
isc
9,110
// License: The Unlicense (https://unlicense.org) #include "EventHandler.hpp" #include <SDL2/SDL.h> int EventFilter(void *userData, SDL_Event *event); void SetUpEvents(void) { SDL_EventState(SDL_APP_TERMINATING, SDL_IGNORE); SDL_EventState(SDL_APP_LOWMEMORY, SDL_IGNORE); SDL_EventState(SDL_APP_WILLENTERBACKGROUND, SDL_IGNORE); SDL_EventState(SDL_APP_DIDENTERBACKGROUND, SDL_IGNORE); SDL_EventState(SDL_APP_WILLENTERFOREGROUND, SDL_IGNORE); SDL_EventState(SDL_APP_DIDENTERFOREGROUND, SDL_IGNORE); SDL_EventState(SDL_AUDIODEVICEADDED, SDL_IGNORE); SDL_EventState(SDL_AUDIODEVICEREMOVED, SDL_IGNORE); SDL_EventState(SDL_CLIPBOARDUPDATE, SDL_IGNORE); SDL_EventState(SDL_CONTROLLERAXISMOTION, SDL_IGNORE); SDL_EventState(SDL_CONTROLLERBUTTONDOWN, SDL_IGNORE); SDL_EventState(SDL_CONTROLLERBUTTONUP, SDL_IGNORE); SDL_EventState(SDL_CONTROLLERDEVICEADDED, SDL_IGNORE); SDL_EventState(SDL_CONTROLLERDEVICEREMAPPED, SDL_IGNORE); SDL_EventState(SDL_CONTROLLERDEVICEREMOVED, SDL_IGNORE); SDL_EventState(SDL_DOLLARGESTURE, SDL_IGNORE); SDL_EventState(SDL_DOLLARRECORD, SDL_IGNORE); SDL_EventState(SDL_DROPFILE, SDL_IGNORE); SDL_EventState(SDL_FINGERDOWN, SDL_IGNORE); SDL_EventState(SDL_FINGERMOTION, SDL_IGNORE); SDL_EventState(SDL_FINGERUP, SDL_IGNORE); SDL_EventState(SDL_JOYAXISMOTION, SDL_IGNORE); SDL_EventState(SDL_JOYBALLMOTION, SDL_IGNORE); SDL_EventState(SDL_JOYBUTTONDOWN, SDL_IGNORE); SDL_EventState(SDL_JOYBUTTONUP, SDL_IGNORE); SDL_EventState(SDL_JOYDEVICEADDED, SDL_IGNORE); SDL_EventState(SDL_JOYDEVICEREMOVED, SDL_IGNORE); SDL_EventState(SDL_JOYHATMOTION, SDL_IGNORE); SDL_EventState(SDL_KEYMAPCHANGED, SDL_IGNORE); SDL_EventState(SDL_KEYUP, SDL_IGNORE); SDL_EventState(SDL_LASTEVENT, SDL_IGNORE); SDL_EventState(SDL_MOUSEBUTTONDOWN, SDL_IGNORE); SDL_EventState(SDL_MOUSEBUTTONUP, SDL_IGNORE); SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE); SDL_EventState(SDL_MOUSEWHEEL, SDL_IGNORE); SDL_EventState(SDL_MULTIGESTURE, SDL_IGNORE); SDL_EventState(SDL_RENDER_TARGETS_RESET, SDL_IGNORE); SDL_EventState(SDL_RENDER_DEVICE_RESET, SDL_IGNORE); SDL_EventState(SDL_SYSWMEVENT, SDL_IGNORE); SDL_EventState(SDL_TEXTEDITING, SDL_IGNORE); SDL_EventState(SDL_TEXTINPUT, SDL_IGNORE); SDL_EventState(SDL_USEREVENT, SDL_IGNORE); SDL_SetEventFilter(EventFilter, nullptr); } int EventFilter(void *, SDL_Event *event) { int result = 0; switch (event->type) { case SDL_QUIT: case SDL_WINDOWEVENT: result = 1; break; case SDL_KEYDOWN: switch (event->key.keysym.sym) { case SDLK_DOWN: case SDLK_UP: case SDLK_LEFT: case SDLK_RIGHT: result = 1; break; default: // Ignore all other keys break; } break; default: printf("Something happened!\n"); break; } return result; }
tblyons/goon
src/EventHandler.cpp
C++
isc
3,005
var DND_START_EVENT = 'dnd-start', DND_END_EVENT = 'dnd-end', DND_DRAG_EVENT = 'dnd-drag'; angular .module( 'app' ) .config( [ 'iScrollServiceProvider', function(iScrollServiceProvider){ iScrollServiceProvider.configureDefaults({ iScroll: { momentum: false, mouseWheel: true, disableMouse: false, useTransform: true, scrollbars: true, interactiveScrollbars: true, resizeScrollbars: false, probeType: 2, preventDefault: false // preventDefaultException: { // tagName: /^.*$/ // } }, directive: { asyncRefreshDelay: 0, refreshInterval: false } }); } ] ) .controller( 'main', function( $scope, draggingIndicator, iScrollService ){ 'use strict'; this.iScrollState = iScrollService.state; var DND_SCROLL_IGNORED_HEIGHT = 20, // ignoring 20px touch-scroll, // TODO: this might be stored somewhere in browser env DND_ACTIVATION_TIMEOUT = 500, // milliseconds needed to touch-activate d-n-d MOUSE_OVER_EVENT = 'mousemove'; var self = this, items = [], touchTimerId; $scope.dragging = draggingIndicator; for( var i = 0; i< 25; i++ ){ items.push( i ); } $scope.items = items; this.disable = function ( ){ $scope.iScrollInstance.disable(); }; this.log = function ( msg ){ console.log( 'got msg', msg ); }; } );
kosich/ng-hammer-iscroll-drag
main.js
JavaScript
isc
1,547
/* * Copyright © 2016 <code@io7m.com> http://io7m.com * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package com.io7m.jcanephora.tests.lwjgl3; import com.io7m.jcanephora.core.api.JCGLContextType; import com.io7m.jcanephora.core.api.JCGLInterfaceGL33Type; import com.io7m.jcanephora.tests.contracts.JCGLFramebuffersContract; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class LWJGL3FramebuffersTestGL33 extends JCGLFramebuffersContract { private static final Logger LOG; static { LOG = LoggerFactory.getLogger(LWJGL3FramebuffersTestGL33.class); } @Override public void onTestCompleted() { LWJGL3TestContexts.closeAllContexts(); } @Override protected Interfaces getInterfaces(final String name) { final JCGLContextType c = LWJGL3TestContexts.newGL33Context(name, 24, 8); final JCGLInterfaceGL33Type cg = c.contextGetGL33(); return new Interfaces(c, cg.framebuffers(), cg.textures()); } @Override protected boolean hasRealBlitting() { return true; } }
io7m/jcanephora
com.io7m.jcanephora.tests.lwjgl3/src/test/java/com/io7m/jcanephora/tests/lwjgl3/LWJGL3FramebuffersTestGL33.java
Java
isc
1,726
'use strict' let _ = require('lodash') let HttpClient = require('./http-client') /** * Server configuration and environment information * @extends {HttpClient} */ class Config extends HttpClient { /** * @constructs Config * @param {Object} options General configuration options * @param {Object} options.http configurations for HttpClient */ constructor (options) { super(options.http) } /** * Return the whole server information * @return {Promise} A promise that resolves to the server information */ server () { return this._httpRequest('GET') .then((response) => response.metadata) } /** * Retrieve the server configuration * @return {Promise} A promise that resolves to the server configuration */ get () { return this.server() .then((server) => server.config) } /** * Unset parameters from server configuration * @param {...String} arguments A list parameters that you want to unset * @return {Promise} A promise that resolves when the config has been unset */ unset () { return this.get() .then((config) => _.omit(config, _.flatten(Array.from(arguments)))) .then((config) => this.update(config)) } /** * Set one or more configurations in the server * @param {Object} data A plain object containing the configuration you want * to insert or update in the server * @return {Pomise} A promise that resolves when the config has been set */ set (data) { return this.get() .then((config) => _.merge(config, data)) .then((config) => this.update(config)) } /** * Replaces the whole server configuration for the one provided * @param {Object} data The new server configuration * @return {Promise} A promise that resolves when the configuration has been * replaces */ update (data) { return this._httpRequest('PUT', { config: data }) } } module.exports = Config
alanhoff/node-lxd
lib/config.js
JavaScript
isc
1,927
import $ from 'jquery'; import { router } from 'src/router'; import './header.scss'; export default class Header { static selectors = { button: '.header__enter', search: '.header__search' }; constructor($root) { this.elements = { $root, $window: $(window) }; this.attachEvents(); } attachEvents() { this.elements.$root.on('click', Header.selectors.button, this.handleClick) } handleClick = () => { const search = $(Header.selectors.search).val(); if (search) { router.navigate(`/search?query=${search}`); } } }
ksukhova/Auction
src/components/header/header.js
JavaScript
isc
658
import re from exchange.constants import ( CURRENCIES, CURRENCY_NAMES, DEFAULT_CURRENCY, CURRENCY_EUR, CURRENCY_UAH, CURRENCY_USD, CURRENCY_SESSION_KEY) def round_number(value, decimal_places=2, down=False): assert decimal_places > 0 factor = 1.0 ** decimal_places sign = -1 if value < 0 else 1 return int(value * factor + sign * (0 if down else 0.5)) / factor def format_number(value): append_comma = lambda match_object: "%s," % match_object.group(0) value = "%.2f" % float(value) value = re.sub("(\d)(?=(\d{3})+\.)", append_comma, value) return value def format_price(price, round_price=False): price = float(price) return format_number(round_number(price) if round_price else price) def format_printable_price(price, currency=DEFAULT_CURRENCY): return '%s %s' % (format_price(price), dict(CURRENCIES)[currency]) def get_currency_from_session(session): currency = session.get(CURRENCY_SESSION_KEY) or DEFAULT_CURRENCY return int(currency) def get_price_factory(rates, src, dst): if src == dst: return lambda p: p name = lambda c: CURRENCY_NAMES[c] if src == CURRENCY_UAH: return lambda p: p / getattr(rates, name(dst)) if dst == CURRENCY_UAH: return lambda p: p * getattr(rates, name(src)) if src == CURRENCY_USD and dst == CURRENCY_EUR: return lambda p: p * rates.usd_eur if src == CURRENCY_EUR and dst == CURRENCY_USD: return lambda p: p / rates.usd_eur raise ValueError('Unknown currencies')
pmaigutyak/mp-shop
exchange/utils.py
Python
isc
1,571
package org.apollo.game.event.handler.impl; import org.apollo.game.event.handler.EventHandler; import org.apollo.game.event.handler.EventHandlerContext; import org.apollo.game.event.impl.ItemOnItemEvent; import org.apollo.game.model.Inventory; import org.apollo.game.model.Item; import org.apollo.game.model.Player; /** * An {@link EventHandler} which verifies the target item in {@link ItemOnItemEvent}s. * * @author Chris Fletcher */ public final class ItemOnItemVerificationHandler extends EventHandler<ItemOnItemEvent> { @Override public void handle(EventHandlerContext ctx, Player player, ItemOnItemEvent event) { Inventory inventory = ItemVerificationHandler.interfaceToInventory(player, event.getTargetInterfaceId()); int slot = event.getTargetSlot(); if (slot < 0 || slot >= inventory.capacity()) { ctx.breakHandlerChain(); return; } Item item = inventory.get(slot); if (item == null || item.getId() != event.getTargetId()) { ctx.breakHandlerChain(); } } }
DealerNextDoor/ApolloDev
src/org/apollo/game/event/handler/impl/ItemOnItemVerificationHandler.java
Java
isc
1,001
"use strict"; describe("This package", function(){ it("rubs the lotion on its skin, or else", function(){ 2..should.equal(2); // In this universe, it'd damn well better }); it("gets the hose again", function(){ this.should.be.extensible.and.ok; // Eventually }); it("should not fail", function(){ NaN.should.not.equal(NaN); // NaH global.foo = "Foo"; }); it("might be written later"); // Nah it("should fail", function(){ const A = { alpha: "A", beta: "B", gamma: "E", delta: "D", }; const B = { Alpha: "A", beta: "B", gamma: "E", delta: "d", }; A.should.equal(B); }); describe("Suite nesting", function(){ it("does something useful eventually", function(done){ setTimeout(() => done(), 40); }); it("cleans anonymous async functions", async function(){ if(true){ true.should.be.true; } }); it("cleans anonymous generators", function * (){ if(true){ true.should.be.true; } }); it("cleans named async functions", async function foo() { if(true){ true.should.be.true; } }); it("cleans named generators", function * foo (){ if(true){ true.should.be.true; } }); it("cleans async arrow functions", async () => { if(true){ true.should.be.true; } }); }); }); describe("Second suite at top-level", function(){ it("shows another block", function(){ Chai.expect(Date).to.be.an.instanceOf(Function); }); it("breaks something", function(){ something(); }); it("loads locally-required files", () => { expect(global.someGlobalThing).to.equal("fooXYZ"); }); unlessOnWindows.it("enjoys real symbolic links", () => { "Any Unix-like system".should.be.ok; }); }); describe("Aborted tests", () => { before(() => {throw new Error("Nah, not really")}); it("won't reach this", () => true.should.not.be.false); it.skip("won't reach this either", () => true.should.be.true); });
Alhadis/Atom-Mocha
spec/basic-spec.js
JavaScript
isc
1,958
'use strict'; var yeoman = require('yeoman-generator'), chalk = require('chalk'), yosay = require('yosay'), bakery = require('../../lib/bakery'), feedback = require('../../lib/feedback'), debug = require('debug')('bakery:generators:cm-bash:index'), glob = require('glob'), path = require('path'), _ = require('lodash'); // placeholder for CM implementaiton delivering a BASH-based project. var BakeryCM = yeoman.Base.extend({ constructor: function () { yeoman.Base.apply(this, arguments); this._options.help.desc = 'Show this help'; this.argument('projectname', { type: String, required: this.config.get('projectname') == undefined }); }, // generators are invalid without at least one method to run during lifecycle default: function () { /* TAKE NOTE: these next two lines are fallout of having to include ALL sub-generators in .composeWith(...) at the top level. Essentially ALL SUBGENERATORS RUN ALL THE TIME. So we have to escape from generators we don't want running within EVERY lifecycle method. (ugh) */ let cmInfo = this.config.get('cm'); if (cmInfo.generatorName != 'cm-bash') { return; } } }); module.exports = BakeryCM;
datapipe/generator-bakery
generators/cm-bash/index.js
JavaScript
isc
1,256
package com.leychina.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.webkit.WebChromeClient; import android.widget.ImageView; import android.widget.TextView; import com.leychina.R; import com.leychina.model.Artist; import com.leychina.value.Constant; import com.leychina.widget.tabindicator.TouchyWebView; import com.squareup.picasso.Picasso; /** * Created by yuandunlong on 11/21/15. */ public class ArtistDetailActivity extends AppCompatActivity { TouchyWebView webview; Artist artist; ImageView imageView; TextView weight, height, name, birthday; public static void start(Context from, Artist artist) { Intent intent = new Intent(from, ArtistDetailActivity.class); intent.putExtra("artist", artist); from.startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { Intent intent = getIntent(); this.artist = (Artist) intent.getSerializableExtra("artist"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_artist_detail); webview = (TouchyWebView) findViewById(R.id.artist_webview); imageView = (ImageView) findViewById(R.id.image_view_artist_cover); Picasso.with(this).load(Constant.DOMAIN+"/static/upload/"+artist.getPhoto()).into(imageView); name = (TextView) findViewById(R.id.text_view_name); height = (TextView) findViewById(R.id.text_view_height); weight = (TextView) findViewById(R.id.text_view_weight); birthday= (TextView) findViewById(R.id.text_view_birthday); // name.setText(artist.get); weight.setText(artist.getWeight() + ""); height.setText(artist.getHeight() + ""); birthday.setText(artist.getBlood()); webview.setWebChromeClient(new WebChromeClient()); webview.getSettings().setDefaultTextEncodingName("utf-8"); webview.loadDataWithBaseURL(Constant.DOMAIN, artist.getDescription(), "text/html", "utf-8",""); } }
yuandunlong/leychina-android
app/src/main/java/com/leychina/activity/ArtistDetailActivity.java
Java
isc
2,114