text
stringlengths
4
5.48M
meta
stringlengths
14
6.54k
FROM balenalib/surface-go-fedora:32-build # http://bugs.python.org/issue19846 # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 RUN dnf install -y \ python-pip \ python-dbus \ && dnf clean all # install "virtualenv", since the vast majority of users of this image will want it RUN pip install -U --no-cache-dir --ignore-installed pip setuptools \ && pip install --no-cache-dir virtualenv RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'As of January 1st, 2020, Python 2 was end-of-life, we will change the latest tag for Balenalib Python base image to Python 3.x and drop support for Python 2 soon. So after 1st July, 2020, all the balenalib Python latest tag will point to the latest Python 3 version and no changes, or fixes will be made to balenalib Python 2 base image. If you are using Python 2 for your application, please upgrade to Python 3 before 1st July.' > /.balena/messages/python-deprecation-warning CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \ && echo "Running test-stack@python" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Fedora 32 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v2.7.18, Pip v21.0.1, Setuptools v56.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{'content_hash': 'ddfcb8d79b3743fee522f3d7d4815a8f', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 723, 'avg_line_length': 78.3225806451613, 'alnum_prop': 0.7327018121911038, 'repo_name': 'nghiant2710/base-images', 'id': 'b2d05371eeaac3c8ba49fecf515ff9924ba7265c', 'size': '2449', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'balena-base-images/python/surface-go/fedora/32/2.7.18/build/Dockerfile', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '144558581'}, {'name': 'JavaScript', 'bytes': '16316'}, {'name': 'Shell', 'bytes': '368690'}]}
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/generic/memory/lib/utils/omi/gen_omi_traits.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2019,2022 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file gen_omi_traits.H /// @brief Generic Traits file for OMI code /// // *HWP HWP Owner: Geetha Pisapati <[email protected]> // *HWP HWP Backup: Louis Stermole <[email protected]> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: HB:FSP // EKB-Mirror-To: hostboot #ifndef _GEN_OMI_TRAITS_H_ #define _GEN_OMI_TRAITS_H_ #include <fapi2.H> namespace mss { namespace omi { /// /// @class omiTraits /// @tparam MC the mc type /// @brief A MC to MC_TARGET_TYPE mapping /// template< mss::mc_type MC > class omiTraits; } // end omi ns } // end mss ns #endif
{'content_hash': 'e35ec671ba774cc82c7fc6c525b0dd9b', 'timestamp': '', 'source': 'github', 'line_count': 58, 'max_line_length': 76, 'avg_line_length': 41.93103448275862, 'alnum_prop': 0.41776315789473684, 'repo_name': 'open-power/hostboot', 'id': '1b773aebb7d2f240ab1dce4ae6d8ebe4ae9ea040', 'size': '2432', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master-p10', 'path': 'src/import/generic/memory/lib/utils/omi/gen_omi_traits.H', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '84276'}, {'name': 'C', 'bytes': '29945981'}, {'name': 'C++', 'bytes': '126613976'}, {'name': 'CMake', 'bytes': '1852'}, {'name': 'Lex', 'bytes': '8996'}, {'name': 'M4', 'bytes': '5738'}, {'name': 'Makefile', 'bytes': '772285'}, {'name': 'Meson', 'bytes': '23911'}, {'name': 'Perl', 'bytes': '2605582'}, {'name': 'Python', 'bytes': '2602753'}, {'name': 'Shell', 'bytes': '290164'}, {'name': 'Tcl', 'bytes': '76031'}, {'name': 'XSLT', 'bytes': '9553'}, {'name': 'Yacc', 'bytes': '29440'}]}
<?php namespace Zend\Form\Annotation; /** * Hydrator annotation * * Use this annotation to specify a specific hydrator class to use with the form. * The value should be a string indicating the fully qualified class name of the * hydrator to use. * * @Annotation * @package Zend_Form * @subpackage Annotation */ class Hydrator extends AbstractStringAnnotation { /** * Retrieve the hydrator class * * @return null|string */ public function getHydrator() { return $this->value; } }
{'content_hash': 'd0f1135f8efd4553b6283dbcafed1f77', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 81, 'avg_line_length': 20.25, 'alnum_prop': 0.6313932980599647, 'repo_name': 'OtsList/OtsList.eu-AAC-for-OpenTibia', 'id': '42ec55d4e50e1931c623413dca441e207231e652', 'size': '900', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'vendor/ZF2/library/Zend/Form/Annotation/Hydrator.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'PHP', 'bytes': '464533'}]}
[![standard-readme compliant](https://img.shields.io/badge/readme%20style-standard-brightgreen.svg)](https://github.com/RichardLitt/standard-readme) [![Gitter](https://img.shields.io/gitter/room/nwjs/nw.js.svg)][Gitter] [![Releases](https://img.shields.io/github/downloads/atom/atom/total.svg)][Releases] > Ethereum miner with OpenCL, CUDA and stratum support The ethminer is an Ethereum GPU mining worker. This is the actively maintained version of ethminer. It originates from [cpp-ethereum] project (where GPU mining has been discontinued) and builds on the improvements made in [Genoil's fork]. See [FAQ](#faq) for more details. ### Features - OpenCL mining - Nvidia CUDA mining - realistic benchmarking against arbitrary epoch/DAG/blocknumber - on-GPU DAG generation (no more DAG files on disk) - stratum mining without proxy - OpenCL devices picking - farm failover (getwork + stratum) ## Table of Contents - [Install](#install) - [Usage](#usage) - [Build](#build) - [Continuous Integration and development builds](#continuous-integration-and-development-builds) - [Building from source](#building-from-source) - [CMake configuration options](#cmake-configuration-options) - [Maintainer](#maintainer) - [Contribute](#contribute) - [F.A.Q.](#faq) ## Install [![Releases](https://img.shields.io/github/downloads/atom/atom/total.svg)][Releases] Standalone **executables** for _Linux_, _macOS_ and _Windows_ are provided in the [Releases] section. Download an archive for your operating system and unpack the content to a place accessible from command line. The ethminer is ready to go. ## Usage The **ethminer** is a command line program. This means you launch it either from a Windows command prompt or Linux console, or create shortcuts to predefined command lines using a Linux Bash script or Windows batch/cmd file. For a full list of available command, please run ```sh ethminer --help ``` ## Build ### Continuous Integration and development builds | CI | OS | Status | Development builds | | ------------- | ------------- | ----- | ----------------- | | [Travis CI] | Linux, macOS | [![Travis CI](https://img.shields.io/travis/ethereum-mining/ethminer.svg)][Travis CI] | ✗ No build artifacts, [Amazon S3 is needed] for this | | [AppVeyor] | Windows | [![AppVeyor](https://img.shields.io/appveyor/ci/ethereum-mining/ethminer.svg)][AppVeyor] | ✓ Build artifacts available for all PRs and branches | The AppVeyor system automatically builds a Windows .exe for every commit. The latest version is always available [on the landing page](https://ci.appveyor.com/project/ethereum-mining/ethminer) or you can [browse the history](https://ci.appveyor.com/project/ethereum-mining/ethminer/history) to access previous builds. To download the .exe on a build under 'JOB NAME' select 'Configuration: Release', choose 'ARTIFACTS' then download the zip file. ### Building from source This project uses [CMake] and [Hunter] package manager. 1. Create a build directory. ```sh mkdir build; cd build ``` 2. Configure the project with CMake. Check out additional [configuration options](#cmake-configuration-options). ```sh cmake .. ``` 3. Build the project using [CMake Build Tool Mode]. This is a portable variant of `make`. ```sh cmake --build . ``` 4. _(Optional, Linux only)_ Install the built executable. ```sh sudo make install ``` #### OpenCL support on Linux If you're planning to use [OpenCL on Linux](https://github.com/ruslo/hunter/wiki/pkg.opencl#pitfalls) you have to install OpenGL libraries. E.g. on Ubuntu run: ```sh sudo apt-get install mesa-common-dev ``` #### Disable Hunter If you want to install dependencies yourself or use system package manager you can disable Hunter by adding [-DHUNTER_ENABLED=OFF](https://docs.hunter.sh/en/latest/reference/user-variables.html#hunter-enabled) to configuration options. ### CMake configuration options Pass these options to CMake configuration command, e.g. ```sh cmake .. -DETHASHCUDA=ON -DETHASHCL=OFF ``` - `-DETHASHCL=ON` - enable OpenCL mining, `ON` by default, - `-DETHASHCUDA=ON` - enable CUDA mining, `OFF` by default, - `-DETHSTRATUM=ON` - build with Stratum protocol support, `ON` by default. ## Maintainer [![Gitter](https://img.shields.io/gitter/room/ethereum-mining/ethminer.svg)][Gitter] - Paweł Bylica [@chfast](https://github.com/chfast) ## Contribute [![Gitter](https://img.shields.io/gitter/room/ethereum-mining/ethminer.svg)][Gitter] To meet the community, ask general questions and chat about ethminer join [the ethminer channel on Gitter][Gitter]. All bug reports, pull requests and code reviews are very much welcome. ## F.A.Q 1. Why is my hashrate with Nvidia cards on Windows 10 so low? The new WDDM 2.x driver on Windows 10 uses a different way of addressing the GPU. This is good for a lot of things, but not for ETH mining. For Kepler GPUs: I actually don't know. Please let me know what works best for good old Kepler. For Maxwell 1 GPUs: Unfortunately the issue is a bit more serious on the GTX750Ti, already causing suboptimal performance on Win7 and Linux. Apparently about 4MH/s can still be reached on Linux, which, depending on ETH price, could still be profitable, considering the relatively low power draw. For Maxwell 2 GPUs: There is a way of mining ETH at Win7/8/Linux speeds on Win10, by downgrading the GPU driver to a Win7 one (350.12 recommended) and using a build that was created using CUDA 6.5. For Pascal GPUs: You have to use the latest WDDM 2.1 compatible drivers in combination with Windows 10 Anniversary edition in order to get the full potential of your Pascal GPU. 2. Why is a GTX 1080 slower than a GTX 1070? Because of the GDDR5X memory, which can't be fully utilized for ETH mining (yet). 3. Are AMD cards also affected by slowdowns with increasing DAG size? Only GCN 1.0 GPUs (78x0, 79x0, 270, 280), but in a different way. You'll see that on each new epoch (30K blocks), the hashrate will go down a little bit. 4. Can I still mine ETH with my 2GB GPU? No. 5. What are the optimal launch parameters? The default parameters are fine in most scenario's (CUDA). For OpenCL it varies a bit more. Just play around with the numbers and use powers of 2. GPU's like powers of 2. 6. What does the ```--cuda-parallel-hash``` flag do? @davilizh made improvements to the CUDA kernel hashing process and added this flag to allow changing the number of tasks it runs in parallel. These improvements were optimised for GTX 1060 GPUs which saw a large increase in hashrate, GTX 1070 and GTX 1080/Ti GPUs saw some, but less, improvement. The default value is 4 (which does not need to be set with the flag) and in most cases this will provide the best performance. 7. What is ethminer's relationship with [Genoil's fork]? [Genoil's fork] was the original source of this version, but as Genoil is no longer consistently maintaining that fork it became almost impossible for developers to get new code merged there. In the interests of progressing development without waiting for reviews this fork should be considered the active one and Genoil's as legacy code. [Amazon S3 is needed]: https://docs.travis-ci.com/user/uploading-artifacts/ [AppVeyor]: https://ci.appveyor.com/project/ethereum-mining/ethminer [CMake]: https://cmake.org [CMake Build Tool Mode]: https://cmake.org/cmake/help/latest/manual/cmake.1.html#build-tool-mode [cpp-ethereum]: https://github.com/ethereum/cpp-ethereum [Genoil's fork]: https://github.com/Genoil/cpp-ethereum [Gitter]: https://gitter.im/ethereum-mining/ethminer [Hunter]: https://docs.hunter.sh [Releases]: https://github.com/ethereum-mining/ethminer/releases [Travis CI]: https://travis-ci.org/ethereum-mining/ethminer
{'content_hash': '7bc9a67494e3a0bcbb22bad87d85e9fd', 'timestamp': '', 'source': 'github', 'line_count': 191, 'max_line_length': 426, 'avg_line_length': 41.068062827225134, 'alnum_prop': 0.7389087200407956, 'repo_name': 'quantumpayment/bopminer', 'id': '8829082aa5823a7d4c1bc9b86b11dd211f98e202', 'size': '7861', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '87464'}, {'name': 'C++', 'bytes': '568233'}, {'name': 'CMake', 'bytes': '34069'}, {'name': 'Cuda', 'bytes': '50365'}, {'name': 'Shell', 'bytes': '2560'}]}
from accessData import getHDFData from voronoi import voronoi import inSituCluster as clusterLib import matplotlib.pyplot as plt from IPython import embed import numpy as np #import cv2 import os import scipy.spatial as kd kdt = None arr = None gradx = None grady = None grad = None imgCntr = 0 yPts = None xPts = None def createHist(inputData, lowerBound=None, upperBound=None, ignore=None): """ Create Histogram with matplotlib Parameters: data - The input data to be processed lowerBound - The smallest value to consider for the histogram upperBound - the largest value to consider for the histogram ignore - A list of values to ignore from the histogram """ data = inputData.copy() if ignore is not None: for val in ignore: # Consecutively remove the values to be ignored data = data[np.where(data != val)] if lowerBound is None: lowerBound = data.min() if upperBound is None: upperBound = data.max() sampleData = data[np.where(data < upperBound)] sampleData = sampleData[np.where(sampleData >= lowerBound)] sampleSize = sampleData.size # Scott's (1979) bin width. Based on the standard deviation # and the data size n = np.power(sampleSize, 1.0 / 3) std = np.std(sampleData) bin_width = (3.49 * std) / n histSize = int((upperBound - lowerBound) / bin_width) ranges = (lowerBound, upperBound) hist = plt.hist(sampleData, histSize, ranges) plt.axes().set_aspect('equal') plt.show() return hist def quantize(data, cutoff, numRegions=8, tolerance=0.0001): newData = data[::4, ::4] # Downsample data to speed up by a factor of 16 # Next remove clouds poorly represented data cleanData = newData[np.logical_and(newData > 0, newData < cutoff)] tess = voronoi(cleanData, numRegions, tolerance, data) thresh = [] for val in tess.values(): thresh.append(np.min(val)) thresh = np.sort(thresh) (rows, cols) = data.shape qData = np.ndarray((rows, cols), dtype='uint8') qData.fill(255) for val, t in enumerate(thresh): qData[data > t] = val + 1 qData[data == 0] = 0 # Put back the land values qData[data == -1] = 255 # Put back the cloud values return qData def colorMap(data): colors = [(123, 0, 255), (0, 0, 255), (0, 255, 255), (0, 255, 0), (123, 255, 0), (255, 255, 0), (255, 123, 0), (255, 0, 0)] (rows, cols) = data.shape color = np.ndarray((rows, cols, 3), dtype='uint8') color.fill(255) # Fill land with black color[data == 0] = (0, 0, 0) for i, c in enumerate(colors): color[data == i + 1] = c #plt.imshow(color) #plt.show() return color def writeClouds(data): # Only clouds should be left as -1 locs = np.where(data == -1) numPts = locs[0].size with open("data/clouds.dat", 'w') as fd: for i in xrange(numPts): if i % 100000 == 0: print i x = locs[0][i] y = locs[1][i] fd.write("%d %d\n" % (x, y)) def findSurroundingVal(qData, cluster, clusterVal=255): """ Summary: Check and see if the cluster is surrounded by a solid value, if it is, return the value which surrounds it. This one checks for border conditions Parameters: qData: The quantized satellite data. cluster: A 2D array of shape (2,n) where n is the number of points composing the cluster. The two rows are parallel arrays of x then y coordinates respectively. Returns: theValue: The surrounding value found. """ theValue = None lk = set([(0, 1), (1, 1), (1, 0), (-1, 0), (-1, 1)]) # Left Kernel rk = set([(1, -1), (1, 0), (-1, 0), (-1, -1), (0, -1)]) # Right Kernel tk = set([(1, -1), (0, 1), (1, 1), (0, -1), (1, 0)]) # Top Kernel bk = set([(-1, -1), (0, 1), (-1, 1), (0, -1), (-1, 0)]) # Bottom Kernel mk = np.array(tuple(lk.union(rk))) # Middle Kernel tlk = np.array(tuple(tk.intersection(lk))) # Top Left Kernel trk = np.array(tuple(tk.intersection(rk))) # Top Right Kernel blk = np.array(tuple(bk.intersection(lk))) # Bottom Left Kernel brk = np.array(tuple(bk.intersection(rk))) # Bottom Right Kernel lk = np.array(tuple(lk)) rk = np.array(tuple(rk)) tk = np.array(tuple(tk)) bk = np.array(tuple(bk)) rows, cols = qData.shape neighbors = {} for pt in cluster.T: row, col = pt k = None kused = None if row > 0: if col > 0: if row < rows - 1: if col < cols - 1: k = (mk + pt).T kused = "middle" else: k = (rk + pt).T kused = "right" elif col < cols - 1: k = (bk + pt).T kused = "bottom" else: k = (brk + pt).T kused = "bottom right" elif row < rows - 1: k = (lk + pt).T kused = "left" else: k = (blk + pt).T kused = "bottom left" elif col > 0: if col < cols - 1: k = (tk + pt).T kused = "top" else: k = (trk + pt).T kused = "top right" else: k = (tlk + pt).T kused = "top left" try: values = qData[tuple(k)] except: print "row %d out of %d" % (row, rows) print "col %d out of %d" % (col, cols) print "pt = ", pt print "k used = ", kused print "resulting k = ", k qData.fill(0) qData[tuple(pt)] = 255 plt.imshow(qData) plt.axes().set_aspect('equal') plt.show() if clusterVal == 255: for value in values: if value == clusterVal or value == 0 or value == 255: continue if theValue is None: theValue = value elif value != theValue: return None else: for value in values: if value == clusterVal or value == 0: continue if value in neighbors.keys(): neighbors[value] += 1 else: neighbors[value] = 1 maximum = 0 for k, v in neighbors.iteritems(): if v > maximum: theValue = k if theValue is None: return clusterVal else: return theValue def filter(img): """ Summary: A filter to remove all points with less than 3 neighbors. Parameters: img - The image to be filtered Returns: output - The filtered dataset. Same dimensions as img """ # Add the border mask cpy = np.ndarray((img.shape[0] + 2, img.shape[1] + 2)) cpy[:, 0] = 0 cpy[0, :] = 0 cpy[:, -1] = 0 cpy[-1, :] = 0 cpy[1:-1, 1:-1] = img.copy() h, w = cpy.shape for y in xrange(1, h - 2): for x in xrange(1, w - 2): val = img[y, x] # Extract a 3x3 sub matrix submat = cpy[y - 1:y + 2, x - 1:x + 2] #print "submat \n", submat #print "kernel \n", kernel numOccurence = submat[submat == val].size if numOccurence < 3: cpy[y, x] = 0.0 # So remove it! output = np.where(cpy == 1) return output def findMaximama(array): """ Find the maxima of a 1D array """ binSizes = array[0] binVals = array[1][:-1] c = (np.diff(np.sign(np.diff(binSizes))) < 0).nonzero()[0] + 1 # local max # Set to True to plot the maxima if False: plt.plot(binVals, binSizes) plt.plot(binVals[c], binSizes[c], "o", label="max") plt.legend() plt.axes().set_aspect('equal') plt.show() return binVals[c] def extractStepEdges(img): """ Summary: A filter to find all step edges in the dataset: img - The image to be filtered Returns: output - The filtered dataset. Same dimensions as img """ subImg = img[1:-1, 1:-1] pts = np.array(np.where(subImg == 1)) yVals = [] xVals = [] for y, x in pts.T: y += 1 # Pts were found with borders extracted x += 1 # Pts were found with borders extracted val = img[y,x] # Extract a 3x3 sub matrix submat = img[y - 1:y + 2, x - 1:x + 2] targetPts = np.logical_and(submat != val, submat != 255) numOccurence = submat[targetPts].size if numOccurence > 0: yVals.append(y) xVals.append(x) edgePts = np.array((yVals, xVals)) #img[(yVals, xVals)] = 8 #plt.imshow(colorMap(img)) #plt.show() return edgePts def buildKDTree(data): global kdt, arr arr = np.asarray(zip(data[0], data[1])) kdt = kd.cKDTree(arr) def getGrads(img, kernelSize): global gradx, grady, grad print "Computing xderiv" gradx = xDeriv(img, kernelSize) print "Computing yderiv" grady = yDeriv(img, kernelSize) def getSobelKernel(size, direction): if size % 2 == 0: print "\nKernel size must be odd!\n" exit() magic = size / 2 kernel = list() for i in xrange(-magic, magic + 1): row = list() if i < 0: pivot = i - magic for j in xrange(-magic, magic + 1): e = pivot + np.abs(j) row.append(e) kernel.append(row) elif i == 0: row = [0] * size kernel.append(row) else: pivot = i + magic for j in xrange(-magic, magic + 1): e = pivot - np.abs(j) row.append(e) kernel.append(row) if direction == 'y': return np.asarray(kernel) elif direction == 'x': return np.asarray(kernel).T def xDeriv(img, kernelSize): s = kernelSize if s % 2 == 0: sys.exit("Kernel size must be odd!\n") kx = getSobelKernel(s, 'x') h, w = img.shape xgrad = np.zeros(img.shape) sigma = s / 2 #blurImg = cv2.GaussianBlur(img, (s, s), sigma) for j in xrange(s / 2, h - s / 2): for i in xrange(s / 2, w - s / 2): submat = blurImg[j - s / 2: j + s / 2 + 1, i - s / 2: i + s / 2 + 1] val = (kx * submat).sum() xgrad[j, i] = val return xgrad def yDeriv(img, kernelSize): s = kernelSize if s % 2 == 0: sys.exit("Kernel size must be odd!\n") ky = getSobelKernel(s, 'y') h, w = img.shape ygrad = np.zeros(img.shape) sigma = s / 2 #blurImg = cv2.GaussianBlur(img, (s, s), sigma) for j in xrange(s / 2, h - s / 2): for i in xrange(s / 2, w - s / 2): submat = blurImg[j - s / 2: j + s / 2 + 1, i - s / 2: i + s / 2 + 1] val = (ky * submat).sum() ygrad[j, i] = val return ygrad def preprocess(data, cutoff): global kdt numRegions = 8 clustDist = 1 print "Quantizing the Data...\n" qData = quantize(data, cutoff, numRegions) #plt.figure(0) #plt.title("After Quantization") #plt.imshow(colorMap(qData)) # Cluster the Clouds using efficient KDT print "Clustering Clouds...\n" cloudsB4 = np.array(np.where(qData == 255)) C = clusterLib.Cluster() cloudClusters = C.clusterGrid(cloudsB4, clustDist) # Remove the clouds once and prepare for filtering print "Removing clouds...\n" cloudsB4 = np.array(np.where(qData == 255)) for cluster in cloudClusters: c = type(cluster) if c is int: c = [cluster] else: c = list(cluster) cloud = cloudsB4[:, c] val = findSurroundingVal(qData, cloud) if val is not None: qData[tuple(cloud)] = val #plt.figure(1) #plt.title("After Removing Clouds") #plt.imshow(colorMap(qData)) # Filter the data print "Filtering out Small Clusters...\n" for region in xrange(numRegions): clusterVal = numRegions - region if not clusterVal in qData: continue dataPts = np.array(np.where(qData == clusterVal)) print "\tFiltering %d Data Points in Region %d..." % \ (dataPts[0].size, clusterVal) C = clusterLib.Cluster() regionClusters = C.clusterGrid(dataPts, clustDist) for cluster in regionClusters: if type(cluster) is int or len(cluster) > 250: continue r = dataPts[:, tuple(cluster)] val = findSurroundingVal(qData, r, clusterVal) qData[tuple(r)] = val #plt.figure(2) #plt.title("After Filtering Data") #plt.imshow(colorMap(qData)) # Remove the clouds again print "Removing Clouds Again..." cloudsB4 = np.array(np.where(qData == 255)) C = clusterLib.Cluster() cloudClusters = C.clusterGrid(cloudsB4, clustDist) for cluster in cloudClusters: c = type(cluster) if c is int: c = [cluster] else: c = list(cluster) try: cloud = cloudsB4[:, c] except: embed() val = findSurroundingVal(qData, cloud) if val is not None: qData[tuple(cloud)] = val #plt.figure(3) #plt.title("After Removing Clouds After Filtering Data") #plt.imshow(colorMap(qData)) #plt.axes().set_aspect('equal') #plt.show() #print "Getting Gradient Values...\n" #if gradx is None or grady is None: #getGrads(qData, ptsBtwnKnts) print "Extracting Edges...\n" edgePts = extractStepEdges(qData) #colorData = colorMap(qData) #plt.imshow(colorData) #plt.axes().set_aspect('equal') #plt.show() return edgePts
{'content_hash': 'bca4c9d2224948497feaa31b3040fee1', 'timestamp': '', 'source': 'github', 'line_count': 501, 'max_line_length': 80, 'avg_line_length': 28.167664670658684, 'alnum_prop': 0.5290532879818595, 'repo_name': 'mathnathan/smartQuantization', 'id': '22b52df90cff7a73ff37c8378d4906a4518c9525', 'size': '14112', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'preprocessing.py', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '45169'}]}
"""Expectation value for a diagonal observable using a sampler primitive.""" from __future__ import annotations from collections.abc import Callable, Sequence, Mapping from typing import Any from dataclasses import dataclass import numpy as np from qiskit.algorithms.algorithm_job import AlgorithmJob from qiskit.circuit import QuantumCircuit from qiskit.primitives import BaseSampler, BaseEstimator, EstimatorResult from qiskit.primitives.utils import init_observable, _circuit_key from qiskit.opflow import PauliSumOp from qiskit.quantum_info import SparsePauliOp from qiskit.quantum_info.operators.base_operator import BaseOperator @dataclass(frozen=True) class _DiagonalEstimatorResult(EstimatorResult): """A result from an expectation of a diagonal observable.""" # TODO make each measurement a dataclass rather than a dict best_measurements: Sequence[Mapping[str, Any]] | None = None class _DiagonalEstimator(BaseEstimator): """An estimator for diagonal observables.""" def __init__( self, sampler: BaseSampler, aggregation: float | Callable[[Sequence[tuple[float, float]]], float] | None = None, callback: Callable[[Sequence[Mapping[str, Any]]], None] | None = None, **options, ) -> None: r"""Evaluate the expectation of quantum state with respect to a diagonal operator. Args: sampler: The sampler used to evaluate the circuits. aggregation: The aggregation function to aggregate the measurement outcomes. If a float this specified the CVaR :math:`\alpha` parameter. callback: A callback which is given the best measurements of all circuits in each evaluation. run_options: Options for the sampler. """ super().__init__(options=options) self.sampler = sampler if not callable(aggregation): aggregation = _get_cvar_aggregation(aggregation) self.aggregation = aggregation self.callback = callback def _run( self, circuits: Sequence[QuantumCircuit], observables: Sequence[BaseOperator | PauliSumOp], parameter_values: Sequence[Sequence[float]], **run_options, ) -> AlgorithmJob: circuit_indices = [] for circuit in circuits: key = _circuit_key(circuit) index = self._circuit_ids.get(key) if index is not None: circuit_indices.append(index) else: circuit_indices.append(len(self._circuits)) self._circuit_ids[key] = len(self._circuits) self._circuits.append(circuit) self._parameters.append(circuit.parameters) observable_indices = [] for observable in observables: index = self._observable_ids.get(id(observable)) if index is not None: observable_indices.append(index) else: observable_indices.append(len(self._observables)) self._observable_ids[id(observable)] = len(self._observables) converted_observable = init_observable(observable) _check_observable_is_diagonal(converted_observable) # check it's diagonal self._observables.append(converted_observable) job = AlgorithmJob( self._call, circuit_indices, observable_indices, parameter_values, **run_options ) job.submit() return job def _call( self, circuits: Sequence[int], observables: Sequence[int], parameter_values: Sequence[Sequence[float]], **run_options, ) -> _DiagonalEstimatorResult: job = self.sampler.run( [self._circuits[i] for i in circuits], parameter_values, **run_options, ) sampler_result = job.result() samples = sampler_result.quasi_dists # a list of dictionaries containing: {state: (measurement probability, value)} evaluations = [ { state: (probability, _evaluate_sparsepauli(state, self._observables[i])) for state, probability in sampled.items() } for i, sampled in zip(observables, samples) ] results = np.array([self.aggregation(evaluated.values()) for evaluated in evaluations]) # get the best measurements best_measurements = [] num_qubits = self._circuits[0].num_qubits for evaluated in evaluations: best_result = min(evaluated.items(), key=lambda x: x[1][1]) best_measurements.append( { "state": best_result[0], "bitstring": bin(best_result[0])[2:].zfill(num_qubits), "value": best_result[1][1], "probability": best_result[1][0], } ) if self.callback is not None: self.callback(best_measurements) return _DiagonalEstimatorResult( values=results, metadata=sampler_result.metadata, best_measurements=best_measurements ) def _get_cvar_aggregation(alpha): """Get the aggregation function for CVaR with confidence level ``alpha``.""" if alpha is None: alpha = 1 elif not 0 <= alpha <= 1: raise ValueError(f"alpha must be in [0, 1] but was {alpha}") # if alpha is close to 1 we can avoid the sorting if np.isclose(alpha, 1): def aggregate(measurements): return sum(probability * value for probability, value in measurements) else: def aggregate(measurements): # sort by values sorted_measurements = sorted(measurements, key=lambda x: x[1]) accumulated_percent = 0 # once alpha is reached, stop cvar = 0 for probability, value in sorted_measurements: cvar += value * max(probability, alpha - accumulated_percent) accumulated_percent += probability if accumulated_percent >= alpha: break return cvar / alpha return aggregate def _evaluate_sparsepauli(state: int, observable: SparsePauliOp) -> complex: return sum( coeff * _evaluate_bitstring(state, paulistring) for paulistring, coeff in observable.label_iter() ) def _evaluate_bitstring(state: int, paulistring: str) -> float: """Evaluate a bitstring on a Pauli label.""" n = len(paulistring) - 1 return np.prod( [-1 if state & (1 << (n - i)) else 1 for i, pauli in enumerate(paulistring) if pauli == "Z"] ) def _check_observable_is_diagonal(observable: SparsePauliOp) -> bool: is_diagonal = not np.any(observable.paulis.x) if not is_diagonal: raise ValueError("The observable must be diagonal.")
{'content_hash': '65b388c6e4cb2fc3e560d64bc8354443', 'timestamp': '', 'source': 'github', 'line_count': 190, 'max_line_length': 100, 'avg_line_length': 36.26315789473684, 'alnum_prop': 0.6169811320754717, 'repo_name': 'QISKit/qiskit-sdk-py', 'id': '67835c9e55a04dca65879ec5c4a4440f6699cc5c', 'size': '7368', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'qiskit/algorithms/minimum_eigensolvers/diagonal_estimator.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '2582'}, {'name': 'C++', 'bytes': '327518'}, {'name': 'CMake', 'bytes': '19294'}, {'name': 'Makefile', 'bytes': '5608'}, {'name': 'Pascal', 'bytes': '2444'}, {'name': 'Python', 'bytes': '1312801'}, {'name': 'Shell', 'bytes': '8385'}]}
/*jslint es5:true, indent:2, maxlen:80, node:true*/ /*global suite:true, test:true, suiteSetup:true, suiteTeardown:true, setup:true, teardown:true*/ // Mocha 'use strict'; // this module // http://stackoverflow.com/questions/1606797 function construct(constructor, args) { function F() { return constructor.apply(this, args); } F.prototype = constructor.prototype; return new F(); } // exports module.exports = function (SubArray, suite, test, assert) { [ [], ['a', 'b', 'c'] ].forEach(function (args) { suite('constructed with: ' + JSON.stringify(args), function () { var subArray; test('constructed without incident', function () { subArray = construct(SubArray, args); assert(true, 'made it without throwing errors'); }); test('detectable as an Array', function () { assert.equal(Object.prototype.toString.call(subArray), '[object Array]'); }); test('inherits from global Array', function () { assert(subArray instanceof Array, 'instanceof Array'); }); test('initial length is correct', function () { assert.equal(subArray.length, args.length); }); test('"last" method returns last of initial args', function () { var last = args.length ? args[args.length - 1] : undefined; assert(subArray.last, '"last" method exists'); assert.equal(subArray.last(), last); }); test('"push" adds a new last element', function () { subArray.push('last'); assert(subArray.last, '"last" method exists'); assert.equal(subArray.last(), 'last'); }); test('length is incremented post-"push"', function () { assert.equal(subArray.length, args.length + 1); }); test('"pop" returns last element', function () { assert.equal(subArray.pop(), 'last'); }); test('"last" method returns last of initial args', function () { var last = args.length ? args[args.length - 1] : undefined; assert(subArray.last, '"last" method exists'); assert.equal(subArray.last(), last); }); test('length is decremented post-"pop"', function () { assert.equal(subArray.length, args.length); }); test('setting length higher changes highest index', function () { subArray.length = 10; assert.equal(subArray.length, 10); subArray.push('last'); assert.equal(subArray.length, 11); assert.equal(subArray[10], 'last'); }); test('setting length lower changes highest index', function () { subArray.length = 0; assert.equal(subArray.length, 0); subArray.push('last'); assert.equal(subArray.length, 1); assert.equal(subArray[0], 'last'); }); test('add an element by direct index', function () { subArray[0] = 'abc'; assert.equal(subArray.length, 1, 'length is updated'); assert.equal(subArray[0], 'abc', 'element was stored/retrieved'); assert.equal(subArray.last(), 'abc', '"last" finds element'); }); test('add an element by higher direct index', function () { subArray[2] = 'abc'; assert.equal(subArray.length, 3, 'length is updated'); assert(!subArray[1], 'skipped index is falsey'); assert.equal(subArray[2], 'abc', 'element was stored/retrieved'); assert.equal(subArray.last(), 'abc', '"last" finds element'); }); }); }); }
{'content_hash': '4502a50c40fc200d1512c0d3ebed7d6c', 'timestamp': '', 'source': 'github', 'line_count': 107, 'max_line_length': 80, 'avg_line_length': 36.728971962616825, 'alnum_prop': 0.5302798982188295, 'repo_name': 'jokeyrhyme/js-sub-array-tests', 'id': '329976486606c177cb08a3f9cac3436c4852483d', 'size': '3930', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/tests.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '9598'}]}
/** * Keyboard class handles the keyboard state for the InputHandler */ class Keyboard { /** * Constructor for the Keyboard class */ constructor() { // Store state this.keys = {}; // Setup listeners for key events document.addEventListener('keydown', (e) => this._onKeyDown(e), false); document.addEventListener('keyup', (e) => this._onKeyUp(e), false); } /** * Callback listener for keydown event */ _onKeyDown(e) { this.keys[e.key.toLowerCase()] = true; e.preventDefault(); e.stopPropagation(); } /** * Callback listener for keyup event */ _onKeyUp(e) { this.keys[e.key.toLowerCase()] = false; } /** * Check if a key is down, * @param {string} key The key to check */ keyIsPressed(key) { if (this.keys[key.toLowerCase()]) { return true; } else { return false; } } } export { Keyboard as default };
{'content_hash': '63ea91615a683d532076681bf5b12a47', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 75, 'avg_line_length': 19.166666666666668, 'alnum_prop': 0.592391304347826, 'repo_name': 'nicholasnelson/uncondemned', 'id': '858d33ae2fcb2ec0f40ac4f109b9b20cff96f1e7', 'size': '2052', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/scripts/GameObjects/Player/InputHandler/Keyboard.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '2095'}, {'name': 'JavaScript', 'bytes': '1503530'}]}
--TEST-- phpunit-skelgen --class -- BankAccountTest _fixture/BankAccountTest.php BankAccount php://stdout --FILE-- <?php $_SERVER['argv'][1] = '--class'; $_SERVER['argv'][2] = '--'; $_SERVER['argv'][3] = 'BankAccountTest'; $_SERVER['argv'][4] = __DIR__ . DIRECTORY_SEPARATOR . '_fixture' . DIRECTORY_SEPARATOR . 'BankAccountTest.php'; $_SERVER['argv'][5] = 'BankAccount'; $_SERVER['argv'][6] = 'php://stdout'; require __DIR__ . '/../src/autoload.php'; $textui = new SebastianBergmann\PHPUnit\SkeletonGenerator\Command; $textui->main(); ?> --EXPECTF-- PHPUnit Skeleton Generator %s by Sebastian Bergmann. <?php /** * Generated by PHPUnit_SkeletonGenerator %s on %s at %s. */ class BankAccount { /** * @todo Implement depositMoney(). */ public function depositMoney() { // Remove the following line when you implement this method. throw new RuntimeException('Not yet implemented.'); } /** * @todo Implement getBalance(). */ public function getBalance() { // Remove the following line when you implement this method. throw new RuntimeException('Not yet implemented.'); } /** * @todo Implement withdrawMoney(). */ public function withdrawMoney() { // Remove the following line when you implement this method. throw new RuntimeException('Not yet implemented.'); } } Wrote skeleton for "BankAccount" to "php://stdout".
{'content_hash': '1261fd1db4c76b20988bb45b6c3c37f5', 'timestamp': '', 'source': 'github', 'line_count': 52, 'max_line_length': 111, 'avg_line_length': 27.78846153846154, 'alnum_prop': 0.6359861591695501, 'repo_name': 'kolodny/phpunit-skeleton-tester', 'id': '9f0516e502f406b8ca8a3711f92758bce66d523a', 'size': '1445', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/class-from-test.phpt', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'PHP', 'bytes': '66277'}]}
'use strict'; import Promise from 'bluebird'; import Joi from 'joi'; export default [ { path: '/v1/teams', method: 'GET', config: { handler: { async: Promise.coroutine(function* (request, reply) { let result = yield Promise.resolve([]); reply(result); }) } } }, { path: '/v1/teams', method: 'POST', config: { validate: { payload: Joi.object({ name: Joi.string().required().min(2).description('Team Name'), description: Joi.string().description('Team description'), members: Joi.array().unique().min(1).items(Joi.string().required()).description('Team Members'), isPublic: Joi.boolean().default(false).description('Is Public'), isActive: Joi.boolean().default(true).description('Is Active') }) }, handler: { async: Promise.coroutine(function* (request, reply) { let result = yield Promise.resolve({}); reply(result); }) } } }, { path: '/v1/teams/:id', method: 'GET', config: { validate: { params: { id: Joi.string() } }, handler: { async: Promise.coroutine(function* (request, reply) { let result = yield Promise.resolve({}); reply(result); }) } } }, { path: '/v1/teams/:id', method: 'PUT', config: { validate: { params: { id: Joi.string() }, payload: Joi.object({ name: Joi.string().required().min(2).description('Team Name'), description: Joi.string().description('Team description'), isPublic: Joi.boolean().default(false).description('Is Public'), isActive: Joi.boolean().default(true).description('Is Active') }) }, handler: { async: Promise.coroutine(function* (request, reply) { let result = yield Promise.resolve({}); reply(result); }) } } }, { path: '/v1/teams/:id', method: 'DELETE', config: { validate: { params: { id: Joi.string() } }, handler: { async: Promise.coroutine(function* (request, reply) { let result = yield Promise.resolve({}); reply(result); }) } } }, { path: '/v1/teams/:id/users/:userId', method: 'POST', config: { validate: { params: { id: Joi.string(), userId: Joi.string() }, payload: Joi.array().items(Joi.string()) }, handler: { async: Promise.coroutine(function* (request, reply) { let result = yield Promise.resolve({}); reply(result); }) } } }, { path: '/v1/teams/:id/users/:userId', method: 'DELETE', config: { validate: { params: { id: Joi.string(), userId: Joi.string() } }, handler: { async: Promise.coroutine(function* (request, reply) { let result = yield Promise.resolve({}); reply(result); }) } } } ]
{'content_hash': '69accbb792f0b5ab68a4cdaf8038a09e', 'timestamp': '', 'source': 'github', 'line_count': 134, 'max_line_length': 106, 'avg_line_length': 23.67910447761194, 'alnum_prop': 0.49196344153797666, 'repo_name': 'TylerGarlick/convergent-api', 'id': '6e9ba9f4fbf7bbec0bc78cc65849d7ac7bfb89e2', 'size': '3173', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'routes/teams.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '12617'}]}
<!-- partial HTML of patch panel app --> <div id="ov-sample-custom" ng-controller="OvSampleCustomCtrl"> <div class="button-panel"> <div class="my-button" ng-click="getData()"> Load Devices </div> </div> <div class="data-panel"> <div> <label>Devices: <select ng-model="myDev" ng-options="dev.name for dev in devices"></select> </label> </div> </div> <div class="button-panel"> <div class="my-button" ng-click="loadPorts()"> Load Ports </div> </div> <div class="data-panel2"> <label>First Port: <select ng-model="myPort1" ng-options="port.name for port in ports"></select> </label> <label>Second Port: <select ng-model="myPort2" ng-options="port.name for port in ports"></select> </label> </div> <div class="button-panel"> <div class="my-button" ng-click="done()"> Patch! </div> </div> <div class="data-panel3"> <p> <span class="quote">{{data.message}} </span> </p> <pre> </pre> </div> <div class="button-panel"> <div class="my-button" ng-click="used()"> ConnectPoints in use </div> </div> <div class="data-panel4"> <p> <span class="quote">{{data.cpoints}} </span> </p> </div> </div>
{'content_hash': 'a1c33d0a615ef548ab9826888cf05960', 'timestamp': '', 'source': 'github', 'line_count': 54, 'max_line_length': 91, 'avg_line_length': 26.77777777777778, 'alnum_prop': 0.4972337482710927, 'repo_name': 'wuwenbin2/onos_bgp_evpn', 'id': '34204b4de3f2e852583e1fe73660d07897c2cf37', 'size': '1446', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'apps/patchpanel/src/main/resources/app/view/sampleCustom/sampleCustom.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '211779'}, {'name': 'Groff', 'bytes': '1090'}, {'name': 'HTML', 'bytes': '177259'}, {'name': 'Java', 'bytes': '25432628'}, {'name': 'JavaScript', 'bytes': '2970699'}, {'name': 'Protocol Buffer', 'bytes': '8451'}, {'name': 'Python', 'bytes': '126671'}, {'name': 'Shell', 'bytes': '913'}, {'name': 'Thrift', 'bytes': '16641'}]}
export const REQUESTS_BEGIN = 'REQUESTS_BEGIN'; export const REQUESTS_END = 'REQUESTS_END'; export const REQUESTS_ERROR = 'REQUESTS_ERROR'; // UI export const UPDATE_EQUIPMENT_LIST_UI = 'UPDATE_EQUIPMENT_LIST_UI'; export const UPDATE_PHYSICAL_ATTACHMENTS_UI = 'UPDATE_PHYSICAL_ATTACHMENTS_UI'; export const UPDATE_OWNERS_UI = 'UPDATE_OWNERS_UI'; export const UPDATE_OWNER_CONTACTS_UI = 'UPDATE_OWNER_CONTACTS_UI'; export const UPDATE_OWNER_EQUIPMENT_UI = 'UPDATE_OWNER_EQUIPMENT_UI'; export const UPDATE_USERS_UI = 'UPDATE_USERS_UI'; export const UPDATE_PROJECTS_UI = 'UPDATE_PROJECTS_UI'; export const UPDATE_PROJECT_CONTACTS_UI = 'UPDATE_PROJECT_CONTACTS_UI'; export const UPDATE_RENTAL_REQUESTS_UI = 'UPDATE_RENTAL_REQUESTS_UI'; export const UPDATE_USER_ROLES_UI = 'UPDATE_USER_ROLES_UI'; export const UPDATE_GROUPS_LOOKUP = 'UPDATE_GROUPS_LOOKUP'; export const UPDATE_PERMISSIONS_LOOKUP = 'UPDATE_PERMISSIONS_LOOKUP'; export const UPDATE_ROLES_UI = 'UPDATE_ROLES_UI'; export const UPDATE_HISTORY_UI = 'UPDATE_HISTORY_UI'; export const UPDATE_DOCUMENTS_UI = 'UPDATE_DOCUMENTS_UI'; // Search export const UPDATE_EQUIPMENT_LIST_SEARCH = 'UPDATE_EQUIPMENT_LIST_SEARCH'; export const UPDATE_OWNERS_SEARCH = 'UPDATE_OWNERS_SEARCH'; export const UPDATE_PROJECTS_SEARCH = 'UPDATE_PROJECTS_SEARCH'; export const UPDATE_RENTAL_REQUESTS_SEARCH = 'UPDATE_RENTAL_REQUESTS_SEARCH'; export const UPDATE_USERS_SEARCH = 'UPDATE_USERS_SEARCH'; export const UPDATE_ROLES_SEARCH = 'UPDATE_ROLES_SEARCH'; // Lookups export const UPDATE_CITIES_LOOKUP = 'UPDATE_CITIES'; export const UPDATE_DISTRICTS_LOOKUP = 'UPDATE_DISTRICTS'; export const UPDATE_REGIONS_LOOKUP = 'UPDATE_REGIONS'; export const UPDATE_SERVICE_AREAS_LOOKUP = 'UPDATE_SERVICE_AREAS'; export const UPDATE_LOCAL_AREAS_LOOKUP = 'UPDATE_LOCAL_AREAS'; export const UPDATE_OWNERS_LOOKUP = 'UPDATE_OWNERS_LOOKUP'; export const UPDATE_DISTRICT_EQUIPMENT_TYPES_LOOKUP = 'UPDATE_DISTRICT_EQUIPMENT_TYPES_LOOKUP'; export const UPDATE_EQUIPMENT_TYPES_LOOKUP = 'UPDATE_EQUIPMENT_TYPES_LOOKUP'; export const UPDATE_ROLES_LOOKUP = 'UPDATE_ROLES_LOOKUP'; export const UPDATE_PROJECTS_LOOKUP = 'UPDATE_PROJECTS_LOOKUP'; export const UPDATE_USERS_LOOKUP = 'UPDATE_USERS_LOOKUP'; // Current User export const UPDATE_CURRENT_USER = 'UPDATE_CURRENT_USER'; // Users export const UPDATE_USERS = 'UPDATE_USERS'; export const UPDATE_USER = 'UPDATE_USER'; export const ADD_USER = 'ADD_USER'; export const DELETE_USER = 'DELETE_USER'; // Favourites export const UPDATE_FAVOURITES = 'UPDATE_FAVOURITES'; export const ADD_FAVOURITE = 'ADD_FAVOURITE'; export const UPDATE_FAVOURITE = 'UPDATE_FAVOURITE'; export const DELETE_FAVOURITE = 'DELETE_FAVOURITE'; // Contacts export const UPDATE_CONTACTS = 'UPDATE_CONTACTS'; export const ADD_CONTACT = 'ADD_CONTACT'; export const UPDATE_CONTACT = 'UPDATE_CONTACT'; export const DELETE_CONTACT = 'DELETE_CONTACT'; // Documents export const UPDATE_DOCUMENTS = 'UPDATE_DOCUMENTS'; export const ADD_DOCUMENT = 'ADD_DOCUMENT'; export const UPDATE_DOCUMENT = 'UPDATE_DOCUMENT'; export const DELETE_DOCUMENT = 'DELETE_DOCUMENT'; // Roles, Permissions export const UPDATE_ROLES = 'UPDATE_ROLES'; export const UPDATE_ROLE = 'UPDATE_ROLE'; export const ADD_ROLE = 'ADD_ROLE'; export const DELETE_ROLE = 'DELETE_ROLE'; export const UPDATE_ROLE_PERMISSIONS = 'UPDATE_ROLE_PERMISSIONS'; // Equipment export const UPDATE_EQUIPMENT_LIST = 'UPDATE_EQUIPMENT_LIST'; export const ADD_EQUIPMENT = 'ADD_EQUIPMENT'; export const UPDATE_EQUIPMENT = 'UPDATE_EQUIPMENT'; // Owners export const UPDATE_OWNERS = 'UPDATE_OWNERS'; export const UPDATE_OWNER = 'UPDATE_OWNER'; export const ADD_OWNER = 'ADD_OWNER'; export const DELETE_OWNER = 'DELETE_OWNER'; // Projects export const UPDATE_PROJECTS = 'UPDATE_PROJECTS'; export const UPDATE_PROJECT = 'UPDATE_PROJECT'; export const ADD_PROJECT = 'ADD_PROJECT'; // Rental Requests export const UPDATE_RENTAL_REQUESTS = 'UPDATE_RENTAL_REQUESTS'; export const UPDATE_RENTAL_REQUEST = 'UPDATE_RENTAL_REQUEST'; export const ADD_RENTAL_REQUEST = 'ADD_RENTAL_REQUEST'; // Rotation List export const UPDATE_RENTAL_REQUEST_ROTATION_LIST = 'UPDATE_RENTAL_REQUEST_ROTATION_LIST'; // Rental Agreements export const UPDATE_RENTAL_AGREEMENT = 'UPDATE_RENTAL_AGREEMENT'; export const ADD_RENTAL_AGREEMENT = 'ADD_RENTAL_AGREEMENT'; // Rental Rates, Conditions export const ADD_RENTAL_RATE = 'ADD_RENTAL_RATE'; export const UPDATE_RENTAL_RATE = 'UPDATE_RENTAL_RATE'; export const DELETE_RENTAL_RATE = 'DELETE_RENTAL_RATE'; export const ADD_RENTAL_CONDITION = 'ADD_RENTAL_CONDITION'; export const UPDATE_RENTAL_CONDITION = 'UPDATE_RENTAL_CONDITION'; export const DELETE_RENTAL_CONDITION = 'DELETE_RENTAL_CONDITION'; // Version export const UPDATE_VERSION = 'UPDATE_VERSION'; // History export const UPDATE_HISTORY = 'UPDATE_HISTORY';
{'content_hash': '176b50923ec8745d4f6e2a8f58e9967f', 'timestamp': '', 'source': 'github', 'line_count': 117, 'max_line_length': 95, 'avg_line_length': 41.162393162393165, 'alnum_prop': 0.7693106312292359, 'repo_name': 'plavoieBC/hets', 'id': 'b05fd770c24c5837e698b0e4cf863c91f5ebb686', 'size': '4832', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Client/src/js/actionTypes.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '9077'}, {'name': 'C#', 'bytes': '4126242'}, {'name': 'CSS', 'bytes': '60442'}, {'name': 'HTML', 'bytes': '343352'}, {'name': 'JavaScript', 'bytes': '475168'}, {'name': 'PowerShell', 'bytes': '805'}, {'name': 'Python', 'bytes': '4784'}, {'name': 'Shell', 'bytes': '5609'}]}
'use strict'; describe('Controller: MainCtrl', function () { // load the controller's module beforeEach(module('autocompleteApp')); var MainCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); MainCtrl = $controller('MainCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings.length).toBe(3); }); });
{'content_hash': '3ff1f6cd980772cf590a61f6e9038f5e', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 72, 'avg_line_length': 23.227272727272727, 'alnum_prop': 0.6516634050880626, 'repo_name': 'theoinglis/controls', 'id': '0c1d617c2f9130e104fdd7ff679bc11ec23f78b1', 'size': '511', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/spec/controllers/main.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '3936'}, {'name': 'JavaScript', 'bytes': '81966'}]}
import {LocalStore} from "fluxx" import * as actions from "./playFormActions" import { defaultFieldValidation, FieldValidation, updateFieldValidation, updateUnchangedFieldValidation, Valid } from "../../../framework/utils/Validation" import { validateFuture, validateNonBlank, validateNonEmptyArray, validateNotNull, validatePositiveNumber } from "../../../common/commonValidations" import {copy} from "../../../framework/utils/object"; import {Theater} from "../../theater/theaterModel"; import messages from "../../../framework/messages"; import * as arrays from "../../../framework/utils/arrays"; import {Company} from "../../company/companyModel"; import {Show} from "../../show/showModel"; export interface PlayFormState { step: "loading" | "form" | "success" company: Company show: Show availableTheaters: Array<Theater> id?: string theater: FieldValidation<string> dates: FieldValidation<Array<DateValidation>> prices: FieldValidation<Array<PriceValidation>> errors?: Array<string> } export interface PriceValidation { name: FieldValidation<string> value: FieldValidation<number> condition: FieldValidation<string> } export interface DateValidation { date: FieldValidation<Date> reservationEndDate: FieldValidation<Date> } const defaultDateValidation: DateValidation = { date: defaultFieldValidation(null), reservationEndDate: defaultFieldValidation(null) } const defaultPriceValidation: PriceValidation = { name: defaultFieldValidation(""), value: defaultFieldValidation(0), condition: defaultFieldValidation("") } const initialState: PlayFormState = { step: "loading", company: null, show: null, availableTheaters: [], theater: defaultFieldValidation(""), dates: defaultFieldValidation([defaultDateValidation]), prices: defaultFieldValidation([defaultPriceValidation]) } export const playFormStore = () => LocalStore(initialState, on => { on(actions.initialize, (state, {company, show, play, theaters}) => { if (play) { return copy(state, { step: "form", company, show, availableTheaters: theaters, id: play.id, theater: defaultFieldValidation(play.theater.id), dates: defaultFieldValidation([{ date: defaultFieldValidation(play.date), reservationEndDate: defaultFieldValidation(play.reservationEndDate) }]), prices: defaultFieldValidation( play.prices.map(price => ({ name: defaultFieldValidation(price.name), value: defaultFieldValidation(price.value), condition: defaultFieldValidation(price.condition) })) ) }) } else { return copy(state, {step: "form", company, show, availableTheaters: theaters}) } }) on(actions.updateTheater, (state, value) => { return copy(state, { theater: updateFieldValidation(state.theater, value, validateNonBlank(value)) }) }) on(actions.addDate, (state) => { return updateDates(state, arrays.append(state.dates.value, defaultDateValidation)) }) on(actions.removeDate, (state, index) => { return updateDates(state, arrays.remove(state.dates.value, index)) }) on(actions.updateDate, (state, {index, value}) => { const currentDate = state.dates.value[index] return updateDates(state, arrays.replace(state.dates.value, index, copy(currentDate, { date: updateFieldValidation(currentDate.date, value, validateNotNull(value).flatMap(validateFuture)), reservationEndDate: updateUnchangedFieldValidation(currentDate.reservationEndDate, currentDate.reservationEndDate.value, validateReservationEndDate(currentDate.reservationEndDate.value, value)) }))) }) on(actions.updateReservationEndDate, (state, {index, value}) => { const currentDate = state.dates.value[index] return updateDates(state, arrays.replace(state.dates.value, index, copy(currentDate, { reservationEndDate: updateFieldValidation(currentDate.reservationEndDate, value, validateReservationEndDate(value, currentDate.date.value)) }))) }) on(actions.addPrice, (state) => { return updatePrices(state, arrays.append(state.prices.value, defaultPriceValidation)) }) on(actions.removePrice, (state, index) => { return updatePrices(state, arrays.remove(state.prices.value, index)) }) on(actions.updatePriceName, (state, {index, value}) => { const currentPrice = state.prices.value[index] return updatePrices(state, arrays.replace(state.prices.value, index, copy(currentPrice, { name: updateFieldValidation(currentPrice.name, value, validateNonBlank(value)) }))) }) on(actions.updatePriceValue, (state, {index, value}) => { const currentPrice = state.prices.value[index] return updatePrices(state, arrays.replace(state.prices.value, index, copy(currentPrice, { value: updateFieldValidation(currentPrice.value, value, validatePositiveNumber(value)) }))) }) on(actions.updatePriceCondition, (state, {index, value}) => { const currentPrice = state.prices.value[index] return updatePrices(state, arrays.replace(state.prices.value, index, copy(currentPrice, { condition: updateFieldValidation(currentPrice.condition, value, Valid(value)) }))) }) on(actions.closeErrors, (state) => { return copy(state, {errors: null}) }) on(actions.success, (state) => { return copy(state, {step: "success"}) }) }) function validateReservationEndDate(reservationEndDate: Date, date: Date) { return validateNotNull(reservationEndDate) .flatMap(validateFuture) .filter(reservationEndDate => reservationEndDate < date, messages.production.play.form.reservationEndDateAfterDate) } function updateDates(state: PlayFormState, dates: Array<DateValidation>) { return copy(state, { dates: updateFieldValidation(state.dates, dates, validateDates(dates)) }) } function validateDates(dates: Array<DateValidation>) { return validateNonEmptyArray(dates) } function updatePrices(state: PlayFormState, prices: Array<PriceValidation>) { return copy(state, { prices: updateFieldValidation(state.prices, prices, validatePrices(prices)) }) } function validatePrices(prices: Array<PriceValidation>) { return validateNonEmptyArray(prices) }
{'content_hash': '289114cbb8eef6641f0314e1ad35e0e0', 'timestamp': '', 'source': 'github', 'line_count': 180, 'max_line_length': 199, 'avg_line_length': 34.833333333333336, 'alnum_prop': 0.7207336523125997, 'repo_name': 'kneelnrise/vep', 'id': '5858c3ce17fdfd9bbedaacdd09a2d323d9471be1', 'size': '6270', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/client/app/production/play/playForm/playFormStore.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1507'}, {'name': 'HTML', 'bytes': '86391'}, {'name': 'JavaScript', 'bytes': '69698'}, {'name': 'Scala', 'bytes': '430360'}, {'name': 'Shell', 'bytes': '1778'}]}
[![standard-readme compliant](https://img.shields.io/badge/readme%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/RichardLitt/standard-readme) > HTTP frontend to the Cisco Webex JS SDK Why would we put an http server in front of our SDK? Encryption is hard and this lets all of our client test suites (potentially written in languages for which we do not have sdks) do encrypted things without a major time expenditure - [Install](#install) - [Usage](#usage) - [Contribute](#contribute) - [Maintainers](#maintainers) - [License](#license) ## Install ```bash npm install -g @webex/webex-server ``` ## Usage Start the daemon ```bash webex-server ``` Create a session (make sure to copy your set cookie header) ```bash curl -X POST \ -H "Content-Type: application/json" \ -d '{"clientId":"<your client id>","clientSecret":"<your client secret>","redirectUri":"<your redirect_uri>","scope":"<your scopes>"}' \ http://localhost:3000/api/v1/session ``` (optional) Create a conversation > SDK: webex.internal.conversation.create({comment: 'first comment', displayName: 'title', participants: ['<userId1>', '<userId2>', '<userId3>']}) ``` curl -X POST \ -H "Content-Type: application/json" \ -H "Cookie: <connect.sid cookie from step one>" \ -d '[{"comment":"first message","displayName":"title","participants":["userId1","userId2","userId3"]}]' -v \ http://localhost:3000/api/v1/session/invoke/internal/conversation/create ``` (optional) Post a message > SDK: `webex.inernal.conversation.post({url: '<conversation url>', {displayName: 'second comment'}})` ``` curl -X POST \ -H "Content-Type: application/json" \ -H "Cookie: <connect.sid cookie from step one>" \ -d [{"url":"<conversation url>"},{"displayName":"second comment"}] -v \ http://localhost:3000/api/v1/session/invoke/internal/conversation/post ``` (optional) Fetch a conversation > SDK: `webex.internal.conversation.get({url: '<conversation url>'})` > SDK: `webex.internal.conversation.get({url: '<conversation url>'})` ``` curl -X POST \ -H "Content-Type: application/json" \ -H "Cookie: <connect.sid cookie from step one>" \ -d [{"url":"<conversation url>"}] -v \ http://localhost:3000/api/v1/session/invoke/internal/conversation/get ``` Clean up your session (If you don't do this, you'll have a bunch of long-running web socket connections) ``` curl -X DELETE \ -H "Content-Type: application/json" \ -H "Cookie: <connect.sid cookie from step one>" \ -v \ http://localhost:3000/api/v1/session ``` ## Maintainers This package is maintained by [Cisco Webex for Developers](https://developer.webex.com/). ## Contribute Pull requests welcome. Please see [CONTRIBUTING.md](https://github.com/webex/webex-js-sdk/blob/master/CONTRIBUTING.md) for more details. ## License © 2016-2019 Cisco and/or its affiliates. All Rights Reserved.
{'content_hash': '3973dcd97084c8ce044d305421e07c44', 'timestamp': '', 'source': 'github', 'line_count': 96, 'max_line_length': 233, 'avg_line_length': 30.020833333333332, 'alnum_prop': 0.7002081887578071, 'repo_name': 'bbender/spark-js-sdk', 'id': 'd409b7632c7179312aeeb871649f17e4e36a7ac0', 'size': '2906', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'packages/node_modules/@webex/webex-server/README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Dockerfile', 'bytes': '877'}, {'name': 'JavaScript', 'bytes': '112240'}, {'name': 'Python', 'bytes': '4743'}, {'name': 'Shell', 'bytes': '21329'}]}
cmake_minimum_required( VERSION 2.6.3 ) if( DEFINED CMAKE_CROSSCOMPILING ) # subsequent toolchain loading is not really needed return() endif() if( CMAKE_TOOLCHAIN_FILE ) # touch toolchain variable only to suppress "unused variable" warning endif() get_property( _CMAKE_IN_TRY_COMPILE GLOBAL PROPERTY IN_TRY_COMPILE ) if( _CMAKE_IN_TRY_COMPILE ) include( "${CMAKE_CURRENT_SOURCE_DIR}/../android.toolchain.config.cmake" OPTIONAL ) endif() # this one is important set( CMAKE_SYSTEM_NAME Linux ) # this one not so much set( CMAKE_SYSTEM_VERSION 1 ) # rpath makes low sence for Android set( CMAKE_SKIP_RPATH TRUE CACHE BOOL "If set, runtime paths are not added when using shared libraries." ) set( ANDROID_SUPPORTED_NDK_VERSIONS ${ANDROID_EXTRA_NDK_VERSIONS} -r9d -r9c -r9b -r9 -r8e -r8d -r8c -r8b -r8 -r7c -r7b -r7 -r6b -r6 -r5c -r5b -r5 "" ) if(NOT DEFINED ANDROID_NDK_SEARCH_PATHS) if( CMAKE_HOST_WIN32 ) file( TO_CMAKE_PATH "$ENV{PROGRAMFILES}" ANDROID_NDK_SEARCH_PATHS ) set( ANDROID_NDK_SEARCH_PATHS "${ANDROID_NDK_SEARCH_PATHS}/android-ndk" "$ENV{SystemDrive}/NVPACK/android-ndk" ) else() file( TO_CMAKE_PATH "$ENV{HOME}" ANDROID_NDK_SEARCH_PATHS ) set( ANDROID_NDK_SEARCH_PATHS /opt/android-ndk "${ANDROID_NDK_SEARCH_PATHS}/NVPACK/android-ndk" ) endif() endif() if(NOT DEFINED ANDROID_STANDALONE_TOOLCHAIN_SEARCH_PATH) set( ANDROID_STANDALONE_TOOLCHAIN_SEARCH_PATH /opt/android-toolchain ) endif() set( ANDROID_SUPPORTED_ABIS_arm "armeabi-v7a;armeabi;armeabi-v7a with NEON;armeabi-v7a with VFPV3;armeabi-v6 with VFP" ) set( ANDROID_SUPPORTED_ABIS_x86 "x86" ) set( ANDROID_SUPPORTED_ABIS_mipsel "mips" ) set( ANDROID_DEFAULT_NDK_API_LEVEL 15 ) set( ANDROID_DEFAULT_NDK_API_LEVEL_x86 15 ) set( ANDROID_DEFAULT_NDK_API_LEVEL_mips 15 ) macro( __LIST_FILTER listvar regex ) if( ${listvar} ) foreach( __val ${${listvar}} ) if( __val MATCHES "${regex}" ) list( REMOVE_ITEM ${listvar} "${__val}" ) endif() endforeach() endif() endmacro() macro( __INIT_VARIABLE var_name ) set( __test_path 0 ) foreach( __var ${ARGN} ) if( __var STREQUAL "PATH" ) set( __test_path 1 ) break() endif() endforeach() if( __test_path AND NOT EXISTS "${${var_name}}" ) unset( ${var_name} CACHE ) endif() if( "${${var_name}}" STREQUAL "" ) set( __values 0 ) foreach( __var ${ARGN} ) if( __var STREQUAL "VALUES" ) set( __values 1 ) elseif( NOT __var STREQUAL "PATH" ) set( __obsolete 0 ) if( __var MATCHES "^OBSOLETE_.*$" ) string( REPLACE "OBSOLETE_" "" __var "${__var}" ) set( __obsolete 1 ) endif() if( __var MATCHES "^ENV_.*$" ) string( REPLACE "ENV_" "" __var "${__var}" ) set( __value "$ENV{${__var}}" ) elseif( DEFINED ${__var} ) set( __value "${${__var}}" ) else() if( __values ) set( __value "${__var}" ) else() set( __value "" ) endif() endif() if( NOT "${__value}" STREQUAL "" ) if( __test_path ) if( EXISTS "${__value}" ) file( TO_CMAKE_PATH "${__value}" ${var_name} ) if( __obsolete AND NOT _CMAKE_IN_TRY_COMPILE ) message( WARNING "Using value of obsolete variable ${__var} as initial value for ${var_name}. Please note, that ${__var} can be completely removed in future versions of the toolchain." ) endif() break() endif() else() set( ${var_name} "${__value}" ) if( __obsolete AND NOT _CMAKE_IN_TRY_COMPILE ) message( WARNING "Using value of obsolete variable ${__var} as initial value for ${var_name}. Please note, that ${__var} can be completely removed in future versions of the toolchain." ) endif() break() endif() endif() endif() endforeach() unset( __value ) unset( __values ) unset( __obsolete ) elseif( __test_path ) file( TO_CMAKE_PATH "${${var_name}}" ${var_name} ) endif() unset( __test_path ) endmacro() macro( __DETECT_NATIVE_API_LEVEL _var _path ) SET( __ndkApiLevelRegex "^[\t ]*#define[\t ]+__ANDROID_API__[\t ]+([0-9]+)[\t ]*$" ) FILE( STRINGS ${_path} __apiFileContent REGEX "${__ndkApiLevelRegex}" ) if( NOT __apiFileContent ) message( SEND_ERROR "Could not get Android native API level. Probably you have specified invalid level value, or your copy of NDK/toolchain is broken." ) endif() string( REGEX REPLACE "${__ndkApiLevelRegex}" "\\1" ${_var} "${__apiFileContent}" ) unset( __apiFileContent ) unset( __ndkApiLevelRegex ) endmacro() macro( __DETECT_TOOLCHAIN_MACHINE_NAME _var _root ) if( EXISTS "${_root}" ) file( GLOB __gccExePath RELATIVE "${_root}/bin/" "${_root}/bin/*-gcc${TOOL_OS_SUFFIX}" ) __LIST_FILTER( __gccExePath "^[.].*" ) list( LENGTH __gccExePath __gccExePathsCount ) if( NOT __gccExePathsCount EQUAL 1 AND NOT _CMAKE_IN_TRY_COMPILE ) message( WARNING "Could not determine machine name for compiler from ${_root}" ) set( ${_var} "" ) else() get_filename_component( __gccExeName "${__gccExePath}" NAME_WE ) string( REPLACE "-gcc" "" ${_var} "${__gccExeName}" ) endif() unset( __gccExePath ) unset( __gccExePathsCount ) unset( __gccExeName ) else() set( ${_var} "" ) endif() endmacro() # fight against cygwin set( ANDROID_FORBID_SYGWIN TRUE CACHE BOOL "Prevent cmake from working under cygwin and using cygwin tools") mark_as_advanced( ANDROID_FORBID_SYGWIN ) if( ANDROID_FORBID_SYGWIN ) if( CYGWIN ) message( FATAL_ERROR "Android NDK and android-cmake toolchain are not welcome Cygwin. It is unlikely that this cmake toolchain will work under cygwin. But if you want to try then you can set cmake variable ANDROID_FORBID_SYGWIN to FALSE and rerun cmake." ) endif() if( CMAKE_HOST_WIN32 ) # remove cygwin from PATH set( __new_path "$ENV{PATH}") __LIST_FILTER( __new_path "cygwin" ) set(ENV{PATH} "${__new_path}") unset(__new_path) endif() endif() # detect current host platform if( NOT DEFINED ANDROID_NDK_HOST_X64 AND (CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "amd64|x86_64|AMD64" OR CMAKE_HOST_APPLE) ) set( ANDROID_NDK_HOST_X64 1 CACHE BOOL "Try to use 64-bit compiler toolchain" ) mark_as_advanced( ANDROID_NDK_HOST_X64 ) endif() set( TOOL_OS_SUFFIX "" ) if( CMAKE_HOST_APPLE ) set( ANDROID_NDK_HOST_SYSTEM_NAME "darwin-x86_64" ) set( ANDROID_NDK_HOST_SYSTEM_NAME2 "darwin-x86" ) elseif( CMAKE_HOST_WIN32 ) set( ANDROID_NDK_HOST_SYSTEM_NAME "windows-x86_64" ) set( ANDROID_NDK_HOST_SYSTEM_NAME2 "windows" ) set( TOOL_OS_SUFFIX ".exe" ) elseif( CMAKE_HOST_UNIX ) set( ANDROID_NDK_HOST_SYSTEM_NAME "linux-x86_64" ) set( ANDROID_NDK_HOST_SYSTEM_NAME2 "linux-x86" ) else() message( FATAL_ERROR "Cross-compilation on your platform is not supported by this cmake toolchain" ) endif() if( NOT ANDROID_NDK_HOST_X64 ) set( ANDROID_NDK_HOST_SYSTEM_NAME ${ANDROID_NDK_HOST_SYSTEM_NAME2} ) endif() # see if we have path to Android NDK __INIT_VARIABLE( ANDROID_NDK PATH ENV_ANDROID_NDK ) if( NOT ANDROID_NDK ) # see if we have path to Android standalone toolchain __INIT_VARIABLE( ANDROID_STANDALONE_TOOLCHAIN PATH ENV_ANDROID_STANDALONE_TOOLCHAIN OBSOLETE_ANDROID_NDK_TOOLCHAIN_ROOT OBSOLETE_ENV_ANDROID_NDK_TOOLCHAIN_ROOT ) if( NOT ANDROID_STANDALONE_TOOLCHAIN ) #try to find Android NDK in one of the the default locations set( __ndkSearchPaths ) foreach( __ndkSearchPath ${ANDROID_NDK_SEARCH_PATHS} ) foreach( suffix ${ANDROID_SUPPORTED_NDK_VERSIONS} ) list( APPEND __ndkSearchPaths "${__ndkSearchPath}${suffix}" ) endforeach() endforeach() __INIT_VARIABLE( ANDROID_NDK PATH VALUES ${__ndkSearchPaths} ) unset( __ndkSearchPaths ) if( ANDROID_NDK ) message( STATUS "Using default path for Android NDK: ${ANDROID_NDK}" ) message( STATUS " If you prefer to use a different location, please define a cmake or environment variable: ANDROID_NDK" ) else() #try to find Android standalone toolchain in one of the the default locations __INIT_VARIABLE( ANDROID_STANDALONE_TOOLCHAIN PATH ANDROID_STANDALONE_TOOLCHAIN_SEARCH_PATH ) if( ANDROID_STANDALONE_TOOLCHAIN ) message( STATUS "Using default path for standalone toolchain ${ANDROID_STANDALONE_TOOLCHAIN}" ) message( STATUS " If you prefer to use a different location, please define the variable: ANDROID_STANDALONE_TOOLCHAIN" ) endif( ANDROID_STANDALONE_TOOLCHAIN ) endif( ANDROID_NDK ) endif( NOT ANDROID_STANDALONE_TOOLCHAIN ) endif( NOT ANDROID_NDK ) # remember found paths if( ANDROID_NDK ) get_filename_component( ANDROID_NDK "${ANDROID_NDK}" ABSOLUTE ) set( ANDROID_NDK "${ANDROID_NDK}" CACHE INTERNAL "Path of the Android NDK" FORCE ) set( BUILD_WITH_ANDROID_NDK True ) if( EXISTS "${ANDROID_NDK}/RELEASE.TXT" ) file( STRINGS "${ANDROID_NDK}/RELEASE.TXT" ANDROID_NDK_RELEASE_FULL LIMIT_COUNT 1 REGEX r[0-9]+[a-z]? ) string( REGEX MATCH r[0-9]+[a-z]? ANDROID_NDK_RELEASE "${ANDROID_NDK_RELEASE_FULL}" ) else() set( ANDROID_NDK_RELEASE "r1x" ) set( ANDROID_NDK_RELEASE_FULL "unreleased" ) endif() elseif( ANDROID_STANDALONE_TOOLCHAIN ) get_filename_component( ANDROID_STANDALONE_TOOLCHAIN "${ANDROID_STANDALONE_TOOLCHAIN}" ABSOLUTE ) # try to detect change if( CMAKE_AR ) string( LENGTH "${ANDROID_STANDALONE_TOOLCHAIN}" __length ) string( SUBSTRING "${CMAKE_AR}" 0 ${__length} __androidStandaloneToolchainPreviousPath ) if( NOT __androidStandaloneToolchainPreviousPath STREQUAL ANDROID_STANDALONE_TOOLCHAIN ) message( FATAL_ERROR "It is not possible to change path to the Android standalone toolchain on subsequent run." ) endif() unset( __androidStandaloneToolchainPreviousPath ) unset( __length ) endif() set( ANDROID_STANDALONE_TOOLCHAIN "${ANDROID_STANDALONE_TOOLCHAIN}" CACHE INTERNAL "Path of the Android standalone toolchain" FORCE ) set( BUILD_WITH_STANDALONE_TOOLCHAIN True ) else() list(GET ANDROID_NDK_SEARCH_PATHS 0 ANDROID_NDK_SEARCH_PATH) message( FATAL_ERROR "Could not find neither Android NDK nor Android standalone toolchain. You should either set an environment variable: export ANDROID_NDK=~/my-android-ndk or export ANDROID_STANDALONE_TOOLCHAIN=~/my-android-toolchain or put the toolchain or NDK in the default path: sudo ln -s ~/my-android-ndk ${ANDROID_NDK_SEARCH_PATH} sudo ln -s ~/my-android-toolchain ${ANDROID_STANDALONE_TOOLCHAIN_SEARCH_PATH}" ) endif() # android NDK layout if( BUILD_WITH_ANDROID_NDK ) if( NOT DEFINED ANDROID_NDK_LAYOUT ) # try to automatically detect the layout if( EXISTS "${ANDROID_NDK}/RELEASE.TXT") set( ANDROID_NDK_LAYOUT "RELEASE" ) elseif( EXISTS "${ANDROID_NDK}/../../linux-x86/toolchain/" ) set( ANDROID_NDK_LAYOUT "LINARO" ) elseif( EXISTS "${ANDROID_NDK}/../../gcc/" ) set( ANDROID_NDK_LAYOUT "ANDROID" ) endif() endif() set( ANDROID_NDK_LAYOUT "${ANDROID_NDK_LAYOUT}" CACHE STRING "The inner layout of NDK" ) mark_as_advanced( ANDROID_NDK_LAYOUT ) if( ANDROID_NDK_LAYOUT STREQUAL "LINARO" ) set( ANDROID_NDK_HOST_SYSTEM_NAME ${ANDROID_NDK_HOST_SYSTEM_NAME2} ) # only 32-bit at the moment set( ANDROID_NDK_TOOLCHAINS_PATH "${ANDROID_NDK}/../../${ANDROID_NDK_HOST_SYSTEM_NAME}/toolchain" ) set( ANDROID_NDK_TOOLCHAINS_SUBPATH "" ) set( ANDROID_NDK_TOOLCHAINS_SUBPATH2 "" ) elseif( ANDROID_NDK_LAYOUT STREQUAL "ANDROID" ) set( ANDROID_NDK_HOST_SYSTEM_NAME ${ANDROID_NDK_HOST_SYSTEM_NAME2} ) # only 32-bit at the moment set( ANDROID_NDK_TOOLCHAINS_PATH "${ANDROID_NDK}/../../gcc/${ANDROID_NDK_HOST_SYSTEM_NAME}/arm" ) set( ANDROID_NDK_TOOLCHAINS_SUBPATH "" ) set( ANDROID_NDK_TOOLCHAINS_SUBPATH2 "" ) else() # ANDROID_NDK_LAYOUT STREQUAL "RELEASE" set( ANDROID_NDK_TOOLCHAINS_PATH "${ANDROID_NDK}/toolchains" ) set( ANDROID_NDK_TOOLCHAINS_SUBPATH "/prebuilt/${ANDROID_NDK_HOST_SYSTEM_NAME}" ) set( ANDROID_NDK_TOOLCHAINS_SUBPATH2 "/prebuilt/${ANDROID_NDK_HOST_SYSTEM_NAME2}" ) endif() get_filename_component( ANDROID_NDK_TOOLCHAINS_PATH "${ANDROID_NDK_TOOLCHAINS_PATH}" ABSOLUTE ) # try to detect change of NDK if( CMAKE_AR ) string( LENGTH "${ANDROID_NDK_TOOLCHAINS_PATH}" __length ) string( SUBSTRING "${CMAKE_AR}" 0 ${__length} __androidNdkPreviousPath ) if( NOT __androidNdkPreviousPath STREQUAL ANDROID_NDK_TOOLCHAINS_PATH ) message( FATAL_ERROR "It is not possible to change the path to the NDK on subsequent CMake run. You must remove all generated files from your build folder first. " ) endif() unset( __androidNdkPreviousPath ) unset( __length ) endif() endif() # get all the details about standalone toolchain if( BUILD_WITH_STANDALONE_TOOLCHAIN ) __DETECT_NATIVE_API_LEVEL( ANDROID_SUPPORTED_NATIVE_API_LEVELS "${ANDROID_STANDALONE_TOOLCHAIN}/sysroot/usr/include/android/api-level.h" ) set( ANDROID_STANDALONE_TOOLCHAIN_API_LEVEL ${ANDROID_SUPPORTED_NATIVE_API_LEVELS} ) set( __availableToolchains "standalone" ) __DETECT_TOOLCHAIN_MACHINE_NAME( __availableToolchainMachines "${ANDROID_STANDALONE_TOOLCHAIN}" ) if( NOT __availableToolchainMachines ) message( FATAL_ERROR "Could not determine machine name of your toolchain. Probably your Android standalone toolchain is broken." ) endif() if( __availableToolchainMachines MATCHES i686 ) set( __availableToolchainArchs "x86" ) elseif( __availableToolchainMachines MATCHES arm ) set( __availableToolchainArchs "arm" ) elseif( __availableToolchainMachines MATCHES mipsel ) set( __availableToolchainArchs "mipsel" ) endif() execute_process( COMMAND "${ANDROID_STANDALONE_TOOLCHAIN}/bin/${__availableToolchainMachines}-gcc${TOOL_OS_SUFFIX}" -dumpversion OUTPUT_VARIABLE __availableToolchainCompilerVersions OUTPUT_STRIP_TRAILING_WHITESPACE ) string( REGEX MATCH "[0-9]+[.][0-9]+([.][0-9]+)?" __availableToolchainCompilerVersions "${__availableToolchainCompilerVersions}" ) if( EXISTS "${ANDROID_STANDALONE_TOOLCHAIN}/bin/clang${TOOL_OS_SUFFIX}" ) list( APPEND __availableToolchains "standalone-clang" ) list( APPEND __availableToolchainMachines ${__availableToolchainMachines} ) list( APPEND __availableToolchainArchs ${__availableToolchainArchs} ) list( APPEND __availableToolchainCompilerVersions ${__availableToolchainCompilerVersions} ) endif() endif() macro( __GLOB_NDK_TOOLCHAINS __availableToolchainsVar __availableToolchainsLst __toolchain_subpath ) foreach( __toolchain ${${__availableToolchainsLst}} ) if( "${__toolchain}" MATCHES "-clang3[.][0-9]$" AND NOT EXISTS "${ANDROID_NDK_TOOLCHAINS_PATH}/${__toolchain}${__toolchain_subpath}" ) string( REGEX REPLACE "-clang3[.][0-9]$" "-4.6" __gcc_toolchain "${__toolchain}" ) else() set( __gcc_toolchain "${__toolchain}" ) endif() __DETECT_TOOLCHAIN_MACHINE_NAME( __machine "${ANDROID_NDK_TOOLCHAINS_PATH}/${__gcc_toolchain}${__toolchain_subpath}" ) if( __machine ) string( REGEX MATCH "[0-9]+[.][0-9]+([.][0-9x]+)?$" __version "${__gcc_toolchain}" ) if( __machine MATCHES i686 ) set( __arch "x86" ) elseif( __machine MATCHES arm ) set( __arch "arm" ) elseif( __machine MATCHES mipsel ) set( __arch "mipsel" ) endif() list( APPEND __availableToolchainMachines "${__machine}" ) list( APPEND __availableToolchainArchs "${__arch}" ) list( APPEND __availableToolchainCompilerVersions "${__version}" ) list( APPEND ${__availableToolchainsVar} "${__toolchain}" ) endif() unset( __gcc_toolchain ) endforeach() endmacro() # get all the details about NDK if( BUILD_WITH_ANDROID_NDK ) file( GLOB ANDROID_SUPPORTED_NATIVE_API_LEVELS RELATIVE "${ANDROID_NDK}/platforms" "${ANDROID_NDK}/platforms/android-*" ) string( REPLACE "android-" "" ANDROID_SUPPORTED_NATIVE_API_LEVELS "${ANDROID_SUPPORTED_NATIVE_API_LEVELS}" ) set( __availableToolchains "" ) set( __availableToolchainMachines "" ) set( __availableToolchainArchs "" ) set( __availableToolchainCompilerVersions "" ) if( ANDROID_TOOLCHAIN_NAME AND EXISTS "${ANDROID_NDK_TOOLCHAINS_PATH}/${ANDROID_TOOLCHAIN_NAME}/" ) # do not go through all toolchains if we know the name set( __availableToolchainsLst "${ANDROID_TOOLCHAIN_NAME}" ) __GLOB_NDK_TOOLCHAINS( __availableToolchains __availableToolchainsLst "${ANDROID_NDK_TOOLCHAINS_SUBPATH}" ) if( NOT __availableToolchains AND NOT ANDROID_NDK_TOOLCHAINS_SUBPATH STREQUAL ANDROID_NDK_TOOLCHAINS_SUBPATH2 ) __GLOB_NDK_TOOLCHAINS( __availableToolchains __availableToolchainsLst "${ANDROID_NDK_TOOLCHAINS_SUBPATH2}" ) if( __availableToolchains ) set( ANDROID_NDK_TOOLCHAINS_SUBPATH ${ANDROID_NDK_TOOLCHAINS_SUBPATH2} ) endif() endif() endif() if( NOT __availableToolchains ) file( GLOB __availableToolchainsLst RELATIVE "${ANDROID_NDK_TOOLCHAINS_PATH}" "${ANDROID_NDK_TOOLCHAINS_PATH}/*" ) if( __availableToolchains ) list(SORT __availableToolchainsLst) # we need clang to go after gcc endif() __LIST_FILTER( __availableToolchainsLst "^[.]" ) __LIST_FILTER( __availableToolchainsLst "llvm" ) __LIST_FILTER( __availableToolchainsLst "renderscript" ) __GLOB_NDK_TOOLCHAINS( __availableToolchains __availableToolchainsLst "${ANDROID_NDK_TOOLCHAINS_SUBPATH}" ) if( NOT __availableToolchains AND NOT ANDROID_NDK_TOOLCHAINS_SUBPATH STREQUAL ANDROID_NDK_TOOLCHAINS_SUBPATH2 ) __GLOB_NDK_TOOLCHAINS( __availableToolchains __availableToolchainsLst "${ANDROID_NDK_TOOLCHAINS_SUBPATH2}" ) if( __availableToolchains ) set( ANDROID_NDK_TOOLCHAINS_SUBPATH ${ANDROID_NDK_TOOLCHAINS_SUBPATH2} ) endif() endif() endif() if( NOT __availableToolchains ) message( FATAL_ERROR "Could not find any working toolchain in the NDK. Probably your Android NDK is broken." ) endif() endif() # build list of available ABIs set( ANDROID_SUPPORTED_ABIS "" ) set( __uniqToolchainArchNames ${__availableToolchainArchs} ) list( REMOVE_DUPLICATES __uniqToolchainArchNames ) list( SORT __uniqToolchainArchNames ) foreach( __arch ${__uniqToolchainArchNames} ) list( APPEND ANDROID_SUPPORTED_ABIS ${ANDROID_SUPPORTED_ABIS_${__arch}} ) endforeach() unset( __uniqToolchainArchNames ) if( NOT ANDROID_SUPPORTED_ABIS ) message( FATAL_ERROR "No one of known Android ABIs is supported by this cmake toolchain." ) endif() # choose target ABI __INIT_VARIABLE( ANDROID_ABI OBSOLETE_ARM_TARGET OBSOLETE_ARM_TARGETS VALUES ${ANDROID_SUPPORTED_ABIS} ) # verify that target ABI is supported list( FIND ANDROID_SUPPORTED_ABIS "${ANDROID_ABI}" __androidAbiIdx ) if( __androidAbiIdx EQUAL -1 ) string( REPLACE ";" "\", \"" PRINTABLE_ANDROID_SUPPORTED_ABIS "${ANDROID_SUPPORTED_ABIS}" ) message( FATAL_ERROR "Specified ANDROID_ABI = \"${ANDROID_ABI}\" is not supported by this cmake toolchain or your NDK/toolchain. Supported values are: \"${PRINTABLE_ANDROID_SUPPORTED_ABIS}\" " ) endif() unset( __androidAbiIdx ) # set target ABI options if( ANDROID_ABI STREQUAL "x86" ) set( X86 true ) set( ANDROID_NDK_ABI_NAME "x86" ) set( ANDROID_ARCH_NAME "x86" ) set( ANDROID_ARCH_FULLNAME "x86" ) set( ANDROID_LLVM_TRIPLE "i686-none-linux-android" ) set( CMAKE_SYSTEM_PROCESSOR "i686" ) elseif( ANDROID_ABI STREQUAL "mips" ) set( MIPS true ) set( ANDROID_NDK_ABI_NAME "mips" ) set( ANDROID_ARCH_NAME "mips" ) set( ANDROID_ARCH_FULLNAME "mipsel" ) set( ANDROID_LLVM_TRIPLE "mipsel-none-linux-android" ) set( CMAKE_SYSTEM_PROCESSOR "mips" ) elseif( ANDROID_ABI STREQUAL "armeabi" ) set( ARMEABI true ) set( ANDROID_NDK_ABI_NAME "armeabi" ) set( ANDROID_ARCH_NAME "arm" ) set( ANDROID_ARCH_FULLNAME "arm" ) set( ANDROID_LLVM_TRIPLE "armv5te-none-linux-androideabi" ) set( CMAKE_SYSTEM_PROCESSOR "armv5te" ) elseif( ANDROID_ABI STREQUAL "armeabi-v6 with VFP" ) set( ARMEABI_V6 true ) set( ANDROID_NDK_ABI_NAME "armeabi" ) set( ANDROID_ARCH_NAME "arm" ) set( ANDROID_ARCH_FULLNAME "arm" ) set( ANDROID_LLVM_TRIPLE "armv5te-none-linux-androideabi" ) set( CMAKE_SYSTEM_PROCESSOR "armv6" ) # need always fallback to older platform set( ARMEABI true ) elseif( ANDROID_ABI STREQUAL "armeabi-v7a") set( ARMEABI_V7A true ) set( ANDROID_NDK_ABI_NAME "armeabi-v7a" ) set( ANDROID_ARCH_NAME "arm" ) set( ANDROID_ARCH_FULLNAME "arm" ) set( ANDROID_LLVM_TRIPLE "armv7-none-linux-androideabi" ) set( CMAKE_SYSTEM_PROCESSOR "armv7-a" ) elseif( ANDROID_ABI STREQUAL "armeabi-v7a with VFPV3" ) set( ARMEABI_V7A true ) set( ANDROID_NDK_ABI_NAME "armeabi-v7a" ) set( ANDROID_ARCH_NAME "arm" ) set( ANDROID_ARCH_FULLNAME "arm" ) set( ANDROID_LLVM_TRIPLE "armv7-none-linux-androideabi" ) set( CMAKE_SYSTEM_PROCESSOR "armv7-a" ) set( VFPV3 true ) elseif( ANDROID_ABI STREQUAL "armeabi-v7a with NEON" ) set( ARMEABI_V7A true ) set( ANDROID_NDK_ABI_NAME "armeabi-v7a" ) set( ANDROID_ARCH_NAME "arm" ) set( ANDROID_ARCH_FULLNAME "arm" ) set( ANDROID_LLVM_TRIPLE "armv7-none-linux-androideabi" ) set( CMAKE_SYSTEM_PROCESSOR "armv7-a" ) set( VFPV3 true ) set( NEON true ) else() message( SEND_ERROR "Unknown ANDROID_ABI=\"${ANDROID_ABI}\" is specified." ) endif() if( CMAKE_BINARY_DIR AND EXISTS "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeSystem.cmake" ) # really dirty hack # it is not possible to change CMAKE_SYSTEM_PROCESSOR after the first run... file( APPEND "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeSystem.cmake" "SET(CMAKE_SYSTEM_PROCESSOR \"${CMAKE_SYSTEM_PROCESSOR}\")\n" ) endif() if( ANDROID_ARCH_NAME STREQUAL "arm" AND NOT ARMEABI_V6 ) __INIT_VARIABLE( ANDROID_FORCE_ARM_BUILD OBSOLETE_FORCE_ARM VALUES OFF ) set( ANDROID_FORCE_ARM_BUILD ${ANDROID_FORCE_ARM_BUILD} CACHE BOOL "Use 32-bit ARM instructions instead of Thumb-1" FORCE ) mark_as_advanced( ANDROID_FORCE_ARM_BUILD ) else() unset( ANDROID_FORCE_ARM_BUILD CACHE ) endif() # choose toolchain if( ANDROID_TOOLCHAIN_NAME ) list( FIND __availableToolchains "${ANDROID_TOOLCHAIN_NAME}" __toolchainIdx ) if( __toolchainIdx EQUAL -1 ) list( SORT __availableToolchains ) string( REPLACE ";" "\n * " toolchains_list "${__availableToolchains}" ) set( toolchains_list " * ${toolchains_list}") message( FATAL_ERROR "Specified toolchain \"${ANDROID_TOOLCHAIN_NAME}\" is missing in your NDK or broken. Please verify that your NDK is working or select another compiler toolchain. To configure the toolchain set CMake variable ANDROID_TOOLCHAIN_NAME to one of the following values:\n${toolchains_list}\n" ) endif() list( GET __availableToolchainArchs ${__toolchainIdx} __toolchainArch ) if( NOT __toolchainArch STREQUAL ANDROID_ARCH_FULLNAME ) message( SEND_ERROR "Selected toolchain \"${ANDROID_TOOLCHAIN_NAME}\" is not able to compile binaries for the \"${ANDROID_ARCH_NAME}\" platform." ) endif() else() set( __toolchainIdx -1 ) set( __applicableToolchains "" ) set( __toolchainMaxVersion "0.0.0" ) list( LENGTH __availableToolchains __availableToolchainsCount ) math( EXPR __availableToolchainsCount "${__availableToolchainsCount}-1" ) foreach( __idx RANGE ${__availableToolchainsCount} ) list( GET __availableToolchainArchs ${__idx} __toolchainArch ) if( __toolchainArch STREQUAL ANDROID_ARCH_FULLNAME ) list( GET __availableToolchainCompilerVersions ${__idx} __toolchainVersion ) string( REPLACE "x" "99" __toolchainVersion "${__toolchainVersion}") if( __toolchainVersion VERSION_GREATER __toolchainMaxVersion ) set( __toolchainMaxVersion "${__toolchainVersion}" ) set( __toolchainIdx ${__idx} ) endif() endif() endforeach() unset( __availableToolchainsCount ) unset( __toolchainMaxVersion ) unset( __toolchainVersion ) endif() unset( __toolchainArch ) if( __toolchainIdx EQUAL -1 ) message( FATAL_ERROR "No one of available compiler toolchains is able to compile for ${ANDROID_ARCH_NAME} platform." ) endif() list( GET __availableToolchains ${__toolchainIdx} ANDROID_TOOLCHAIN_NAME ) list( GET __availableToolchainMachines ${__toolchainIdx} ANDROID_TOOLCHAIN_MACHINE_NAME ) list( GET __availableToolchainCompilerVersions ${__toolchainIdx} ANDROID_COMPILER_VERSION ) unset( __toolchainIdx ) unset( __availableToolchains ) unset( __availableToolchainMachines ) unset( __availableToolchainArchs ) unset( __availableToolchainCompilerVersions ) # choose native API level __INIT_VARIABLE( ANDROID_NATIVE_API_LEVEL ENV_ANDROID_NATIVE_API_LEVEL ANDROID_API_LEVEL ENV_ANDROID_API_LEVEL ANDROID_STANDALONE_TOOLCHAIN_API_LEVEL ANDROID_DEFAULT_NDK_API_LEVEL_${ANDROID_ARCH_NAME} ANDROID_DEFAULT_NDK_API_LEVEL ) string( REGEX MATCH "[0-9]+" ANDROID_NATIVE_API_LEVEL "${ANDROID_NATIVE_API_LEVEL}" ) # adjust API level set( __real_api_level ${ANDROID_DEFAULT_NDK_API_LEVEL_${ANDROID_ARCH_NAME}} ) foreach( __level ${ANDROID_SUPPORTED_NATIVE_API_LEVELS} ) if( NOT __level GREATER ANDROID_NATIVE_API_LEVEL AND NOT __level LESS __real_api_level ) set( __real_api_level ${__level} ) endif() endforeach() if( __real_api_level AND NOT ANDROID_NATIVE_API_LEVEL EQUAL __real_api_level ) message( STATUS "Adjusting Android API level 'android-${ANDROID_NATIVE_API_LEVEL}' to 'android-${__real_api_level}'") set( ANDROID_NATIVE_API_LEVEL ${__real_api_level} ) endif() unset(__real_api_level) # validate list( FIND ANDROID_SUPPORTED_NATIVE_API_LEVELS "${ANDROID_NATIVE_API_LEVEL}" __levelIdx ) if( __levelIdx EQUAL -1 ) message( SEND_ERROR "Specified Android native API level 'android-${ANDROID_NATIVE_API_LEVEL}' is not supported by your NDK/toolchain." ) else() if( BUILD_WITH_ANDROID_NDK ) __DETECT_NATIVE_API_LEVEL( __realApiLevel "${ANDROID_NDK}/platforms/android-${ANDROID_NATIVE_API_LEVEL}/arch-${ANDROID_ARCH_NAME}/usr/include/android/api-level.h" ) if( NOT __realApiLevel EQUAL ANDROID_NATIVE_API_LEVEL ) message( SEND_ERROR "Specified Android API level (${ANDROID_NATIVE_API_LEVEL}) does not match to the level found (${__realApiLevel}). Probably your copy of NDK is broken." ) endif() unset( __realApiLevel ) endif() set( ANDROID_NATIVE_API_LEVEL "${ANDROID_NATIVE_API_LEVEL}" CACHE STRING "Android API level for native code" FORCE ) if( CMAKE_VERSION VERSION_GREATER "2.8" ) list( SORT ANDROID_SUPPORTED_NATIVE_API_LEVELS ) set_property( CACHE ANDROID_NATIVE_API_LEVEL PROPERTY STRINGS ${ANDROID_SUPPORTED_NATIVE_API_LEVELS} ) endif() endif() unset( __levelIdx ) # remember target ABI set( ANDROID_ABI "${ANDROID_ABI}" CACHE STRING "The target ABI for Android. If arm, then armeabi-v7a is recommended for hardware floating point." FORCE ) if( CMAKE_VERSION VERSION_GREATER "2.8" ) list( SORT ANDROID_SUPPORTED_ABIS_${ANDROID_ARCH_FULLNAME} ) set_property( CACHE ANDROID_ABI PROPERTY STRINGS ${ANDROID_SUPPORTED_ABIS_${ANDROID_ARCH_FULLNAME}} ) endif() # runtime choice (STL, rtti, exceptions) if( NOT ANDROID_STL ) # honor legacy ANDROID_USE_STLPORT if( DEFINED ANDROID_USE_STLPORT ) if( ANDROID_USE_STLPORT ) set( ANDROID_STL stlport_static ) endif() message( WARNING "You are using an obsolete variable ANDROID_USE_STLPORT to select the STL variant. Use -DANDROID_STL=stlport_static instead." ) endif() if( NOT ANDROID_STL ) set( ANDROID_STL gnustl_static ) endif() endif() set( ANDROID_STL "${ANDROID_STL}" CACHE STRING "C++ runtime" ) set( ANDROID_STL_FORCE_FEATURES ON CACHE BOOL "automatically configure rtti and exceptions support based on C++ runtime" ) mark_as_advanced( ANDROID_STL ANDROID_STL_FORCE_FEATURES ) if( BUILD_WITH_ANDROID_NDK ) if( NOT "${ANDROID_STL}" MATCHES "^(none|system|system_re|gabi\\+\\+_static|gabi\\+\\+_shared|stlport_static|stlport_shared|gnustl_static|gnustl_shared)$") message( FATAL_ERROR "ANDROID_STL is set to invalid value \"${ANDROID_STL}\". The possible values are: none -> Do not configure the runtime. system -> Use the default minimal system C++ runtime library. system_re -> Same as system but with rtti and exceptions. gabi++_static -> Use the GAbi++ runtime as a static library. gabi++_shared -> Use the GAbi++ runtime as a shared library. stlport_static -> Use the STLport runtime as a static library. stlport_shared -> Use the STLport runtime as a shared library. gnustl_static -> (default) Use the GNU STL as a static library. gnustl_shared -> Use the GNU STL as a shared library. " ) endif() elseif( BUILD_WITH_STANDALONE_TOOLCHAIN ) if( NOT "${ANDROID_STL}" MATCHES "^(none|gnustl_static|gnustl_shared)$") message( FATAL_ERROR "ANDROID_STL is set to invalid value \"${ANDROID_STL}\". The possible values are: none -> Do not configure the runtime. gnustl_static -> (default) Use the GNU STL as a static library. gnustl_shared -> Use the GNU STL as a shared library. " ) endif() endif() unset( ANDROID_RTTI ) unset( ANDROID_EXCEPTIONS ) unset( ANDROID_STL_INCLUDE_DIRS ) unset( __libstl ) unset( __libsupcxx ) if( NOT _CMAKE_IN_TRY_COMPILE AND ANDROID_NDK_RELEASE STREQUAL "r7b" AND ARMEABI_V7A AND NOT VFPV3 AND ANDROID_STL MATCHES "gnustl" ) message( WARNING "The GNU STL armeabi-v7a binaries from NDK r7b can crash non-NEON devices. The files provided with NDK r7b were not configured properly, resulting in crashes on Tegra2-based devices and others when trying to use certain floating-point functions (e.g., cosf, sinf, expf). You are strongly recommended to switch to another NDK release. " ) endif() if( NOT _CMAKE_IN_TRY_COMPILE AND X86 AND ANDROID_STL MATCHES "gnustl" AND ANDROID_NDK_RELEASE STREQUAL "r6" ) message( WARNING "The x86 system header file from NDK r6 has incorrect definition for ptrdiff_t. You are recommended to upgrade to a newer NDK release or manually patch the header: See https://android.googlesource.com/platform/development.git f907f4f9d4e56ccc8093df6fee54454b8bcab6c2 diff --git a/ndk/platforms/android-9/arch-x86/include/machine/_types.h b/ndk/platforms/android-9/arch-x86/include/machine/_types.h index 5e28c64..65892a1 100644 --- a/ndk/platforms/android-9/arch-x86/include/machine/_types.h +++ b/ndk/platforms/android-9/arch-x86/include/machine/_types.h @@ -51,7 +51,11 @@ typedef long int ssize_t; #endif #ifndef _PTRDIFF_T #define _PTRDIFF_T -typedef long ptrdiff_t; +# ifdef __ANDROID__ + typedef int ptrdiff_t; +# else + typedef long ptrdiff_t; +# endif #endif " ) endif() # setup paths and STL for standalone toolchain if( BUILD_WITH_STANDALONE_TOOLCHAIN ) set( ANDROID_TOOLCHAIN_ROOT "${ANDROID_STANDALONE_TOOLCHAIN}" ) set( ANDROID_CLANG_TOOLCHAIN_ROOT "${ANDROID_STANDALONE_TOOLCHAIN}" ) set( ANDROID_SYSROOT "${ANDROID_STANDALONE_TOOLCHAIN}/sysroot" ) if( NOT ANDROID_STL STREQUAL "none" ) set( ANDROID_STL_INCLUDE_DIRS "${ANDROID_STANDALONE_TOOLCHAIN}/include/c++/${ANDROID_COMPILER_VERSION}" ) if( NOT EXISTS "${ANDROID_STL_INCLUDE_DIRS}" ) # old location ( pre r8c ) set( ANDROID_STL_INCLUDE_DIRS "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/include/c++/${ANDROID_COMPILER_VERSION}" ) endif() if( ARMEABI_V7A AND EXISTS "${ANDROID_STL_INCLUDE_DIRS}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/${CMAKE_SYSTEM_PROCESSOR}/bits" ) list( APPEND ANDROID_STL_INCLUDE_DIRS "${ANDROID_STL_INCLUDE_DIRS}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/${CMAKE_SYSTEM_PROCESSOR}" ) elseif( ARMEABI AND NOT ANDROID_FORCE_ARM_BUILD AND EXISTS "${ANDROID_STL_INCLUDE_DIRS}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/thumb/bits" ) list( APPEND ANDROID_STL_INCLUDE_DIRS "${ANDROID_STL_INCLUDE_DIRS}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/thumb" ) else() list( APPEND ANDROID_STL_INCLUDE_DIRS "${ANDROID_STL_INCLUDE_DIRS}/${ANDROID_TOOLCHAIN_MACHINE_NAME}" ) endif() # always search static GNU STL to get the location of libsupc++.a if( ARMEABI_V7A AND NOT ANDROID_FORCE_ARM_BUILD AND EXISTS "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/${CMAKE_SYSTEM_PROCESSOR}/thumb/libstdc++.a" ) set( __libstl "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/${CMAKE_SYSTEM_PROCESSOR}/thumb" ) elseif( ARMEABI_V7A AND EXISTS "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/${CMAKE_SYSTEM_PROCESSOR}/libstdc++.a" ) set( __libstl "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/${CMAKE_SYSTEM_PROCESSOR}" ) elseif( ARMEABI AND NOT ANDROID_FORCE_ARM_BUILD AND EXISTS "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/thumb/libstdc++.a" ) set( __libstl "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/thumb" ) elseif( EXISTS "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/libstdc++.a" ) set( __libstl "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib" ) endif() if( __libstl ) set( __libsupcxx "${__libstl}/libsupc++.a" ) set( __libstl "${__libstl}/libstdc++.a" ) endif() if( NOT EXISTS "${__libsupcxx}" ) message( FATAL_ERROR "The required libstdsupc++.a is missing in your standalone toolchain. Usually it happens because of bug in make-standalone-toolchain.sh script from NDK r7, r7b and r7c. You need to either upgrade to newer NDK or manually copy $ANDROID_NDK/sources/cxx-stl/gnu-libstdc++/libs/${ANDROID_NDK_ABI_NAME}/libsupc++.a to ${__libsupcxx} " ) endif() if( ANDROID_STL STREQUAL "gnustl_shared" ) if( ARMEABI_V7A AND EXISTS "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/${CMAKE_SYSTEM_PROCESSOR}/libgnustl_shared.so" ) set( __libstl "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/${CMAKE_SYSTEM_PROCESSOR}/libgnustl_shared.so" ) elseif( ARMEABI AND NOT ANDROID_FORCE_ARM_BUILD AND EXISTS "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/thumb/libgnustl_shared.so" ) set( __libstl "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/thumb/libgnustl_shared.so" ) elseif( EXISTS "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/libgnustl_shared.so" ) set( __libstl "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/libgnustl_shared.so" ) endif() endif() endif() endif() # clang if( "${ANDROID_TOOLCHAIN_NAME}" STREQUAL "standalone-clang" ) set( ANDROID_COMPILER_IS_CLANG 1 ) execute_process( COMMAND "${ANDROID_CLANG_TOOLCHAIN_ROOT}/bin/clang${TOOL_OS_SUFFIX}" --version OUTPUT_VARIABLE ANDROID_CLANG_VERSION OUTPUT_STRIP_TRAILING_WHITESPACE ) string( REGEX MATCH "[0-9]+[.][0-9]+" ANDROID_CLANG_VERSION "${ANDROID_CLANG_VERSION}") elseif( "${ANDROID_TOOLCHAIN_NAME}" MATCHES "-clang3[.][0-9]?$" ) string( REGEX MATCH "3[.][0-9]$" ANDROID_CLANG_VERSION "${ANDROID_TOOLCHAIN_NAME}") string( REGEX REPLACE "-clang${ANDROID_CLANG_VERSION}$" "-4.6" ANDROID_GCC_TOOLCHAIN_NAME "${ANDROID_TOOLCHAIN_NAME}" ) if( NOT EXISTS "${ANDROID_NDK_TOOLCHAINS_PATH}/llvm-${ANDROID_CLANG_VERSION}${ANDROID_NDK_TOOLCHAINS_SUBPATH}/bin/clang${TOOL_OS_SUFFIX}" ) message( FATAL_ERROR "Could not find the Clang compiler driver" ) endif() set( ANDROID_COMPILER_IS_CLANG 1 ) set( ANDROID_CLANG_TOOLCHAIN_ROOT "${ANDROID_NDK_TOOLCHAINS_PATH}/llvm-${ANDROID_CLANG_VERSION}${ANDROID_NDK_TOOLCHAINS_SUBPATH}" ) else() set( ANDROID_GCC_TOOLCHAIN_NAME "${ANDROID_TOOLCHAIN_NAME}" ) unset( ANDROID_COMPILER_IS_CLANG CACHE ) endif() string( REPLACE "." "" _clang_name "clang${ANDROID_CLANG_VERSION}" ) if( NOT EXISTS "${ANDROID_CLANG_TOOLCHAIN_ROOT}/bin/${_clang_name}${TOOL_OS_SUFFIX}" ) set( _clang_name "clang" ) endif() # setup paths and STL for NDK if( BUILD_WITH_ANDROID_NDK ) set( ANDROID_TOOLCHAIN_ROOT "${ANDROID_NDK_TOOLCHAINS_PATH}/${ANDROID_GCC_TOOLCHAIN_NAME}${ANDROID_NDK_TOOLCHAINS_SUBPATH}" ) set( ANDROID_SYSROOT "${ANDROID_NDK}/platforms/android-${ANDROID_NATIVE_API_LEVEL}/arch-${ANDROID_ARCH_NAME}" ) if( ANDROID_STL STREQUAL "none" ) # do nothing elseif( ANDROID_STL STREQUAL "system" ) set( ANDROID_RTTI OFF ) set( ANDROID_EXCEPTIONS OFF ) set( ANDROID_STL_INCLUDE_DIRS "${ANDROID_NDK}/sources/cxx-stl/system/include" ) elseif( ANDROID_STL STREQUAL "system_re" ) set( ANDROID_RTTI ON ) set( ANDROID_EXCEPTIONS ON ) set( ANDROID_STL_INCLUDE_DIRS "${ANDROID_NDK}/sources/cxx-stl/system/include" ) elseif( ANDROID_STL MATCHES "gabi" ) if( ANDROID_NDK_RELEASE STRLESS "r7" ) message( FATAL_ERROR "gabi++ is not awailable in your NDK. You have to upgrade to NDK r7 or newer to use gabi++.") endif() set( ANDROID_RTTI ON ) set( ANDROID_EXCEPTIONS OFF ) set( ANDROID_STL_INCLUDE_DIRS "${ANDROID_NDK}/sources/cxx-stl/gabi++/include" ) set( __libstl "${ANDROID_NDK}/sources/cxx-stl/gabi++/libs/${ANDROID_NDK_ABI_NAME}/libgabi++_static.a" ) elseif( ANDROID_STL MATCHES "stlport" ) if( NOT ANDROID_NDK_RELEASE STRLESS "r8d" ) set( ANDROID_EXCEPTIONS ON ) else() set( ANDROID_EXCEPTIONS OFF ) endif() if( ANDROID_NDK_RELEASE STRLESS "r7" ) set( ANDROID_RTTI OFF ) else() set( ANDROID_RTTI ON ) endif() set( ANDROID_STL_INCLUDE_DIRS "${ANDROID_NDK}/sources/cxx-stl/stlport/stlport" ) set( __libstl "${ANDROID_NDK}/sources/cxx-stl/stlport/libs/${ANDROID_NDK_ABI_NAME}/libstlport_static.a" ) elseif( ANDROID_STL MATCHES "gnustl" ) set( ANDROID_EXCEPTIONS ON ) set( ANDROID_RTTI ON ) if( EXISTS "${ANDROID_NDK}/sources/cxx-stl/gnu-libstdc++/${ANDROID_COMPILER_VERSION}" ) if( ARMEABI_V7A AND ANDROID_COMPILER_VERSION VERSION_EQUAL "4.7" AND ANDROID_NDK_RELEASE STREQUAL "r8d" ) # gnustl binary for 4.7 compiler is buggy :( # TODO: look for right fix set( __libstl "${ANDROID_NDK}/sources/cxx-stl/gnu-libstdc++/4.6" ) else() set( __libstl "${ANDROID_NDK}/sources/cxx-stl/gnu-libstdc++/${ANDROID_COMPILER_VERSION}" ) endif() else() set( __libstl "${ANDROID_NDK}/sources/cxx-stl/gnu-libstdc++" ) endif() set( ANDROID_STL_INCLUDE_DIRS "${__libstl}/include" "${__libstl}/libs/${ANDROID_NDK_ABI_NAME}/include" ) if( EXISTS "${__libstl}/libs/${ANDROID_NDK_ABI_NAME}/libgnustl_static.a" ) set( __libstl "${__libstl}/libs/${ANDROID_NDK_ABI_NAME}/libgnustl_static.a" ) else() set( __libstl "${__libstl}/libs/${ANDROID_NDK_ABI_NAME}/libstdc++.a" ) endif() else() message( FATAL_ERROR "Unknown runtime: ${ANDROID_STL}" ) endif() # find libsupc++.a - rtti & exceptions if( ANDROID_STL STREQUAL "system_re" OR ANDROID_STL MATCHES "gnustl" ) set( __libsupcxx "${ANDROID_NDK}/sources/cxx-stl/gnu-libstdc++/${ANDROID_COMPILER_VERSION}/libs/${ANDROID_NDK_ABI_NAME}/libsupc++.a" ) # r8b or newer if( NOT EXISTS "${__libsupcxx}" ) set( __libsupcxx "${ANDROID_NDK}/sources/cxx-stl/gnu-libstdc++/libs/${ANDROID_NDK_ABI_NAME}/libsupc++.a" ) # r7-r8 endif() if( NOT EXISTS "${__libsupcxx}" ) # before r7 if( ARMEABI_V7A ) if( ANDROID_FORCE_ARM_BUILD ) set( __libsupcxx "${ANDROID_TOOLCHAIN_ROOT}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/${CMAKE_SYSTEM_PROCESSOR}/libsupc++.a" ) else() set( __libsupcxx "${ANDROID_TOOLCHAIN_ROOT}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/${CMAKE_SYSTEM_PROCESSOR}/thumb/libsupc++.a" ) endif() elseif( ARMEABI AND NOT ANDROID_FORCE_ARM_BUILD ) set( __libsupcxx "${ANDROID_TOOLCHAIN_ROOT}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/thumb/libsupc++.a" ) else() set( __libsupcxx "${ANDROID_TOOLCHAIN_ROOT}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/libsupc++.a" ) endif() endif() if( NOT EXISTS "${__libsupcxx}") message( ERROR "Could not find libsupc++.a for a chosen platform. Either your NDK is not supported or is broken.") endif() endif() endif() # case of shared STL linkage if( ANDROID_STL MATCHES "shared" AND DEFINED __libstl ) string( REPLACE "_static.a" "_shared.so" __libstl "${__libstl}" ) # TODO: check if .so file exists before the renaming endif() # ccache support __INIT_VARIABLE( _ndk_ccache NDK_CCACHE ENV_NDK_CCACHE ) if( _ndk_ccache ) if( DEFINED NDK_CCACHE AND NOT EXISTS NDK_CCACHE ) unset( NDK_CCACHE CACHE ) endif() find_program( NDK_CCACHE "${_ndk_ccache}" DOC "The path to ccache binary") else() unset( NDK_CCACHE CACHE ) endif() unset( _ndk_ccache ) # setup the cross-compiler if( NOT CMAKE_C_COMPILER ) if( NDK_CCACHE AND NOT ANDROID_SYSROOT MATCHES "[ ;\"]" ) set( CMAKE_C_COMPILER "${NDK_CCACHE}" CACHE PATH "ccache as C compiler" ) set( CMAKE_CXX_COMPILER "${NDK_CCACHE}" CACHE PATH "ccache as C++ compiler" ) if( ANDROID_COMPILER_IS_CLANG ) set( CMAKE_C_COMPILER_ARG1 "${ANDROID_CLANG_TOOLCHAIN_ROOT}/bin/${_clang_name}${TOOL_OS_SUFFIX}" CACHE PATH "C compiler") set( CMAKE_CXX_COMPILER_ARG1 "${ANDROID_CLANG_TOOLCHAIN_ROOT}/bin/${_clang_name}++${TOOL_OS_SUFFIX}" CACHE PATH "C++ compiler") else() set( CMAKE_C_COMPILER_ARG1 "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-gcc${TOOL_OS_SUFFIX}" CACHE PATH "C compiler") set( CMAKE_CXX_COMPILER_ARG1 "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-g++${TOOL_OS_SUFFIX}" CACHE PATH "C++ compiler") endif() else() if( ANDROID_COMPILER_IS_CLANG ) set( CMAKE_C_COMPILER "${ANDROID_CLANG_TOOLCHAIN_ROOT}/bin/${_clang_name}${TOOL_OS_SUFFIX}" CACHE PATH "C compiler") set( CMAKE_CXX_COMPILER "${ANDROID_CLANG_TOOLCHAIN_ROOT}/bin/${_clang_name}++${TOOL_OS_SUFFIX}" CACHE PATH "C++ compiler") else() set( CMAKE_C_COMPILER "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-gcc${TOOL_OS_SUFFIX}" CACHE PATH "C compiler" ) set( CMAKE_CXX_COMPILER "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-g++${TOOL_OS_SUFFIX}" CACHE PATH "C++ compiler" ) endif() endif() set( CMAKE_ASM_COMPILER "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-gcc${TOOL_OS_SUFFIX}" CACHE PATH "assembler" ) set( CMAKE_STRIP "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-strip${TOOL_OS_SUFFIX}" CACHE PATH "strip" ) set( CMAKE_AR "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-ar${TOOL_OS_SUFFIX}" CACHE PATH "archive" ) set( CMAKE_LINKER "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-ld${TOOL_OS_SUFFIX}" CACHE PATH "linker" ) set( CMAKE_NM "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-nm${TOOL_OS_SUFFIX}" CACHE PATH "nm" ) set( CMAKE_OBJCOPY "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-objcopy${TOOL_OS_SUFFIX}" CACHE PATH "objcopy" ) set( CMAKE_OBJDUMP "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-objdump${TOOL_OS_SUFFIX}" CACHE PATH "objdump" ) set( CMAKE_RANLIB "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-ranlib${TOOL_OS_SUFFIX}" CACHE PATH "ranlib" ) endif() set( _CMAKE_TOOLCHAIN_PREFIX "${ANDROID_TOOLCHAIN_MACHINE_NAME}-" ) if( CMAKE_VERSION VERSION_LESS 2.8.5 ) set( CMAKE_ASM_COMPILER_ARG1 "-c" ) endif() if( APPLE ) find_program( CMAKE_INSTALL_NAME_TOOL NAMES install_name_tool ) if( NOT CMAKE_INSTALL_NAME_TOOL ) message( FATAL_ERROR "Could not find install_name_tool, please check your installation." ) endif() mark_as_advanced( CMAKE_INSTALL_NAME_TOOL ) endif() # Force set compilers because standard identification works badly for us include( CMakeForceCompiler ) CMAKE_FORCE_C_COMPILER( "${CMAKE_C_COMPILER}" GNU ) if( ANDROID_COMPILER_IS_CLANG ) set( CMAKE_C_COMPILER_ID Clang) endif() set( CMAKE_C_PLATFORM_ID Linux ) set( CMAKE_C_SIZEOF_DATA_PTR 4 ) set( CMAKE_C_HAS_ISYSROOT 1 ) set( CMAKE_C_COMPILER_ABI ELF ) CMAKE_FORCE_CXX_COMPILER( "${CMAKE_CXX_COMPILER}" GNU ) if( ANDROID_COMPILER_IS_CLANG ) set( CMAKE_CXX_COMPILER_ID Clang) endif() set( CMAKE_CXX_PLATFORM_ID Linux ) set( CMAKE_CXX_SIZEOF_DATA_PTR 4 ) set( CMAKE_CXX_HAS_ISYSROOT 1 ) set( CMAKE_CXX_COMPILER_ABI ELF ) set( CMAKE_CXX_SOURCE_FILE_EXTENSIONS cc cp cxx cpp CPP c++ C ) # force ASM compiler (required for CMake < 2.8.5) set( CMAKE_ASM_COMPILER_ID_RUN TRUE ) set( CMAKE_ASM_COMPILER_ID GNU ) set( CMAKE_ASM_COMPILER_WORKS TRUE ) set( CMAKE_ASM_COMPILER_FORCED TRUE ) set( CMAKE_COMPILER_IS_GNUASM 1) set( CMAKE_ASM_SOURCE_FILE_EXTENSIONS s S asm ) # flags and definitions remove_definitions( -DANDROID ) add_definitions( -DANDROID ) if( ANDROID_SYSROOT MATCHES "[ ;\"]" ) if( CMAKE_HOST_WIN32 ) # try to convert path to 8.3 form file( WRITE "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/cvt83.cmd" "@echo %~s1" ) execute_process( COMMAND "$ENV{ComSpec}" /c "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/cvt83.cmd" "${ANDROID_SYSROOT}" OUTPUT_VARIABLE __path OUTPUT_STRIP_TRAILING_WHITESPACE RESULT_VARIABLE __result ERROR_QUIET ) if( __result EQUAL 0 ) file( TO_CMAKE_PATH "${__path}" ANDROID_SYSROOT ) set( ANDROID_CXX_FLAGS "--sysroot=${ANDROID_SYSROOT}" ) else() set( ANDROID_CXX_FLAGS "--sysroot=\"${ANDROID_SYSROOT}\"" ) endif() else() set( ANDROID_CXX_FLAGS "'--sysroot=${ANDROID_SYSROOT}'" ) endif() if( NOT _CMAKE_IN_TRY_COMPILE ) # quotes can break try_compile and compiler identification message(WARNING "Path to your Android NDK (or toolchain) has non-alphanumeric symbols.\nThe build might be broken.\n") endif() else() set( ANDROID_CXX_FLAGS "--sysroot=${ANDROID_SYSROOT}" ) endif() # NDK flags if( ARMEABI OR ARMEABI_V7A ) set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -fpic -funwind-tables" ) if( NOT ANDROID_FORCE_ARM_BUILD AND NOT ARMEABI_V6 ) set( ANDROID_CXX_FLAGS_RELEASE "-mthumb -fomit-frame-pointer -fno-strict-aliasing" ) set( ANDROID_CXX_FLAGS_DEBUG "-marm -fno-omit-frame-pointer -fno-strict-aliasing" ) if( NOT ANDROID_COMPILER_IS_CLANG ) set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -finline-limit=64" ) endif() else() # always compile ARMEABI_V6 in arm mode; otherwise there is no difference from ARMEABI set( ANDROID_CXX_FLAGS_RELEASE "-marm -fomit-frame-pointer -fstrict-aliasing" ) set( ANDROID_CXX_FLAGS_DEBUG "-marm -fno-omit-frame-pointer -fno-strict-aliasing" ) if( NOT ANDROID_COMPILER_IS_CLANG ) set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -funswitch-loops -finline-limit=300" ) endif() endif() elseif( X86 ) set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -funwind-tables" ) if( NOT ANDROID_COMPILER_IS_CLANG ) set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -funswitch-loops -finline-limit=300" ) else() set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -fPIC" ) endif() set( ANDROID_CXX_FLAGS_RELEASE "-fomit-frame-pointer -fstrict-aliasing" ) set( ANDROID_CXX_FLAGS_DEBUG "-fno-omit-frame-pointer -fno-strict-aliasing" ) elseif( MIPS ) set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -fpic -fno-strict-aliasing -finline-functions -ffunction-sections -funwind-tables -fmessage-length=0" ) set( ANDROID_CXX_FLAGS_RELEASE "-fomit-frame-pointer" ) set( ANDROID_CXX_FLAGS_DEBUG "-fno-omit-frame-pointer" ) if( NOT ANDROID_COMPILER_IS_CLANG ) set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -fno-inline-functions-called-once -fgcse-after-reload -frerun-cse-after-loop -frename-registers" ) set( ANDROID_CXX_FLAGS_RELEASE "${ANDROID_CXX_FLAGS_RELEASE} -funswitch-loops -finline-limit=300" ) endif() elseif() set( ANDROID_CXX_FLAGS_RELEASE "" ) set( ANDROID_CXX_FLAGS_DEBUG "" ) endif() set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -fsigned-char" ) # good/necessary when porting desktop libraries if( NOT X86 AND NOT ANDROID_COMPILER_IS_CLANG ) set( ANDROID_CXX_FLAGS "-Wno-psabi ${ANDROID_CXX_FLAGS}" ) endif() if( NOT ANDROID_COMPILER_VERSION VERSION_LESS "4.6" ) set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -no-canonical-prefixes" ) # see https://android-review.googlesource.com/#/c/47564/ endif() # ABI-specific flags if( ARMEABI_V7A ) set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -march=armv7-a -mfloat-abi=softfp" ) if( NEON ) set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -mfpu=neon" ) elseif( VFPV3 ) set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -mfpu=vfpv3" ) else() set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -mfpu=vfpv3-d16" ) endif() elseif( ARMEABI_V6 ) set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -march=armv6 -mfloat-abi=softfp -mfpu=vfp" ) # vfp == vfpv2 elseif( ARMEABI ) set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -march=armv5te -mtune=xscale -msoft-float" ) endif() if( ANDROID_STL MATCHES "gnustl" AND (EXISTS "${__libstl}" OR EXISTS "${__libsupcxx}") ) set( CMAKE_CXX_CREATE_SHARED_LIBRARY "<CMAKE_C_COMPILER> <CMAKE_SHARED_LIBRARY_CXX_FLAGS> <LANGUAGE_COMPILE_FLAGS> <LINK_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS> <CMAKE_SHARED_LIBRARY_SONAME_CXX_FLAG><TARGET_SONAME> -o <TARGET> <OBJECTS> <LINK_LIBRARIES>" ) set( CMAKE_CXX_CREATE_SHARED_MODULE "<CMAKE_C_COMPILER> <CMAKE_SHARED_LIBRARY_CXX_FLAGS> <LANGUAGE_COMPILE_FLAGS> <LINK_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS> <CMAKE_SHARED_LIBRARY_SONAME_CXX_FLAG><TARGET_SONAME> -o <TARGET> <OBJECTS> <LINK_LIBRARIES>" ) set( CMAKE_CXX_LINK_EXECUTABLE "<CMAKE_C_COMPILER> <FLAGS> <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> -o <TARGET> <LINK_LIBRARIES>" ) else() set( CMAKE_CXX_CREATE_SHARED_LIBRARY "<CMAKE_CXX_COMPILER> <CMAKE_SHARED_LIBRARY_CXX_FLAGS> <LANGUAGE_COMPILE_FLAGS> <LINK_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS> <CMAKE_SHARED_LIBRARY_SONAME_CXX_FLAG><TARGET_SONAME> -o <TARGET> <OBJECTS> <LINK_LIBRARIES>" ) set( CMAKE_CXX_CREATE_SHARED_MODULE "<CMAKE_CXX_COMPILER> <CMAKE_SHARED_LIBRARY_CXX_FLAGS> <LANGUAGE_COMPILE_FLAGS> <LINK_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS> <CMAKE_SHARED_LIBRARY_SONAME_CXX_FLAG><TARGET_SONAME> -o <TARGET> <OBJECTS> <LINK_LIBRARIES>" ) set( CMAKE_CXX_LINK_EXECUTABLE "<CMAKE_CXX_COMPILER> <FLAGS> <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> -o <TARGET> <LINK_LIBRARIES>" ) endif() # STL if( EXISTS "${__libstl}" OR EXISTS "${__libsupcxx}" ) if( EXISTS "${__libstl}" ) set( CMAKE_CXX_CREATE_SHARED_LIBRARY "${CMAKE_CXX_CREATE_SHARED_LIBRARY} \"${__libstl}\"" ) set( CMAKE_CXX_CREATE_SHARED_MODULE "${CMAKE_CXX_CREATE_SHARED_MODULE} \"${__libstl}\"" ) set( CMAKE_CXX_LINK_EXECUTABLE "${CMAKE_CXX_LINK_EXECUTABLE} \"${__libstl}\"" ) endif() if( EXISTS "${__libsupcxx}" ) set( CMAKE_CXX_CREATE_SHARED_LIBRARY "${CMAKE_CXX_CREATE_SHARED_LIBRARY} \"${__libsupcxx}\"" ) set( CMAKE_CXX_CREATE_SHARED_MODULE "${CMAKE_CXX_CREATE_SHARED_MODULE} \"${__libsupcxx}\"" ) set( CMAKE_CXX_LINK_EXECUTABLE "${CMAKE_CXX_LINK_EXECUTABLE} \"${__libsupcxx}\"" ) # C objects: set( CMAKE_C_CREATE_SHARED_LIBRARY "<CMAKE_C_COMPILER> <CMAKE_SHARED_LIBRARY_C_FLAGS> <LANGUAGE_COMPILE_FLAGS> <LINK_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS> <CMAKE_SHARED_LIBRARY_SONAME_C_FLAG><TARGET_SONAME> -o <TARGET> <OBJECTS> <LINK_LIBRARIES>" ) set( CMAKE_C_CREATE_SHARED_MODULE "<CMAKE_C_COMPILER> <CMAKE_SHARED_LIBRARY_C_FLAGS> <LANGUAGE_COMPILE_FLAGS> <LINK_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS> <CMAKE_SHARED_LIBRARY_SONAME_C_FLAG><TARGET_SONAME> -o <TARGET> <OBJECTS> <LINK_LIBRARIES>" ) set( CMAKE_C_LINK_EXECUTABLE "<CMAKE_C_COMPILER> <FLAGS> <CMAKE_C_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> -o <TARGET> <LINK_LIBRARIES>" ) set( CMAKE_C_CREATE_SHARED_LIBRARY "${CMAKE_C_CREATE_SHARED_LIBRARY} \"${__libsupcxx}\"" ) set( CMAKE_C_CREATE_SHARED_MODULE "${CMAKE_C_CREATE_SHARED_MODULE} \"${__libsupcxx}\"" ) set( CMAKE_C_LINK_EXECUTABLE "${CMAKE_C_LINK_EXECUTABLE} \"${__libsupcxx}\"" ) endif() if( ANDROID_STL MATCHES "gnustl" ) if( NOT EXISTS "${ANDROID_LIBM_PATH}" ) set( ANDROID_LIBM_PATH -lm ) endif() set( CMAKE_CXX_CREATE_SHARED_LIBRARY "${CMAKE_CXX_CREATE_SHARED_LIBRARY} ${ANDROID_LIBM_PATH}" ) set( CMAKE_CXX_CREATE_SHARED_MODULE "${CMAKE_CXX_CREATE_SHARED_MODULE} ${ANDROID_LIBM_PATH}" ) set( CMAKE_CXX_LINK_EXECUTABLE "${CMAKE_CXX_LINK_EXECUTABLE} ${ANDROID_LIBM_PATH}" ) endif() endif() # variables controlling optional build flags if (ANDROID_NDK_RELEASE STRLESS "r7") # libGLESv2.so in NDK's prior to r7 refers to missing external symbols. # So this flag option is required for all projects using OpenGL from native. __INIT_VARIABLE( ANDROID_SO_UNDEFINED VALUES ON ) else() __INIT_VARIABLE( ANDROID_SO_UNDEFINED VALUES OFF ) endif() __INIT_VARIABLE( ANDROID_NO_UNDEFINED OBSOLETE_NO_UNDEFINED VALUES ON ) __INIT_VARIABLE( ANDROID_FUNCTION_LEVEL_LINKING VALUES ON ) __INIT_VARIABLE( ANDROID_GOLD_LINKER VALUES ON ) __INIT_VARIABLE( ANDROID_NOEXECSTACK VALUES ON ) __INIT_VARIABLE( ANDROID_RELRO VALUES ON ) set( ANDROID_NO_UNDEFINED ${ANDROID_NO_UNDEFINED} CACHE BOOL "Show all undefined symbols as linker errors" ) set( ANDROID_SO_UNDEFINED ${ANDROID_SO_UNDEFINED} CACHE BOOL "Allows or disallows undefined symbols in shared libraries" ) set( ANDROID_FUNCTION_LEVEL_LINKING ${ANDROID_FUNCTION_LEVEL_LINKING} CACHE BOOL "Allows or disallows undefined symbols in shared libraries" ) set( ANDROID_GOLD_LINKER ${ANDROID_GOLD_LINKER} CACHE BOOL "Enables gold linker (only avaialble for NDK r8b for ARM and x86 architectures on linux-86 and darwin-x86 hosts)" ) set( ANDROID_NOEXECSTACK ${ANDROID_NOEXECSTACK} CACHE BOOL "Allows or disallows undefined symbols in shared libraries" ) set( ANDROID_RELRO ${ANDROID_RELRO} CACHE BOOL "Enables RELRO - a memory corruption mitigation technique" ) mark_as_advanced( ANDROID_NO_UNDEFINED ANDROID_SO_UNDEFINED ANDROID_FUNCTION_LEVEL_LINKING ANDROID_GOLD_LINKER ANDROID_NOEXECSTACK ANDROID_RELRO ) # linker flags set( ANDROID_LINKER_FLAGS "" ) if( ARMEABI_V7A ) # this is *required* to use the following linker flags that routes around # a CPU bug in some Cortex-A8 implementations: set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -Wl,--fix-cortex-a8" ) endif() if( ANDROID_NO_UNDEFINED ) if( MIPS ) # there is some sysroot-related problem in mips linker... if( NOT ANDROID_SYSROOT MATCHES "[ ;\"]" ) set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -Wl,--no-undefined -Wl,-rpath-link,${ANDROID_SYSROOT}/usr/lib" ) endif() else() set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -Wl,--no-undefined" ) endif() endif() if( ANDROID_SO_UNDEFINED ) set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -Wl,-allow-shlib-undefined" ) endif() if( ANDROID_FUNCTION_LEVEL_LINKING ) set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -fdata-sections -ffunction-sections" ) set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -Wl,--gc-sections" ) endif() if( ANDROID_COMPILER_VERSION VERSION_EQUAL "4.6" ) if( ANDROID_GOLD_LINKER AND (CMAKE_HOST_UNIX OR ANDROID_NDK_RELEASE STRGREATER "r8b") AND (ARMEABI OR ARMEABI_V7A OR X86) ) set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -fuse-ld=gold" ) elseif( ANDROID_NDK_RELEASE STRGREATER "r8b") set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -fuse-ld=bfd" ) elseif( ANDROID_NDK_RELEASE STREQUAL "r8b" AND ARMEABI AND NOT _CMAKE_IN_TRY_COMPILE ) message( WARNING "The default bfd linker from arm GCC 4.6 toolchain can fail with 'unresolvable R_ARM_THM_CALL relocation' error message. See https://code.google.com/p/android/issues/detail?id=35342 On Linux and OS X host platform you can workaround this problem using gold linker (default). Rerun cmake with -DANDROID_GOLD_LINKER=ON option in case of problems. " ) endif() endif() # version 4.6 if( ANDROID_NOEXECSTACK ) if( ANDROID_COMPILER_IS_CLANG ) set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -Xclang -mnoexecstack" ) else() set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -Wa,--noexecstack" ) endif() set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -Wl,-z,noexecstack" ) endif() if( ANDROID_RELRO ) set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -Wl,-z,relro -Wl,-z,now" ) endif() if( ANDROID_COMPILER_IS_CLANG ) set( ANDROID_CXX_FLAGS "-Qunused-arguments ${ANDROID_CXX_FLAGS}" ) if( ARMEABI_V7A AND NOT ANDROID_FORCE_ARM_BUILD ) set( ANDROID_CXX_FLAGS_RELEASE "-target thumbv7-none-linux-androideabi ${ANDROID_CXX_FLAGS_RELEASE}" ) set( ANDROID_CXX_FLAGS_DEBUG "-target ${ANDROID_LLVM_TRIPLE} ${ANDROID_CXX_FLAGS_DEBUG}" ) else() set( ANDROID_CXX_FLAGS "-target ${ANDROID_LLVM_TRIPLE} ${ANDROID_CXX_FLAGS}" ) endif() if( BUILD_WITH_ANDROID_NDK ) set( ANDROID_CXX_FLAGS "-gcc-toolchain ${ANDROID_TOOLCHAIN_ROOT} ${ANDROID_CXX_FLAGS}" ) endif() endif() # cache flags set( CMAKE_CXX_FLAGS "" CACHE STRING "c++ flags" ) set( CMAKE_C_FLAGS "" CACHE STRING "c flags" ) set( CMAKE_CXX_FLAGS_RELEASE "-O3 -DNDEBUG" CACHE STRING "c++ Release flags" ) set( CMAKE_C_FLAGS_RELEASE "-O3 -DNDEBUG" CACHE STRING "c Release flags" ) set( CMAKE_CXX_FLAGS_DEBUG "-O0 -g -DDEBUG -D_DEBUG" CACHE STRING "c++ Debug flags" ) set( CMAKE_C_FLAGS_DEBUG "-O0 -g -DDEBUG -D_DEBUG" CACHE STRING "c Debug flags" ) set( CMAKE_SHARED_LINKER_FLAGS "" CACHE STRING "shared linker flags" ) set( CMAKE_MODULE_LINKER_FLAGS "" CACHE STRING "module linker flags" ) set( CMAKE_EXE_LINKER_FLAGS "-Wl,-z,nocopyreloc" CACHE STRING "executable linker flags" ) # put flags to cache (for debug purpose only) set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS}" CACHE INTERNAL "Android specific c/c++ flags" ) set( ANDROID_CXX_FLAGS_RELEASE "${ANDROID_CXX_FLAGS_RELEASE}" CACHE INTERNAL "Android specific c/c++ Release flags" ) set( ANDROID_CXX_FLAGS_DEBUG "${ANDROID_CXX_FLAGS_DEBUG}" CACHE INTERNAL "Android specific c/c++ Debug flags" ) set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS}" CACHE INTERNAL "Android specific c/c++ linker flags" ) # finish flags set( CMAKE_CXX_FLAGS "${ANDROID_CXX_FLAGS} ${CMAKE_CXX_FLAGS}" ) set( CMAKE_C_FLAGS "${ANDROID_CXX_FLAGS} ${CMAKE_C_FLAGS}" ) set( CMAKE_CXX_FLAGS_RELEASE "${ANDROID_CXX_FLAGS_RELEASE} ${CMAKE_CXX_FLAGS_RELEASE}" ) set( CMAKE_C_FLAGS_RELEASE "${ANDROID_CXX_FLAGS_RELEASE} ${CMAKE_C_FLAGS_RELEASE}" ) set( CMAKE_CXX_FLAGS_DEBUG "${ANDROID_CXX_FLAGS_DEBUG} ${CMAKE_CXX_FLAGS_DEBUG}" ) set( CMAKE_C_FLAGS_DEBUG "${ANDROID_CXX_FLAGS_DEBUG} ${CMAKE_C_FLAGS_DEBUG}" ) set( CMAKE_SHARED_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} ${CMAKE_SHARED_LINKER_FLAGS}" ) set( CMAKE_MODULE_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} ${CMAKE_MODULE_LINKER_FLAGS}" ) set( CMAKE_EXE_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} ${CMAKE_EXE_LINKER_FLAGS}" ) if( MIPS AND BUILD_WITH_ANDROID_NDK AND ANDROID_NDK_RELEASE STREQUAL "r8" ) set( CMAKE_SHARED_LINKER_FLAGS "-Wl,-T,${ANDROID_NDK_TOOLCHAINS_PATH}/${ANDROID_GCC_TOOLCHAIN_NAME}/mipself.xsc ${CMAKE_SHARED_LINKER_FLAGS}" ) set( CMAKE_MODULE_LINKER_FLAGS "-Wl,-T,${ANDROID_NDK_TOOLCHAINS_PATH}/${ANDROID_GCC_TOOLCHAIN_NAME}/mipself.xsc ${CMAKE_MODULE_LINKER_FLAGS}" ) set( CMAKE_EXE_LINKER_FLAGS "-Wl,-T,${ANDROID_NDK_TOOLCHAINS_PATH}/${ANDROID_GCC_TOOLCHAIN_NAME}/mipself.x ${CMAKE_EXE_LINKER_FLAGS}" ) endif() # configure rtti if( DEFINED ANDROID_RTTI AND ANDROID_STL_FORCE_FEATURES ) if( ANDROID_RTTI ) set( CMAKE_CXX_FLAGS "-frtti ${CMAKE_CXX_FLAGS}" ) else() set( CMAKE_CXX_FLAGS "-fno-rtti ${CMAKE_CXX_FLAGS}" ) endif() endif() # configure exceptios if( DEFINED ANDROID_EXCEPTIONS AND ANDROID_STL_FORCE_FEATURES ) if( ANDROID_EXCEPTIONS ) set( CMAKE_CXX_FLAGS "-fexceptions ${CMAKE_CXX_FLAGS}" ) set( CMAKE_C_FLAGS "-fexceptions ${CMAKE_C_FLAGS}" ) else() set( CMAKE_CXX_FLAGS "-fno-exceptions ${CMAKE_CXX_FLAGS}" ) set( CMAKE_C_FLAGS "-fno-exceptions ${CMAKE_C_FLAGS}" ) endif() endif() # global includes and link directories include_directories( SYSTEM "${ANDROID_SYSROOT}/usr/include" ${ANDROID_STL_INCLUDE_DIRS} ) get_filename_component(__android_install_path "${CMAKE_INSTALL_PREFIX}/libs/${ANDROID_NDK_ABI_NAME}" ABSOLUTE) # avoid CMP0015 policy warning link_directories( "${__android_install_path}" ) # detect if need link crtbegin_so.o explicitly if( NOT DEFINED ANDROID_EXPLICIT_CRT_LINK ) set( __cmd "${CMAKE_CXX_CREATE_SHARED_LIBRARY}" ) string( REPLACE "<CMAKE_CXX_COMPILER>" "${CMAKE_CXX_COMPILER} ${CMAKE_CXX_COMPILER_ARG1}" __cmd "${__cmd}" ) string( REPLACE "<CMAKE_C_COMPILER>" "${CMAKE_C_COMPILER} ${CMAKE_C_COMPILER_ARG1}" __cmd "${__cmd}" ) string( REPLACE "<CMAKE_SHARED_LIBRARY_CXX_FLAGS>" "${CMAKE_CXX_FLAGS}" __cmd "${__cmd}" ) string( REPLACE "<LANGUAGE_COMPILE_FLAGS>" "" __cmd "${__cmd}" ) string( REPLACE "<LINK_FLAGS>" "${CMAKE_SHARED_LINKER_FLAGS}" __cmd "${__cmd}" ) string( REPLACE "<CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS>" "-shared" __cmd "${__cmd}" ) string( REPLACE "<CMAKE_SHARED_LIBRARY_SONAME_CXX_FLAG>" "" __cmd "${__cmd}" ) string( REPLACE "<TARGET_SONAME>" "" __cmd "${__cmd}" ) string( REPLACE "<TARGET>" "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/toolchain_crtlink_test.so" __cmd "${__cmd}" ) string( REPLACE "<OBJECTS>" "\"${ANDROID_SYSROOT}/usr/lib/crtbegin_so.o\"" __cmd "${__cmd}" ) string( REPLACE "<LINK_LIBRARIES>" "" __cmd "${__cmd}" ) separate_arguments( __cmd ) foreach( __var ANDROID_NDK ANDROID_NDK_TOOLCHAINS_PATH ANDROID_STANDALONE_TOOLCHAIN ) if( ${__var} ) set( __tmp "${${__var}}" ) separate_arguments( __tmp ) string( REPLACE "${__tmp}" "${${__var}}" __cmd "${__cmd}") endif() endforeach() string( REPLACE "'" "" __cmd "${__cmd}" ) string( REPLACE "\"" "" __cmd "${__cmd}" ) execute_process( COMMAND ${__cmd} RESULT_VARIABLE __cmd_result OUTPUT_QUIET ERROR_QUIET ) if( __cmd_result EQUAL 0 ) set( ANDROID_EXPLICIT_CRT_LINK ON ) else() set( ANDROID_EXPLICIT_CRT_LINK OFF ) endif() endif() if( ANDROID_EXPLICIT_CRT_LINK ) set( CMAKE_CXX_CREATE_SHARED_LIBRARY "${CMAKE_CXX_CREATE_SHARED_LIBRARY} \"${ANDROID_SYSROOT}/usr/lib/crtbegin_so.o\"" ) set( CMAKE_CXX_CREATE_SHARED_MODULE "${CMAKE_CXX_CREATE_SHARED_MODULE} \"${ANDROID_SYSROOT}/usr/lib/crtbegin_so.o\"" ) endif() # setup output directories set( LIBRARY_OUTPUT_PATH_ROOT ${CMAKE_SOURCE_DIR} CACHE PATH "root for library output, set this to change where android libs are installed to" ) set( CMAKE_INSTALL_PREFIX "${ANDROID_TOOLCHAIN_ROOT}/user" CACHE STRING "path for installing" ) if(NOT _CMAKE_IN_TRY_COMPILE) if( EXISTS "${CMAKE_SOURCE_DIR}/jni/CMakeLists.txt" ) set( EXECUTABLE_OUTPUT_PATH "${LIBRARY_OUTPUT_PATH_ROOT}/bin/${ANDROID_NDK_ABI_NAME}" CACHE PATH "Output directory for applications" ) else() set( EXECUTABLE_OUTPUT_PATH "${LIBRARY_OUTPUT_PATH_ROOT}/bin" CACHE PATH "Output directory for applications" ) endif() set( LIBRARY_OUTPUT_PATH "${LIBRARY_OUTPUT_PATH_ROOT}/libs/${ANDROID_NDK_ABI_NAME}" CACHE PATH "path for android libs" ) endif() # copy shaed stl library to build directory if( NOT _CMAKE_IN_TRY_COMPILE AND __libstl MATCHES "[.]so$" ) get_filename_component( __libstlname "${__libstl}" NAME ) execute_process( COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${__libstl}" "${LIBRARY_OUTPUT_PATH}/${__libstlname}" RESULT_VARIABLE __fileCopyProcess ) if( NOT __fileCopyProcess EQUAL 0 OR NOT EXISTS "${LIBRARY_OUTPUT_PATH}/${__libstlname}") message( SEND_ERROR "Failed copying of ${__libstl} to the ${LIBRARY_OUTPUT_PATH}/${__libstlname}" ) endif() unset( __fileCopyProcess ) unset( __libstlname ) endif() # set these global flags for cmake client scripts to change behavior set( ANDROID True ) set( BUILD_ANDROID True ) # where is the target environment set( CMAKE_FIND_ROOT_PATH "${ANDROID_TOOLCHAIN_ROOT}/bin" "${ANDROID_TOOLCHAIN_ROOT}/${ANDROID_TOOLCHAIN_MACHINE_NAME}" "${ANDROID_SYSROOT}" "${CMAKE_INSTALL_PREFIX}" "${CMAKE_INSTALL_PREFIX}/share" ) # only search for libraries and includes in the ndk toolchain set( CMAKE_FIND_ROOT_PATH_MODE_PROGRAM ONLY ) set( CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY ) set( CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY ) # macro to find packages on the host OS macro( find_host_package ) set( CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER ) set( CMAKE_FIND_ROOT_PATH_MODE_LIBRARY NEVER ) set( CMAKE_FIND_ROOT_PATH_MODE_INCLUDE NEVER ) if( CMAKE_HOST_WIN32 ) SET( WIN32 1 ) SET( UNIX ) elseif( CMAKE_HOST_APPLE ) SET( APPLE 1 ) SET( UNIX ) endif() find_package( ${ARGN} ) SET( WIN32 ) SET( APPLE ) SET( UNIX 1 ) set( CMAKE_FIND_ROOT_PATH_MODE_PROGRAM ONLY ) set( CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY ) set( CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY ) endmacro() # macro to find programs on the host OS macro( find_host_program ) set( CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER ) set( CMAKE_FIND_ROOT_PATH_MODE_LIBRARY NEVER ) set( CMAKE_FIND_ROOT_PATH_MODE_INCLUDE NEVER ) if( CMAKE_HOST_WIN32 ) SET( WIN32 1 ) SET( UNIX ) elseif( CMAKE_HOST_APPLE ) SET( APPLE 1 ) SET( UNIX ) endif() find_program( ${ARGN} ) SET( WIN32 ) SET( APPLE ) SET( UNIX 1 ) set( CMAKE_FIND_ROOT_PATH_MODE_PROGRAM ONLY ) set( CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY ) set( CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY ) endmacro() macro( ANDROID_GET_ABI_RAWNAME TOOLCHAIN_FLAG VAR ) if( "${TOOLCHAIN_FLAG}" STREQUAL "ARMEABI" ) set( ${VAR} "armeabi" ) elseif( "${TOOLCHAIN_FLAG}" STREQUAL "ARMEABI_V7A" ) set( ${VAR} "armeabi-v7a" ) elseif( "${TOOLCHAIN_FLAG}" STREQUAL "X86" ) set( ${VAR} "x86" ) elseif( "${TOOLCHAIN_FLAG}" STREQUAL "MIPS" ) set( ${VAR} "mips" ) else() set( ${VAR} "unknown" ) endif() endmacro() # export toolchain settings for the try_compile() command if( NOT PROJECT_NAME STREQUAL "CMAKE_TRY_COMPILE" ) set( __toolchain_config "") foreach( __var NDK_CCACHE LIBRARY_OUTPUT_PATH_ROOT ANDROID_FORBID_SYGWIN ANDROID_SET_OBSOLETE_VARIABLES ANDROID_NDK_HOST_X64 ANDROID_NDK ANDROID_NDK_LAYOUT ANDROID_STANDALONE_TOOLCHAIN ANDROID_TOOLCHAIN_NAME ANDROID_ABI ANDROID_NATIVE_API_LEVEL ANDROID_STL ANDROID_STL_FORCE_FEATURES ANDROID_FORCE_ARM_BUILD ANDROID_NO_UNDEFINED ANDROID_SO_UNDEFINED ANDROID_FUNCTION_LEVEL_LINKING ANDROID_GOLD_LINKER ANDROID_NOEXECSTACK ANDROID_RELRO ANDROID_LIBM_PATH ANDROID_EXPLICIT_CRT_LINK ) if( DEFINED ${__var} ) if( "${__var}" MATCHES " ") set( __toolchain_config "${__toolchain_config}set( ${__var} \"${${__var}}\" CACHE INTERNAL \"\" )\n" ) else() set( __toolchain_config "${__toolchain_config}set( ${__var} ${${__var}} CACHE INTERNAL \"\" )\n" ) endif() endif() endforeach() file( WRITE "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/android.toolchain.config.cmake" "${__toolchain_config}" ) unset( __toolchain_config ) endif() # force cmake to produce / instead of \ in build commands for Ninja generator if( CMAKE_GENERATOR MATCHES "Ninja" AND CMAKE_HOST_WIN32 ) # it is a bad hack after all # CMake generates Ninja makefiles with UNIX paths only if it thinks that we are going to build with MinGW set( CMAKE_COMPILER_IS_MINGW TRUE ) # tell CMake that we are MinGW set( CMAKE_CROSSCOMPILING TRUE ) # stop recursion enable_language( C ) enable_language( CXX ) # unset( CMAKE_COMPILER_IS_MINGW ) # can't unset because CMake does not convert back-slashes in response files without it unset( MINGW ) endif() # set some obsolete variables for backward compatibility set( ANDROID_SET_OBSOLETE_VARIABLES ON CACHE BOOL "Define obsolete Andrid-specific cmake variables" ) mark_as_advanced( ANDROID_SET_OBSOLETE_VARIABLES ) if( ANDROID_SET_OBSOLETE_VARIABLES ) set( ANDROID_API_LEVEL ${ANDROID_NATIVE_API_LEVEL} ) set( ARM_TARGET "${ANDROID_ABI}" ) set( ARMEABI_NDK_NAME "${ANDROID_NDK_ABI_NAME}" ) endif() # Variables controlling behavior or set by cmake toolchain: # ANDROID_ABI : "armeabi-v7a" (default), "armeabi", "armeabi-v7a with NEON", "armeabi-v7a with VFPV3", "armeabi-v6 with VFP", "x86", "mips" # ANDROID_NATIVE_API_LEVEL : 3,4,5,8,9,14 (depends on NDK version) # ANDROID_STL : gnustl_static/gnustl_shared/stlport_static/stlport_shared/gabi++_static/gabi++_shared/system_re/system/none # ANDROID_FORBID_SYGWIN : ON/OFF # ANDROID_NO_UNDEFINED : ON/OFF # ANDROID_SO_UNDEFINED : OFF/ON (default depends on NDK version) # ANDROID_FUNCTION_LEVEL_LINKING : ON/OFF # ANDROID_GOLD_LINKER : ON/OFF # ANDROID_NOEXECSTACK : ON/OFF # ANDROID_RELRO : ON/OFF # ANDROID_FORCE_ARM_BUILD : ON/OFF # ANDROID_STL_FORCE_FEATURES : ON/OFF # ANDROID_SET_OBSOLETE_VARIABLES : ON/OFF # Can be set only at the first run: # ANDROID_NDK # ANDROID_STANDALONE_TOOLCHAIN # ANDROID_TOOLCHAIN_NAME : the NDK name of compiler toolchain # ANDROID_NDK_HOST_X64 : try to use x86_64 toolchain (default for x64 host systems) # ANDROID_NDK_LAYOUT : the inner NDK structure (RELEASE, LINARO, ANDROID) # LIBRARY_OUTPUT_PATH_ROOT : <any valid path> # NDK_CCACHE : <path to your ccache executable> # Obsolete: # ANDROID_API_LEVEL : superseded by ANDROID_NATIVE_API_LEVEL # ARM_TARGET : superseded by ANDROID_ABI # ARM_TARGETS : superseded by ANDROID_ABI (can be set only) # ANDROID_NDK_TOOLCHAIN_ROOT : superseded by ANDROID_STANDALONE_TOOLCHAIN (can be set only) # ANDROID_USE_STLPORT : superseded by ANDROID_STL=stlport_static # ANDROID_LEVEL : superseded by ANDROID_NATIVE_API_LEVEL (completely removed) # # Primary read-only variables: # ANDROID : always TRUE # ARMEABI : TRUE for arm v6 and older devices # ARMEABI_V6 : TRUE for arm v6 # ARMEABI_V7A : TRUE for arm v7a # NEON : TRUE if NEON unit is enabled # VFPV3 : TRUE if VFP version 3 is enabled # X86 : TRUE if configured for x86 # MIPS : TRUE if configured for mips # BUILD_ANDROID : always TRUE # BUILD_WITH_ANDROID_NDK : TRUE if NDK is used # BUILD_WITH_STANDALONE_TOOLCHAIN : TRUE if standalone toolchain is used # ANDROID_NDK_HOST_SYSTEM_NAME : "windows", "linux-x86" or "darwin-x86" depending on host platform # ANDROID_NDK_ABI_NAME : "armeabi", "armeabi-v7a", "x86" or "mips" depending on ANDROID_ABI # ANDROID_NDK_RELEASE : one of r5, r5b, r5c, r6, r6b, r7, r7b, r7c, r8, r8b, r8c, r8d, r8e, r9, r9b, r9c, r9d; set only for NDK # ANDROID_ARCH_NAME : "arm" or "x86" or "mips" depending on ANDROID_ABI # ANDROID_SYSROOT : path to the compiler sysroot # TOOL_OS_SUFFIX : "" or ".exe" depending on host platform # ANDROID_COMPILER_IS_CLANG : TRUE if clang compiler is used # Obsolete: # ARMEABI_NDK_NAME : superseded by ANDROID_NDK_ABI_NAME # # Secondary (less stable) read-only variables: # ANDROID_COMPILER_VERSION : GCC version used # ANDROID_CXX_FLAGS : C/C++ compiler flags required by Android platform # ANDROID_SUPPORTED_ABIS : list of currently allowed values for ANDROID_ABI # ANDROID_TOOLCHAIN_MACHINE_NAME : "arm-linux-androideabi", "arm-eabi" or "i686-android-linux" # ANDROID_TOOLCHAIN_ROOT : path to the top level of toolchain (standalone or placed inside NDK) # ANDROID_CLANG_TOOLCHAIN_ROOT : path to clang tools # ANDROID_SUPPORTED_NATIVE_API_LEVELS : list of native API levels found inside NDK # ANDROID_STL_INCLUDE_DIRS : stl include paths # ANDROID_RTTI : if rtti is enabled by the runtime # ANDROID_EXCEPTIONS : if exceptions are enabled by the runtime # ANDROID_GCC_TOOLCHAIN_NAME : read-only, differs from ANDROID_TOOLCHAIN_NAME only if clang is used # ANDROID_CLANG_VERSION : version of clang compiler if clang is used # ANDROID_LIBM_PATH : path to libm.so (set to something like $(TOP)/out/target/product/<product_name>/obj/lib/libm.so) to workaround unresolved `sincos` # # Defaults: # ANDROID_DEFAULT_NDK_API_LEVEL # ANDROID_DEFAULT_NDK_API_LEVEL_${ARCH} # ANDROID_NDK_SEARCH_PATHS # ANDROID_STANDALONE_TOOLCHAIN_SEARCH_PATH # ANDROID_SUPPORTED_ABIS_${ARCH} # ANDROID_SUPPORTED_NDK_VERSIONS
{'content_hash': '572927fa0aeabea778f166726d21e712', 'timestamp': '', 'source': 'github', 'line_count': 1471, 'max_line_length': 289, 'avg_line_length': 48.53229095853161, 'alnum_prop': 0.6988415906766959, 'repo_name': 'dinahmoe/dm-cmake', 'id': 'c2000f487fcf15ea66a46698950906cf4c14642a', 'size': '86390', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'android.toolchain.cmake', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CMake', 'bytes': '114910'}]}
LWM (compressed PlayCanvas model) file format toolset ------ * Live demo can be found here: https://playcanvas.com/project/358306/overview/lwm-model-example * Downloadable SDK can be found here: https://github.com/PsichiX/PlayCanvasLWM/releases Tool usage: ------ 1. To convert PlayCanvas JSON model into LWM model, first you need to get JSON file of your model uploaded into PlayCanvas Editor. 2. Then you have to process it with `convertlwm.exe` tool (found in: `/tools/`; it'swritten in C#, so .NET 4.5 is needed to be installed on your machine): ```bash convertlwm.exe -v -i truck.json -o truck.lwm -r -jtb -sspd -ipq 64 ``` * `-v` - process will be verbose; * `-i truck.json` - path to input JSON file; * `-o truck.lwm` - path to output LWM file; * `-r` - overwrite output file if already exists; * `-jtb` - convert from JSON to LWM (if you want to convert from LWM to JSON, then you use `-btj`); * `-sspd` - enables Small Size of Packed Data mode (model will be compressed, not just translated into binary); * `-ipq 64` - defines Items Per Quant count (when used with `-sspd` it will quantize data into chunks that can be compressed even more than without quantization: small chunks - better compression); 3. Upload compressed LWM model onto external server that support CORS (cross-origin) - if your server cannot support CORS for LWM files, you can use `getlwmfile.php` and `.htaccess` files from `/cors/` folder. 4. Add `lib/lwm.js`(debug) or `lib/lwm.min.js`(release) LWM scripts into root object in scene (this library hooks into PlayCanvas engine and allow to decompress and convert LWM files into `pc.Model` instances). 5. Add `components/LWMModel.js` component script into your entity scripts and put address of externally hosted LWM model file into `url` attribute (note that because you cannot upload LWM model files into PlayCanvas Editor, you have to host them externally). 6. Create new JSON file with LWM materials maping description content, that will looks like: ```json { "meshInstancesMapping": [ "Right_Wiper", "Left_Wiper", "Right_Rear", "Left_Rear", "Left_Front", "Right_Front", "TruckBody" ], "materialsMapping": { "Right_Wiper": "Pickup Truck Texture", "Left_Wiper": "Pickup Truck Texture", "Right_Rear": "Pickup Truck Texture", "Left_Rear": "Pickup Truck Texture", "Left_Front": "Pickup Truck Texture", "Right_Front": "Pickup Truck Texture", "TruckBody": "Pickup Truck Texture" } } ``` * meshInstancesMapping tells which mesh instance index will have which name; * materialsMapping tells which mesh instance name will have which material (material can be either string name or assed id number); 7. Attach that JSON into `materialsMapping` attribute. 8. Run your game and check if there is no errors. If you will get an error during LWM model loading, the most reason is that your server does not support CORS correctly - check details in browser debug console! TODO: ------ * Add skin and animation data support
{'content_hash': '18a32d01c5c94f1317392dfa2356d6a4', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 258, 'avg_line_length': 47.50769230769231, 'alnum_prop': 0.7117875647668394, 'repo_name': 'PsichiX/PlayCanvasLWM', 'id': '0c5b267f1dac4ac8e7025572c05b10502387b898', 'size': '3088', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '221'}, {'name': 'Batchfile', 'bytes': '81'}, {'name': 'JavaScript', 'bytes': '4741'}, {'name': 'PHP', 'bytes': '1293'}, {'name': 'Shell', 'bytes': '75'}]}
namespace Microsoft.Azure.CognitiveServices.Vision.Face { using Microsoft.Rest; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Net; using System.Net.Http; /// <summary> /// An API for face detection, verification, and identification. /// </summary> public partial class FaceAPI : ServiceClient<FaceAPI>, IFaceAPI { /// <summary> /// The base URI of the service. /// </summary> internal string BaseUri {get; set;} /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Supported Azure regions for Cognitive Services endpoints. Possible values /// include: 'westus', 'westeurope', 'southeastasia', 'eastus2', /// 'westcentralus', 'westus2', 'eastus', 'southcentralus', 'northeurope', /// 'eastasia', 'australiaeast', 'brazilsouth' /// </summary> public AzureRegions AzureRegion { get; set; } /// <summary> /// Subscription credentials which uniquely identify client subscription. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets the IFaceOperations. /// </summary> public virtual IFaceOperations Face { get; private set; } /// <summary> /// Gets the IPersonGroupPerson. /// </summary> public virtual IPersonGroupPerson PersonGroupPerson { get; private set; } /// <summary> /// Gets the IPersonGroupOperations. /// </summary> public virtual IPersonGroupOperations PersonGroup { get; private set; } /// <summary> /// Gets the IFaceListOperations. /// </summary> public virtual IFaceListOperations FaceList { get; private set; } /// <summary> /// Initializes a new instance of the FaceAPI class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected FaceAPI(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the FaceAPI class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected FaceAPI(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the FaceAPI class. /// </summary> /// <param name='credentials'> /// Required. Subscription credentials which uniquely identify client subscription. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public FaceAPI(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the FaceAPI class. /// </summary> /// <param name='credentials'> /// Required. Subscription credentials which uniquely identify client subscription. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public FaceAPI(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. ///</summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { Face = new FaceOperations(this); PersonGroupPerson = new PersonGroupPerson(this); PersonGroup = new PersonGroupOperations(this); FaceList = new FaceListOperations(this); BaseUri = "https://{AzureRegion}.api.cognitive.microsoft.com/face/v1.0"; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); } } }
{'content_hash': '69e8a4581f958be9653e7bbb60732c95', 'timestamp': '', 'source': 'github', 'line_count': 185, 'max_line_length': 158, 'avg_line_length': 39.32432432432432, 'alnum_prop': 0.5869415807560138, 'repo_name': 'DheerendraRathor/azure-sdk-for-net', 'id': 'ea63df3ce11e2bef12e46a6677a052bfdf05ea92', 'size': '7628', 'binary': False, 'copies': '2', 'ref': 'refs/heads/psSdkJson6', 'path': 'src/SDKs/CognitiveServices/dataPlane/Vision/Face/Face/Generated/FaceAPI.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '118'}, {'name': 'Batchfile', 'bytes': '15938'}, {'name': 'C#', 'bytes': '74830057'}, {'name': 'CSS', 'bytes': '685'}, {'name': 'JavaScript', 'bytes': '7875'}, {'name': 'PowerShell', 'bytes': '21530'}, {'name': 'Shell', 'bytes': '9959'}, {'name': 'XSLT', 'bytes': '6114'}]}
$(document).ready(function() { $("#add-note").on("submit", function(event) { event.preventDefault(); var action = $(this).attr("action"); var method = $(this).attr("method"); var data = $(this).serialize(); var request = $.ajax(action, {"method": method, "data": data}); request.done(function(response) { $("#private-notes").append(response) }) }) $(".delete").on("click", function(event) { event.preventDefault(); var action = $(this).attr("href"); var method = "delete"; var data = "note_id=" + $(this).attr("id"); var deleted_element = $(this).parent() // debugger; var request = $.ajax(action, {"method": method, "data": data}); request.done(function() { deleted_element.remove(); }) }) });
{'content_hash': 'e7b418ace4155a63d0d452715ab2b5dd', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 67, 'avg_line_length': 29.11111111111111, 'alnum_prop': 0.5661577608142494, 'repo_name': 'helin24/FS-Momentum', 'id': '1fab55c903800b2034ede1d5b80e9614be7b7f2e', 'size': '786', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'public/js/skill.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '3484'}, {'name': 'JavaScript', 'bytes': '2123'}, {'name': 'Ruby', 'bytes': '17810'}]}
using System; using System.Collections.Generic; using System.Data; using System.Linq.Expressions; namespace ServiceStack.OrmLite { public static class OrmLiteWriteExpressionsApi { /// <summary> /// Use an SqlExpression to select which fields to update and construct the where expression, E.g: /// /// var q = db.From&gt;Person&lt;()); /// db.UpdateOnly(new Person { FirstName = "JJ" }, q.Update(p => p.FirstName).Where(x => x.FirstName == "Jimi")); /// UPDATE "Person" SET "FirstName" = 'JJ' WHERE ("FirstName" = 'Jimi') /// /// What's not in the update expression doesn't get updated. No where expression updates all rows. E.g: /// /// db.UpdateOnly(new Person { FirstName = "JJ", LastName = "Hendo" }, ev.Update(p => p.FirstName)); /// UPDATE "Person" SET "FirstName" = 'JJ' /// </summary> public static int UpdateOnly<T>(this IDbConnection dbConn, T model, SqlExpression<T> onlyFields, Action<IDbCommand> commandFilter = null) { return dbConn.Exec(dbCmd => dbCmd.UpdateOnly(model, onlyFields, commandFilter)); } /// <summary> /// Update only fields in the specified expression that matches the where condition (if any), E.g: /// /// db.UpdateOnly(() => new Person { FirstName = "JJ" }, where: p => p.LastName == "Hendrix"); /// UPDATE "Person" SET "FirstName" = 'JJ' WHERE ("LastName" = 'Hendrix') /// /// db.UpdateOnly(() => new Person { FirstName = "JJ" }); /// UPDATE "Person" SET "FirstName" = 'JJ' /// </summary> public static int UpdateOnly<T>(this IDbConnection dbConn, Expression<Func<T>> updateFields, Expression<Func<T, bool>> where = null, Action<IDbCommand> commandFilter = null) { return dbConn.Exec(dbCmd => dbCmd.UpdateOnly(updateFields, dbCmd.GetDialectProvider().SqlExpression<T>().Where(where), commandFilter)); } /// <summary> /// Update only fields in the specified expression that matches the where condition (if any), E.g: /// /// db.UpdateOnly(() => new Person { FirstName = "JJ" }, db.From&gt;Person&lt;().Where(p => p.LastName == "Hendrix")); /// UPDATE "Person" SET "FirstName" = 'JJ' WHERE ("LastName" = 'Hendrix') /// </summary> public static int UpdateOnly<T>(this IDbConnection dbConn, Expression<Func<T>> updateFields, SqlExpression<T> q, Action<IDbCommand> commandFilter = null) { return dbConn.Exec(dbCmd => dbCmd.UpdateOnly(updateFields, q, commandFilter)); } /// <summary> /// Update only fields in the specified expression that matches the where condition (if any), E.g: /// /// var q = db.From&gt;Person&lt;().Where(p => p.LastName == "Hendrix"); /// db.UpdateOnly(() => new Person { FirstName = "JJ" }, q.WhereExpression, q.Params); /// UPDATE "Person" SET "FirstName" = 'JJ' WHERE ("LastName" = 'Hendrix') /// </summary> public static int UpdateOnly<T>(this IDbConnection dbConn, Expression<Func<T>> updateFields, string whereExpression, IEnumerable<IDbDataParameter> sqlParams, Action<IDbCommand> commandFilter = null) { return dbConn.Exec(dbCmd => dbCmd.UpdateOnly(updateFields, whereExpression, sqlParams, commandFilter)); } /// <summary> /// Update record, updating only fields specified in updateOnly that matches the where condition (if any), E.g: /// /// db.UpdateOnly(new Person { FirstName = "JJ" }, p => p.FirstName, p => p.LastName == "Hendrix"); /// UPDATE "Person" SET "FirstName" = 'JJ' WHERE ("LastName" = 'Hendrix') /// /// db.UpdateOnly(new Person { FirstName = "JJ" }, p => p.FirstName); /// UPDATE "Person" SET "FirstName" = 'JJ' /// /// db.UpdateOnly(new Person { FirstName = "JJ", Age = 27 }, p => new { p.FirstName, p.Age ); /// UPDATE "Person" SET "FirstName" = 'JJ', "Age" = 27 /// </summary> public static int UpdateOnly<T>(this IDbConnection dbConn, T obj, Expression<Func<T, object>> onlyFields = null, Expression<Func<T, bool>> where = null, Action<IDbCommand> commandFilter = null) { return dbConn.Exec(dbCmd => dbCmd.UpdateOnly(obj, onlyFields, where, commandFilter)); } /// <summary> /// Update record, updating only fields specified in updateOnly that matches the where condition (if any), E.g: /// /// db.UpdateOnly(new Person { FirstName = "JJ" }, new[]{ "FirstName" }, p => p.LastName == "Hendrix"); /// UPDATE "Person" SET "FirstName" = 'JJ' WHERE ("LastName" = 'Hendrix') /// </summary> public static int UpdateOnly<T>(this IDbConnection dbConn, T obj, string[] onlyFields, Expression<Func<T, bool>> where = null, Action<IDbCommand> commandFilter = null) { return dbConn.Exec(dbCmd => dbCmd.UpdateOnly(obj, onlyFields, where, commandFilter)); } /// <summary> /// Update record, updating only fields specified in updateOnly that matches the where condition (if any), E.g: /// Numeric fields generates an increment sql which is useful to increment counters, etc... /// avoiding concurrency conflicts /// /// db.UpdateAdd(() => new Person { Age = 5 }, where: p => p.LastName == "Hendrix"); /// UPDATE "Person" SET "Age" = "Age" + 5 WHERE ("LastName" = 'Hendrix') /// /// db.UpdateAdd(() => new Person { Age = 5 }); /// UPDATE "Person" SET "Age" = "Age" + 5 /// </summary> public static int UpdateAdd<T>(this IDbConnection dbConn, Expression<Func<T>> updateFields, Expression<Func<T, bool>> where = null, Action<IDbCommand> commandFilter = null) { return dbConn.Exec(dbCmd => dbCmd.UpdateAdd(updateFields, dbCmd.GetDialectProvider().SqlExpression<T>().Where(where), commandFilter)); } /// <summary> /// Update record, updating only fields specified in updateOnly that matches the where condition (if any), E.g: /// Numeric fields generates an increment sql which is useful to increment counters, etc... /// avoiding concurrency conflicts /// /// db.UpdateAdd(() => new Person { Age = 5 }, db.From&lt;Person&gt;().Where(p => p.LastName == "Hendrix")); /// UPDATE "Person" SET "Age" = "Age" + 5 WHERE ("LastName" = 'Hendrix') /// </summary> public static int UpdateAdd<T>(this IDbConnection dbConn, Expression<Func<T>> updateFields, SqlExpression<T> q, Action<IDbCommand> commandFilter = null) { return dbConn.Exec(dbCmd => dbCmd.UpdateAdd(updateFields, q, commandFilter)); } /// <summary> /// Updates all values from Object Dictionary matching the where condition. E.g /// /// db.UpdateOnly&lt;Person&gt;(new Dictionary&lt;string,object&lt; { {"FirstName", "JJ"} }, where:p => p.FirstName == "Jimi"); /// UPDATE "Person" SET "FirstName" = 'JJ' WHERE ("FirstName" = 'Jimi') /// </summary> public static int UpdateOnly<T>(this IDbConnection dbConn, Dictionary<string, object> updateFields, Expression<Func<T, bool>> obj) { return dbConn.Exec(dbCmd => dbCmd.UpdateOnly(updateFields, obj)); } /// <summary> /// Updates all non-default values set on item matching the where condition (if any). E.g /// /// db.UpdateNonDefaults(new Person { FirstName = "JJ" }, p => p.FirstName == "Jimi"); /// UPDATE "Person" SET "FirstName" = 'JJ' WHERE ("FirstName" = 'Jimi') /// </summary> public static int UpdateNonDefaults<T>(this IDbConnection dbConn, T item, Expression<Func<T, bool>> obj) { return dbConn.Exec(dbCmd => dbCmd.UpdateNonDefaults(item, obj)); } /// <summary> /// Updates all values set on item matching the where condition (if any). E.g /// /// db.Update(new Person { Id = 1, FirstName = "JJ" }, p => p.LastName == "Hendrix"); /// UPDATE "Person" SET "Id" = 1,"FirstName" = 'JJ',"LastName" = NULL,"Age" = 0 WHERE ("LastName" = 'Hendrix') /// </summary> public static int Update<T>(this IDbConnection dbConn, T item, Expression<Func<T, bool>> where, Action<IDbCommand> commandFilter = null) { return dbConn.Exec(dbCmd => dbCmd.Update(item, where, commandFilter)); } /// <summary> /// Updates the entity using the primary key as the filter /// </summary> public static int Update<T>(this IDbConnection dbConn, object entity) { return dbConn.Exec(dbCmd => dbCmd.Update<T>(entity, where:null, commandFilter:null)); } /// <summary> /// Updates all matching fields populated on anonymousType that matches where condition (if any). E.g: /// /// db.Update&lt;Person&gt;(new { FirstName = "JJ" }, p => p.LastName == "Hendrix"); /// UPDATE "Person" SET "FirstName" = 'JJ' WHERE ("LastName" = 'Hendrix') /// </summary> public static int Update<T>(this IDbConnection dbConn, object updateOnly, Expression<Func<T, bool>> where, Action<IDbCommand> commandFilter = null) { return dbConn.Exec(dbCmd => dbCmd.Update<T>(updateOnly, where, commandFilter)); } /// <summary> /// Using an SqlExpression to only Insert the fields specified, e.g: /// /// db.InsertOnly(new Person { FirstName = "Amy" }, p => p.FirstName)); /// INSERT INTO "Person" ("FirstName") VALUES ('Amy'); /// /// db.InsertOnly(new Person { Id =1 , FirstName="Amy" }, p => new { p.Id, p.FirstName })); /// INSERT INTO "Person" ("Id", "FirstName") VALUES (1, 'Amy'); /// </summary> public static long InsertOnly<T>(this IDbConnection dbConn, T obj, Expression<Func<T, object>> onlyFields, bool selectIdentity = false) { return dbConn.Exec(dbCmd => dbCmd.InsertOnly(obj, onlyFields.GetFieldNames(), selectIdentity)); } /// <summary> /// Using an SqlExpression to only Insert the fields specified, e.g: /// /// db.InsertOnly(new Person { FirstName = "Amy" }, new[]{ "FirstName" })); /// INSERT INTO "Person" ("FirstName") VALUES ('Amy'); /// </summary> public static long InsertOnly<T>(this IDbConnection dbConn, T obj, string[] onlyFields, bool selectIdentity = false) { return dbConn.Exec(dbCmd => dbCmd.InsertOnly(obj, onlyFields, selectIdentity)); } /// <summary> /// Using an SqlExpression to only Insert the fields specified, e.g: /// /// db.InsertOnly(() => new Person { FirstName = "Amy" })); /// INSERT INTO "Person" ("FirstName") VALUES (@FirstName); /// </summary> public static long InsertOnly<T>(this IDbConnection dbConn, Expression<Func<T>> insertFields, bool selectIdentity = false) { return dbConn.Exec(dbCmd => dbCmd.InsertOnly(insertFields, selectIdentity)); } /// <summary> /// Delete the rows that matches the where expression, e.g: /// /// db.Delete&lt;Person&gt;(p => p.Age == 27); /// DELETE FROM "Person" WHERE ("Age" = 27) /// </summary> public static int Delete<T>(this IDbConnection dbConn, Expression<Func<T, bool>> where) { return dbConn.Exec(dbCmd => dbCmd.Delete(where)); } /// <summary> /// Delete the rows that matches the where expression, e.g: /// /// var q = db.From&lt;Person&gt;()); /// db.Delete&lt;Person&gt;(q.Where(p => p.Age == 27)); /// DELETE FROM "Person" WHERE ("Age" = 27) /// </summary> public static int Delete<T>(this IDbConnection dbConn, SqlExpression<T> where) { return dbConn.Exec(dbCmd => dbCmd.Delete(where)); } } }
{'content_hash': 'b9e0f6c6088382028c5e3bbadfbd6ecc', 'timestamp': '', 'source': 'github', 'line_count': 254, 'max_line_length': 155, 'avg_line_length': 49.25984251968504, 'alnum_prop': 0.5728101023017903, 'repo_name': 'Pathfinder-Fr/YAFNET', 'id': '0e47d06e0b057909bd41e636c4356ac7f807766e', 'size': '12514', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'yafsrc/ServiceStack/ServiceStack.OrmLite/OrmLiteWriteExpressionsApi.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '1160769'}, {'name': 'Batchfile', 'bytes': '4612'}, {'name': 'C#', 'bytes': '32268813'}, {'name': 'CSS', 'bytes': '1119799'}, {'name': 'HTML', 'bytes': '14854'}, {'name': 'JavaScript', 'bytes': '5789303'}, {'name': 'PLSQL', 'bytes': '34218'}, {'name': 'PLpgSQL', 'bytes': '53478'}, {'name': 'TSQL', 'bytes': '706921'}]}
SharePoint Add-in Recipe - Yammer Integration ============================================= Summary ------- The approach you take to integrate Yammer with SharePoint is the same in the new SharePoint Add-in model as it is with Full Trust Code. High Level Guidelines --------------------- As a rule of a thumb, we would like to provide the following high level guidelines to integrate Yammer with SharePoint. - Yammer integration may be used in both on-premises and Office 365 SharePoint environments. - You can use the remote provisioning pattern to create Yammer groups and/or Yammer OpenGraph objects to facilitate conversations when you create new SharePoint sites. - You can use the out-of-the-box embed functionality to quickly and easily integrate Yammer with SharePoint. + To use embed you need a HTML container 400 pixels or larger in your application. - You can use the Yammer SDKs and REST APIs to create customized integration functionality. Options to integrate Yammer with SharePoint ------------------------------------------- You have a few options to integrate Yammer with SharePoint. - Embed + Group, Topic, My, and User Feeds + OpenGraph Feeds - Yammer OpenGraph API and/or Yammer REST API with Yammer SDKs Embed ----- In this option you embed a Yammer feed in a SharePoint web page. - This option is quickly and easily implemented. - This option allows you to control limited aspects of the feed and how it appears. Using embed looks like this in your SharePoint page: ![](media/Recipes/Yammer/YammerEmbed.png) The following table describes each type of Yammer feed you can access with embed out-of-the-box. Feed | Description | FeedType | Use Case ---- | ----------- | -------- | -------- My Feed | My Feeds are where conversations are delivered for Yammer users. | MyFeed | My Site homepage or workspace site. User Feed | All the conversations posted by a specific user in Yammer. | User | Profile pages for users in a system directory. Topic Feed | A feed of conversations that have been tagged with a topic in Yammer. | Topic | An event page on an intranet. Group Feed | A feed of conversations that have been posted in a specified group. | Group | A team page on an intranet. If you need to go beyond the capabilities of the out-of-the-box Yammer feeds in the table above you can use the OpenGraph embed option. This option gives you more control of the feed. The following table illustrates such an example. Feed | Description | FeedType | Use Case ---- | ----------- | -------- | -------- Comment Feed | Uses Yammer’s Open Graph API to facilitate conversation around an application object. | Custom | An opportunity in a custom CRM application, or a media detail page in a digital asset management system. **When is it a good fit?** When you are trying to integrate Yammer feeds with SharePoint sites and the out-of-the-box capabilities of the embed feed meet your needs. **Getting Started** The following sample demonstrates how to provision sites with a Yammer feed associated with the site in place of the default news feed for the site. - [Provisioning.Yammer (O365 PnP Sample)](https://github.com/OfficeDev/PnP/tree/master/Scenarios/Provisioning.Yammer) The **CreateYammerGroupDiscussionPartXml** method in the [YammerUtility.cs](https://github.com/OfficeDev/PnP/blob/master/OfficeDevPnP.Core/OfficeDevPnP.Core/Utilities/YammerUtility.cs) class comes from the [OfficeDevPnP.Core](https://github.com/OfficeDev/PnP/blob/master/OfficeDevPnP.Core/OfficeDevPnP.Core) sample. This method creates the XML for an App Part definition that is added to a SharePoint page when a site is provisioned. Notice the **feedType: 'group'** portion of the code. Here you can see the feedType is set to use the out-of-the-box group feedType. public static string CreateYammerGroupDiscussionPartXml(string yammerNetworkName, int yammerGroupId, bool showHeader, bool showFooter, bool useSSO = true) { StringBuilder wp = new StringBuilder(100); wp.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>"); wp.Append("<webParts>"); wp.Append(" <webPart xmlns='http://schemas.microsoft.com/WebPart/v3'>"); wp.Append(" <metaData>"); wp.Append(" <type name='Microsoft.SharePoint.WebPartPages.ScriptEditorWebPart, Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' />"); wp.Append(" <importErrorMessage>Cannot import this Web Part.</importErrorMessage>"); wp.Append(" </metaData>"); wp.Append(" <data>"); wp.Append(" <properties>"); wp.Append(" <property name='Title' type='string'>$Resources:core,ScriptEditorWebPartTitle;</property>"); wp.Append(" <property name='Description' type='string'>$Resources:core,ScriptEditorWebPartDescription;</property>"); wp.Append(" <property name='ChromeType' type='chrometype'>None</property>"); wp.Append(" <property name='Content' type='string'>"); wp.Append(" <![CDATA["); wp.Append(" <div id='embedded-feed' style='height: 500px;'></div>"); wp.Append(" <script type='text/javascript' src='https://assets.yammer.com/assets/platform_embed.js'></script>"); wp.Append(" <script type='text/javascript'> yam.connect.embedFeed({ container: '#embedded-feed', network: '" + yammerNetworkName + @"', feedType: 'group', feedId: '" + yammerGroupId + @"', config: { use_sso: " + useSSO.ToString().ToLower() + @", header: " + showHeader.ToString().ToLower() + @", footer: " + showFooter.ToString().ToLower() + " }}); </script>"); wp.Append(" ]]>"); wp.Append(" </property>"); wp.Append(" </properties>"); wp.Append(" </data>"); wp.Append(" </webPart>"); wp.Append("</webParts>"); return wp.ToString(); } The **CreateYammerOpenGraphDiscussionPartXml** method in the [YammerUtility.cs](https://github.com/OfficeDev/PnP/blob/master/OfficeDevPnP.Core/OfficeDevPnP.Core/Utilities/YammerUtility.cs) class comes from the [OfficeDevPnP.Core](https://github.com/OfficeDev/PnP/blob/master/OfficeDevPnP.Core/OfficeDevPnP.Core) sample. This method creates the XML for an App Part definition that is added to a SharePoint page when a site is provisioned. Notice the **feedType: 'open-graph'** portion of the code. Here you can see the feedType is set to use the OpenGraph API. public static string CreateYammerOpenGraphDiscussionPartXml(string yammerNetworkName, string url, bool showHeader, bool showFooter, string postTitle="", string postImageUrl="", bool useSso = true, string groupId = "") { StringBuilder wp = new StringBuilder(100); wp.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>"); wp.Append("<webParts>"); wp.Append(" <webPart xmlns='http://schemas.microsoft.com/WebPart/v3'>"); wp.Append(" <metaData>"); wp.Append(" <type name='Microsoft.SharePoint.WebPartPages.ScriptEditorWebPart, Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' />"); wp.Append(" <importErrorMessage>Cannot import this Web Part.</importErrorMessage>"); wp.Append(" </metaData>"); wp.Append(" <data>"); wp.Append(" <properties>"); wp.Append(" <property name='Title' type='string'>$Resources:core,ScriptEditorWebPartTitle;</property>"); wp.Append(" <property name='Description' type='string'>$Resources:core,ScriptEditorWebPartDescription;</property>"); wp.Append(" <property name='ChromeType' type='chrometype'>None</property>"); wp.Append(" <property name='Content' type='string'>"); wp.Append(" <![CDATA["); wp.Append(" <div id='embedded-feed' style='height: 500px;'></div>"); wp.Append(" <script type='text/javascript' src='https://assets.yammer.com/assets/platform_embed.js'></script>"); wp.Append(" <script>"); wp.Append(" yam.connect.embedFeed({"); wp.Append(" container: '#embedded-feed'"); wp.Append(" , feedType: 'open-graph'"); wp.Append(" , feedId: ''"); wp.Append(" , config: {"); wp.Append(" use_sso: " + useSso.ToString().ToLower()); wp.Append(" , header: " + showHeader.ToString().ToLower()); wp.Append(" , footer: " + showFooter.ToString().ToLower()); wp.Append(" , showOpenGraphPreview: false"); wp.Append(" , defaultToCanonical: false"); wp.Append(" , hideNetworkName: false"); wp.Append(" , promptText: 'Start a conversation'"); if (!string.IsNullOrEmpty(groupId)) { wp.Append(" , defaultGroupId: '" + groupId + "'"); } wp.Append(" }"); wp.Append(" , objectProperties: {"); wp.Append(" url: '" + url + "'"); wp.Append(" , type: 'page'"); wp.Append(" , title: '" + postTitle + "'"); wp.Append(" , image: '" + postImageUrl + "'"); wp.Append(" }"); wp.Append(" });"); wp.Append(" </script>"); wp.Append(" ]]>"); wp.Append(" </property>"); wp.Append(" </properties>"); wp.Append(" </data>"); wp.Append(" </webPart>"); wp.Append("</webParts>"); return wp.ToString(); } Watch the [Integrate Yammer feeds to SharePoint sites (O365 PnP Video)](https://channel9.msdn.com/blogs/OfficeDevPnP/Integrate-Yammer-feeds-to-SharePoint-sites) to see a walk through of the - [Provisioning.Yammer (O365 PnP Sample)](https://github.com/OfficeDev/PnP/tree/master/Scenarios/Provisioning.Yammer). For more information about Yammer embed see the [Yammer Embed Feed (Yammer Developer Center)](https://developer.yammer.com/v1.0/docs/embed) article. For more information about Yammer OpenGraph see the [Open Graph Introduction & Format (Yammer Developer Center)](https://developer.yammer.com/v1.0/docs/open-graph) article. Yammer OpenGraph API & Yammer REST API with Yammer SDKs ------------------------------------------------------- In this option you use the Yammer OpenGraph API and/or Yammer REST API with Yammer SDKs to integrate Yammer with SharePoint. These APIs may also be used to integrate Yammer with processes outside of web pages. Examples of such scenarios include services and long running operations. - This option takes longer to implement. - This option allows you to control all aspects of the feed and how it appears and how you interact with it. **When is it a good fit?** - When you are trying to integrate Yammer feeds with SharePoint sites and the out-of-the-box capabilities of the embed feeds do not meet your needs. - When you are trying to integrate Yammer feeds into services or long running operations. **Getting Started** For more information about Yammer OpenGraph see the [Open Graph Introduction & Format (Yammer Developer Center)](https://developer.yammer.com/v1.0/docs/open-graph) article. Yammer SDKs provide you the ability to authenticate to Yammer. For more information about the Yammer SDKs see the following articles: - [JavaScript SDK](https://developer.yammer.com/v1.0/docs/js-sdk) - [Ruby SDK](https://developer.yammer.com/v1.0/docs/ruby-sdk) - [Python SDK](https://developer.yammer.com/v1.0/docs/python-sdk) - [iOS SDK](https://developer.yammer.com/v1.0/docs/ios-sdk) - [.NET SDK](https://developer.yammer.com/v1.0/docs/net-sdk) - [Windows Phone 8 SDK](https://developer.yammer.com/v1.0/docs/windows-phone-8-sdk) After you have authenticated to Yammer via the Yammer SDKs you can call the Yammer REST APIs. For more information about Yammer REST APIs see the [REST API & Rate Limits (Yammer Developer Center)](https://developer.yammer.com/v1.0/docs/rest-api-rate-limits) article. **Authentication Note** In a scenario where you sign into SharePoint with credentials that differ from the credentials you use to sign into SharePoint with you may wish to develop a single-sign-on capability for your users. An example of such a scenario is when you sign into SharePoint with a LiveID and you need to sign into Yammer with a Microsoft personal or work account. To implement a single-sign-on scenario you can direct your users to sign into Yammer the first time they come to a SharePoint page with your custom Yammer component on it. After the user signs into Yammer via the Yammer SDK you can store the refresh token for the user in their user profile. Then, on subsequent visits to the page you can retrieve the refresh token from the user profile and use it to authenticate. With this approach your end users only need to sign into Yammer when their refresh token expires. Related links ============= - [Integrate Yammer feeds to SharePoint sites (O365 PnP Video)](https://channel9.msdn.com/blogs/OfficeDevPnP/Integrate-Yammer-feeds-to-SharePoint-sites) - [Yammer Embed Feed (Yammer Developer Center)](https://developer.yammer.com/v1.0/docs/embed) - [Open Graph Introduction & Format (Yammer Developer Center)](https://developer.yammer.com/v1.0/docs/open-graph) - Guidance articles at [http://aka.ms/OfficeDevPnPGuidance](http://aka.ms/OfficeDevPnPGuidance "Guidance Articles") - References in MSDN at [http://aka.ms/OfficeDevPnPMSDN](http://aka.ms/OfficeDevPnPMSDN "References in MSDN") - Videos at [http://aka.ms/OfficeDevPnPVideos](http://aka.ms/OfficeDevPnPVideos "Videos") Related PnP samples =================== - [Provisioning.Yammer (O365 PnP Sample)](https://github.com/OfficeDev/PnP/tree/master/Scenarios/Provisioning.Yammer) - [OfficeDevPnP.Core](https://github.com/OfficeDev/PnP/blob/master/OfficeDevPnP.Core/OfficeDevPnP.Core) - Samples and content at [http://aka.ms/OfficeDevPnP](http://aka.ms/OfficeDevPnP) Applies to ========== - Office 365 Multi Tenant (MT) - Office 365 Dedicated (D) - SharePoint 2013 on-premises Author ------ Todd Baginski (Canviz LLC) - [@toddbaginski](https://twitter.com/toddbaginski) Version history --------------- Version | Date | Comments | Author ---------| -----| ---------| ------ 0.1 | July 6, 2015 | Initial draft | Todd Baginski (Canviz LLC)
{'content_hash': 'c07bd269c801bd0184ef56c00e2c0eb5', 'timestamp': '', 'source': 'github', 'line_count': 237, 'max_line_length': 569, 'avg_line_length': 63.19409282700422, 'alnum_prop': 0.6536689590705749, 'repo_name': 'weshackett/PnP-Guidance', 'id': 'ab788b050a2436f49033347666e6203dc906b845', 'size': '14979', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'articles/SharePoint-Add-In-Recipe-yammer-integration.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
using System; using System.Collections.Generic; using System.Reflection; namespace Ploeh.AutoFixture.Kernel { /// <summary> /// A specification that determines whether the request is a request /// for a <see cref="FieldInfo"/> matching the specified name and <see cref="Type"/>. /// </summary> public class FieldSpecification : IRequestSpecification { private readonly Type targetType; private readonly string targetName; private readonly IEquatable<FieldInfo> target; /// <summary> /// Initializes a new instance of the <see cref="FieldSpecification"/> class. /// </summary> /// <param name="targetType"> /// The <see cref="Type"/> with which the requested /// <see cref="FieldInfo"/> type should be compatible. /// </param> /// <param name="targetName"> /// The name which the requested <see cref="FieldInfo"/> name /// should match exactly. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="targetType"/> or /// <paramref name="targetName"/> is <see langword="null"/>. /// </exception> public FieldSpecification(Type targetType, string targetName) : this(CreateDefaultTarget(targetType, targetName)) { this.targetType = targetType; this.targetName = targetName; } private static IEquatable<FieldInfo> CreateDefaultTarget( Type targetType, string targetName) { if (targetType == null) throw new ArgumentNullException("targetType"); if (targetName == null) throw new ArgumentNullException("targetName"); return new FieldTypeAndNameCriterion( new Criterion<Type>( targetType, new DerivesFromTypeComparer()), new Criterion<string>( targetName, EqualityComparer<string>.Default)); } /// <summary> /// Initializes a new instance of the <see cref="FieldSpecification"/> class. /// </summary> /// <param name="target"> /// The criteria used to match the requested /// <see cref="FieldInfo"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="target"/> is <see langword="null"/>. /// </exception> public FieldSpecification(IEquatable<FieldInfo> target) { if (target == null) throw new ArgumentNullException("target"); this.target = target; } /// <summary> /// The <see cref="Type"/> with which the requested /// <see cref="FieldInfo"/> type should be compatible. /// </summary> [Obsolete("This value is only available if the constructor taking a target type and name is used. Otherwise, it'll be null. Use with caution. This propery will be removed in a future version of AutoFixture.", false)] public Type TargetType { get { return this.targetType; } } /// <summary> /// The name which the requested <see cref="FieldInfo"/> name /// should match exactly. /// </summary> [Obsolete("This value is only available if the constructor taking a target type and name is used. Otherwise, it'll be null. Use with caution. This propery will be removed in a future version of AutoFixture.", false)] public string TargetName { get { return this.targetName; } } /// <summary> /// Evaluates a request for a specimen. /// </summary> /// <param name="request">The specimen request.</param> /// <returns> /// <see langword="true"/> if <paramref name="request"/> is satisfied by the Specification; /// otherwise, <see langword="false"/>. /// </returns> public bool IsSatisfiedBy(object request) { if (request == null) throw new ArgumentNullException("request"); var f = request as FieldInfo; if (f == null) return false; return this.target.Equals(f); } private class DerivesFromTypeComparer : IEqualityComparer<Type> { public bool Equals(Type x, Type y) { if (y == null && x == null) return true; if (y == null) return false; return y.IsAssignableFrom(x); } public int GetHashCode(Type obj) { return 0; } } } }
{'content_hash': '61f5e6b4d20ee0fbf466e8559b7b5856', 'timestamp': '', 'source': 'github', 'line_count': 132, 'max_line_length': 224, 'avg_line_length': 36.22727272727273, 'alnum_prop': 0.5529067335842743, 'repo_name': 'yuva2achieve/AutoFixture', 'id': 'fe012e6d83d0d9d3f20f2ad57e6bbfd9152a0dd6', 'size': '4784', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Src/AutoFixture/Kernel/FieldSpecification.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '3713467'}, {'name': 'F#', 'bytes': '43535'}, {'name': 'PowerShell', 'bytes': '675'}, {'name': 'Puppet', 'bytes': '170'}, {'name': 'Shell', 'bytes': '309'}, {'name': 'Smalltalk', 'bytes': '2018'}, {'name': 'XSLT', 'bytes': '17270'}]}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en-GB" xml:lang="en-GB" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title>Statistics of Polarity in UD_Uyghur-UDT</title> <link rel="root" href=""/> <!-- for JS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/> <link rel="stylesheet" type="text/css" href="../../css/style.css"/> <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/> <link rel="stylesheet" type="text/css" href="../../css/hint.css"/> <script type="text/javascript" src="../../lib/ext/head.load.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/anchor-js/3.2.2/anchor.min.js"></script> <script>document.addEventListener("DOMContentLoaded", function(event) {anchors.add();});</script> <!-- Set up this custom Google search at https://cse.google.com/cse/business/settings?cx=001145188882102106025:dl1mehhcgbo --> <!-- DZ 2021-01-22: I am temporarily hiding the search field to find out whether it slows down loading of the title page. <script> (function() { var cx = '001145188882102106025:dl1mehhcgbo'; var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true; gcse.src = 'https://cse.google.com/cse.js?cx=' + cx; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s); })(); </script> --> <!-- <link rel="shortcut icon" href="favicon.ico"/> --> </head> <body> <div id="main" class="center"> <div id="hp-header"> <table width="100%"><tr><td width="50%"> <span class="header-text"><a href="http://universaldependencies.org/#language-">home</a></span> <span class="header-text"><a href="https://github.com/universaldependencies/docs/edit/pages-source/treebanks/ug_udt/ug_udt-feat-Polarity.md" target="#">edit page</a></span> <span class="header-text"><a href="https://github.com/universaldependencies/docs/issues">issue tracker</a></span> </td><td> <gcse:search></gcse:search> </td></tr></table> </div> <hr/> <div class="v2complete"> This page pertains to UD version 2. </div> <div id="content"> <noscript> <div id="noscript"> It appears that you have Javascript disabled. Please consider enabling Javascript for this page to see the visualizations. </div> </noscript> <!-- The content may include scripts and styles, hence we must load the shared libraries before the content. --> <script type="text/javascript"> console.time('loading libraries'); var root = '../../'; // filled in by jekyll head.js( // External libraries // DZ: Copied from embedding.html. I don't know which one is needed for what, so I'm currently keeping them all. root + 'lib/ext/jquery.min.js', root + 'lib/ext/jquery.svg.min.js', root + 'lib/ext/jquery.svgdom.min.js', root + 'lib/ext/jquery.timeago.js', root + 'lib/ext/jquery-ui.min.js', root + 'lib/ext/waypoints.min.js', root + 'lib/ext/jquery.address.min.js' ); </script> <h2 id="treebank-statistics-ud_uyghur-udt-features-polarity">Treebank Statistics: UD_Uyghur-UDT: Features: <code class="language-plaintext highlighter-rouge">Polarity</code></h2> <p>This feature is universal. It occurs with 1 different values: <code class="language-plaintext highlighter-rouge">Neg</code>.</p> <p>193 tokens (0%) have a non-empty value of <code class="language-plaintext highlighter-rouge">Polarity</code>. 89 types (1%) occur at least once with a non-empty value of <code class="language-plaintext highlighter-rouge">Polarity</code>. 49 lemmas (2%) occur at least once with a non-empty value of <code class="language-plaintext highlighter-rouge">Polarity</code>. The feature is used with 2 part-of-speech tags: <tt><a href="ug_udt-pos-VERB.html">VERB</a></tt> (135; 0% instances), <tt><a href="ug_udt-pos-AUX.html">AUX</a></tt> (58; 0% instances).</p> <h3 id="verb"><code class="language-plaintext highlighter-rouge">VERB</code></h3> <p>135 <tt><a href="ug_udt-pos-VERB.html">VERB</a></tt> tokens (2% of all <code class="language-plaintext highlighter-rouge">VERB</code> tokens) have a non-empty value of <code class="language-plaintext highlighter-rouge">Polarity</code>.</p> <p>The most frequent other feature values with which <code class="language-plaintext highlighter-rouge">VERB</code> and <code class="language-plaintext highlighter-rouge">Polarity</code> co-occurred: <tt><a href="ug_udt-feat-Case.html">Case</a></tt><tt>=EMPTY</tt> (135; 100%), <tt><a href="ug_udt-feat-VerbForm.html">VerbForm</a></tt><tt>=Fin</tt> (114; 84%), <tt><a href="ug_udt-feat-Mood.html">Mood</a></tt><tt>=Ind</tt> (109; 81%), <tt><a href="ug_udt-feat-Person.html">Person</a></tt><tt>=3</tt> (108; 80%), <tt><a href="ug_udt-feat-Aspect.html">Aspect</a></tt><tt>=EMPTY</tt> (102; 76%), <tt><a href="ug_udt-feat-Number.html">Number</a></tt><tt>=Sing</tt> (85; 63%), <tt><a href="ug_udt-feat-Tense.html">Tense</a></tt><tt>=Past</tt> (76; 56%).</p> <p><code class="language-plaintext highlighter-rouge">VERB</code> tokens may have the following values of <code class="language-plaintext highlighter-rouge">Polarity</code>:</p> <ul> <li><code class="language-plaintext highlighter-rouge">Neg</code> (135; 100% of non-empty <code class="language-plaintext highlighter-rouge">Polarity</code>): بولمىغان، بولمايدۇ، باقمىغان، بولمىسا، قىلمىدى، ئوخشىمىغان، ئويلىمىغان، دېمىسىمۇ، قارىمايدۇ، كەلمەيدۇ</li> <li><code class="language-plaintext highlighter-rouge">EMPTY</code> (8193): دەپ، دېدى، بولۇپ، قىلىپ، دەپتۇ، قاراپ، بار، ئېلىپ، دېگەن، كېلىپ</li> </ul> <p><code class="language-plaintext highlighter-rouge">Polarity</code> seems to be <strong>lexical feature</strong> of <code class="language-plaintext highlighter-rouge">VERB</code>. 100% lemmas (48) occur only with one value of <code class="language-plaintext highlighter-rouge">Polarity</code>.</p> <h3 id="aux"><code class="language-plaintext highlighter-rouge">AUX</code></h3> <p>58 <tt><a href="ug_udt-pos-AUX.html">AUX</a></tt> tokens (6% of all <code class="language-plaintext highlighter-rouge">AUX</code> tokens) have a non-empty value of <code class="language-plaintext highlighter-rouge">Polarity</code>.</p> <p>The most frequent other feature values with which <code class="language-plaintext highlighter-rouge">AUX</code> and <code class="language-plaintext highlighter-rouge">Polarity</code> co-occurred: <tt><a href="ug_udt-feat-Person.html">Person</a></tt><tt>=3</tt> (56; 97%), <tt><a href="ug_udt-feat-Number.html">Number</a></tt><tt>=Sing</tt> (55; 95%), <tt><a href="ug_udt-feat-Aspect.html">Aspect</a></tt><tt>=EMPTY</tt> (44; 76%), <tt><a href="ug_udt-feat-Tense.html">Tense</a></tt><tt>=EMPTY</tt> (39; 67%), <tt><a href="ug_udt-feat-Mood.html">Mood</a></tt><tt>=EMPTY</tt> (36; 62%), <tt><a href="ug_udt-feat-VerbForm.html">VerbForm</a></tt><tt>=EMPTY</tt> (36; 62%).</p> <p><code class="language-plaintext highlighter-rouge">AUX</code> tokens may have the following values of <code class="language-plaintext highlighter-rouge">Polarity</code>:</p> <ul> <li><code class="language-plaintext highlighter-rouge">Neg</code> (58; 100% of non-empty <code class="language-plaintext highlighter-rouge">Polarity</code>): ئەمەس، بولمايدۇ، ئەمەسمۇ، بولمىغان، قالمايدۇ، بولمامدۇ، بولمىسا، بولمىسىمۇ، تۇرمامدۇ، قالمىدۇق</li> <li><code class="language-plaintext highlighter-rouge">EMPTY</code> (852): ئىدى، بولۇپ، ئىكەن، كەتتى، قالدى، بولسا، بولدى، بولىدۇ، قالدىم، تۇرۇپ</li> </ul> </div> <!-- support for embedded visualizations --> <script type="text/javascript"> var root = '../../'; // filled in by jekyll head.js( // We assume that external libraries such as jquery.min.js have already been loaded outside! // (See _layouts/base.html.) // brat helper modules root + 'lib/brat/configuration.js', root + 'lib/brat/util.js', root + 'lib/brat/annotation_log.js', root + 'lib/ext/webfont.js', // brat modules root + 'lib/brat/dispatcher.js', root + 'lib/brat/url_monitor.js', root + 'lib/brat/visualizer.js', // embedding configuration root + 'lib/local/config.js', // project-specific collection data root + 'lib/local/collections.js', // Annodoc root + 'lib/annodoc/annodoc.js', // NOTE: non-local libraries 'https://spyysalo.github.io/conllu.js/conllu.js' ); var webFontURLs = [ // root + 'static/fonts/Astloch-Bold.ttf', root + 'static/fonts/PT_Sans-Caption-Web-Regular.ttf', root + 'static/fonts/Liberation_Sans-Regular.ttf' ]; var setupTimeago = function() { jQuery("time.timeago").timeago(); }; head.ready(function() { setupTimeago(); // mark current collection (filled in by Jekyll) Collections.listing['_current'] = ''; // perform all embedding and support functions Annodoc.activate(Config.bratCollData, Collections.listing); }); </script> <!-- google analytics --> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-55233688-1', 'auto'); ga('send', 'pageview'); </script> <div id="footer"> <p class="footer-text">&copy; 2014–2021 <a href="http://universaldependencies.org/introduction.html#contributors" style="color:gray">Universal Dependencies contributors</a>. Site powered by <a href="http://spyysalo.github.io/annodoc" style="color:gray">Annodoc</a> and <a href="http://brat.nlplab.org/" style="color:gray">brat</a></p>. </div> </div> </body> </html>
{'content_hash': 'ab2b5d4326226616abf4c1a7abfa5377', 'timestamp': '', 'source': 'github', 'line_count': 191, 'max_line_length': 753, 'avg_line_length': 55.18324607329843, 'alnum_prop': 0.6471537001897533, 'repo_name': 'UniversalDependencies/universaldependencies.github.io', 'id': '7eaa83f3b8c1e691deb33d56696de7140371fd23', 'size': '10833', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'treebanks/ug_udt/ug_udt-feat-Polarity.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '64420'}, {'name': 'HTML', 'bytes': '383191916'}, {'name': 'JavaScript', 'bytes': '687350'}, {'name': 'Perl', 'bytes': '7788'}, {'name': 'Python', 'bytes': '21203'}, {'name': 'Shell', 'bytes': '7253'}]}
'use strict'; // mailgun messaging module // requires account from www.mailgun.com // Free email service for up to 400 messages a day // require config for environment variables var config = require("../../config"); // set config variables var api_key = config.mailgunPrivateApiKey; var domain = config.mailgunDomain; var fromEmail = config.mailgunFromEmail; // initialize mailgun service var mailgun = require('mailgun-js')({ apiKey: api_key, domain: domain }); // create messaging module export object var mailer = {}; // sendOne // sends one email, requires paramater object : // params = { // to: "Blah blah <[email protected]>", // subject: "Blah dee blah", // text: "Blah deedee blah", // html: "<h1>Blah deedee blah</h1>" // }; mailer.sendOne = function(params, callback) { var data = { from: fromEmail, to: params.to, subject: params.subject, text: params.text, html: params.html }; // send message; if there is a callback let it handle the err, else handle err mailgun.messages().send(data, function(err) { if (callback) { callback(err); } else if (err) { console.log(err); } else { console.log('email sent!'); } }); }; // export module.exports = mailer;
{'content_hash': '9509f2a773189dac292fd801580db52d', 'timestamp': '', 'source': 'github', 'line_count': 54, 'max_line_length': 79, 'avg_line_length': 22.40740740740741, 'alnum_prop': 0.6735537190082644, 'repo_name': 'wtabikeshare/open-bike-project', 'id': 'b3bc4a1abc22c7e9152592f0096aa1aec386b12d', 'size': '1210', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'modules/mailgun/index.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '259'}, {'name': 'HTML', 'bytes': '25553'}, {'name': 'JavaScript', 'bytes': '42672'}]}
The tool is designed to query the [PassiveTotal - Get Passive DNS](http://api.passivetotal.org/api/docs/#api-Passive_DNS-GetV2DnsPassive) and [VirusTotal - IP Address Report](https://developers.virustotal.com/v2.0/reference#ip-address-report) APIs to return all domains associated with an IP. Then each site is retrieved live to attempt to detect web technologies in use on each record. The web technology detection is based on a python port of [Wappalyzer](https://wappalyzer.com/) that has been modified to work with Python 3.6.2. **Warning:** This will reach out to all domains associated with an IP, including possibily malicious domains. Use with caution. To reduce the number of malicious domains, the `MALWARE` config can be set to False to remove VirusTotal's "detected urls." *Note:* PassiveTotal's Community API only supports 15 lookups a day. VirusTotal's Public API caps at 4 queries a minute. ## Inputs * IP or List of IPs * Job ID for tracking ## Outputs Web Technologies in use on domains seen in passive DNS records for each IP Up-to-date apps.json: https://raw.githubusercontent.com/AliasIO/Wappalyzer/master/src/apps.json ## Install 1. Install Python 3.6.2 2. pip3 install six 3. pip3 install requests 4. pip3 install flask 5. Update configs.cfg with API keys 6. python3 getwt.py 7. Web browse to the IP and Port configured in configs ### Modules in Use * Python * Version: 3.6.2 * Use: Code Base * flask * Version: 0.12.2 * Use: User Interface * sqlite3 * Version: 2.6.0 * Use: Backend Database * [wad](https://pypi.python.org/pypi/wad) * Version: Custom modified * Use: Web technology scanner * Notes: Modified to work with Python 3.6.2 * six * Version: 1.10.0 * requests * Version 2.18.4 * Use: Retrieve online apps.json #### TODO: * Convert legacy WAD code to beautifulSoup/requests * Support other databases * Handle sites with tarpit-style responses * Add [PassiveTotal - Host_Attributes - Get Components](http://api.passivetotal.org/api/docs/#api-Host_Attributes-GetV2HostAttributesComponents) Integration * Add support for "Last Seen Date"
{'content_hash': 'ceaac205a83cf8eef0c732bcd0914adf', 'timestamp': '', 'source': 'github', 'line_count': 53, 'max_line_length': 532, 'avg_line_length': 39.79245283018868, 'alnum_prop': 0.7496443812233285, 'repo_name': 'import-au/GetWT', 'id': '2c77b34aa6f1d09ff131b462de9967a90cbfa24d', 'size': '2133', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '5579'}, {'name': 'Python', 'bytes': '38791'}]}
package com.opengamma.analytics.financial.interestrate.bond.provider; import static com.opengamma.financial.convention.yield.SimpleYieldConvention.INDEX_LINKED_FLOAT; import static com.opengamma.financial.convention.yield.SimpleYieldConvention.UK_IL_BOND; import static com.opengamma.financial.convention.yield.SimpleYieldConvention.US_IL_REAL; import org.apache.commons.lang.Validate; import com.opengamma.analytics.financial.instrument.inflation.CouponInflationGearing; import com.opengamma.analytics.financial.interestrate.bond.definition.BondCapitalIndexedSecurity; import com.opengamma.analytics.financial.interestrate.inflation.derivative.CouponInflationZeroCouponInterpolationGearing; import com.opengamma.analytics.financial.interestrate.inflation.derivative.CouponInflationZeroCouponMonthlyGearing; import com.opengamma.analytics.financial.interestrate.payments.derivative.Coupon; import com.opengamma.analytics.financial.provider.calculator.inflation.NetAmountInflationCalculator; import com.opengamma.analytics.financial.provider.calculator.inflation.PresentValueCurveSensitivityDiscountingInflationCalculator; import com.opengamma.analytics.financial.provider.calculator.inflation.PresentValueDiscountingInflationCalculator; import com.opengamma.analytics.financial.provider.description.inflation.InflationIssuerProviderInterface; import com.opengamma.analytics.financial.provider.description.inflation.InflationIssuerProviderIssuerDecoratedSpread; import com.opengamma.analytics.financial.provider.description.inflation.InflationProviderDecoratedIssuer; import com.opengamma.analytics.financial.provider.description.inflation.InflationProviderInterface; import com.opengamma.analytics.financial.provider.sensitivity.inflation.MultipleCurrencyInflationSensitivity; import com.opengamma.analytics.math.function.Function1D; import com.opengamma.analytics.math.rootfinding.BracketRoot; import com.opengamma.analytics.math.rootfinding.BrentSingleRootFinder; import com.opengamma.analytics.math.rootfinding.RealSingleRootFinder; import com.opengamma.financial.convention.yield.YieldConvention; import com.opengamma.util.ArgumentChecker; import com.opengamma.util.money.Currency; import com.opengamma.util.money.MultipleCurrencyAmount; /** * Pricing method for inflation bond. The price is computed by index estimation and discounting. */ public final class BondCapitalIndexedSecurityDiscountingMethod { /** * The unique instance of the class. */ private static final BondCapitalIndexedSecurityDiscountingMethod INSTANCE = new BondCapitalIndexedSecurityDiscountingMethod(); /** * Return the class instance. * * @return The instance. */ public static BondCapitalIndexedSecurityDiscountingMethod getInstance() { return INSTANCE; } /** * The present value inflation calculator (for the different parts of the bond transaction). */ private static final PresentValueDiscountingInflationCalculator PVIC = PresentValueDiscountingInflationCalculator.getInstance(); private static final NetAmountInflationCalculator NAIC = NetAmountInflationCalculator.getInstance(); private static final PresentValueCurveSensitivityDiscountingInflationCalculator PVCSIC = PresentValueCurveSensitivityDiscountingInflationCalculator .getInstance(); // TODO: REVIEW: Method depends on Calculator; Calculator would depend on Method (code duplicated to avoid circularity). /** * The root bracket used for yield finding. */ private static final BracketRoot BRACKETER = new BracketRoot(); /** * The root finder used for yield finding. */ private static final RealSingleRootFinder ROOT_FINDER = new BrentSingleRootFinder(); /** * Computes the present value of a capital indexed bound by index estimation and discounting. The value is the value of the nominal and the coupons but not * the settlement. * * @param bond * The bond. * @param provider * The provider. * @return The present value. */ public MultipleCurrencyAmount presentValue(final BondCapitalIndexedSecurity<?> bond, final InflationIssuerProviderInterface provider) { ArgumentChecker.notNull(bond, "Bond"); final InflationProviderInterface creditDiscounting = new InflationProviderDecoratedIssuer(provider, bond.getCurrency(), bond.getIssuerEntity()); final MultipleCurrencyAmount pvNominal = bond.getNominal().accept(PVIC, creditDiscounting); final MultipleCurrencyAmount pvCoupon = bond.getCoupon().accept(PVIC, creditDiscounting); return pvNominal.plus(pvCoupon); } /** * Computes the security present value from a quoted clean real price. The real accrued are added to the clean real price, the result is multiplied by the * inflation index ratio and then discounted from settlement time to 0 with the discounting curve. * * @param bond * The bond security. * @param market * The market. * @param cleanPriceReal * The real clean price. * @return The present value. */ public MultipleCurrencyAmount presentValueFromCleanRealPrice(final BondCapitalIndexedSecurity<?> bond, final InflationIssuerProviderInterface market, final double cleanPriceReal) { Validate.notNull(bond, "Coupon"); Validate.notNull(market, "Market"); final double settlement = bond.getSettlement().accept(PVIC, market.getInflationProvider()).getAmount(bond.getCurrency()); final double cleanPriceNominal = cleanPriceReal * settlement; return presentValueFromCleanNominalPrice(bond, market, cleanPriceNominal); } /** * Computes the security present value from a quoted clean real price. The real accrued are added to the clean real price, the result is multiplied by the * inflation index ratio and then discounted from settlement time to 0 with the discounting curve. * * @param bond * The bond security. * @param market * The market. * @param cleanPriceNominal * The nominal clean price. * @return The present value. */ public MultipleCurrencyAmount presentValueFromCleanNominalPrice(final BondCapitalIndexedSecurity<?> bond, final InflationIssuerProviderInterface market, final double cleanPriceNominal) { Validate.notNull(bond, "Coupon"); Validate.notNull(market, "Market"); final double notional = bond.getCoupon().getNthPayment(0).getNotional(); final MultipleCurrencyAmount nominalAccruedInterest = bond.getSettlement().accept(PVIC, market.getInflationProvider()) .multipliedBy(bond.getAccruedInterest() / notional); final double dirtyPriceNominal = cleanPriceNominal + nominalAccruedInterest.getAmount(bond.getCurrency()); return MultipleCurrencyAmount.of(bond.getCurrency(), dirtyPriceNominal); } /** * Calculates the accrued interest for a fixed-coupon bond using the clean price. The accrued interest is defined as dirty price - clean price. * * @param bond * The bond, not null * @param cleanPrice * The clean price * @return The accrued interest */ public double accruedInterestFromCleanRealPrice(final BondCapitalIndexedSecurity<?> bond, final double cleanPrice) { ArgumentChecker.notNull(bond, "bond"); return dirtyRealPriceFromCleanRealPrice(bond, cleanPrice) - cleanPrice; } /** * Calculates the accrued interest for a fixed-coupon bond using the clean price. The accrued interest is defined as dirty price - clean price. * * @param bond * The bond, not null * @param yield * The yield * @return The accrued interest */ public double accruedInterestFromCleanYield(final BondCapitalIndexedSecurity<?> bond, final double yield) { ArgumentChecker.notNull(bond, "bond"); return dirtyPriceFromRealYield(bond, yield) - cleanPriceFromYield(bond, yield); } /** * Computes the clean real price of a bond security from a dirty real price. * * @param bond * The bond security. * @param dirtyPrice * The dirty price. * @return The clean price. */ public double cleanRealPriceFromDirtyRealPrice(final BondCapitalIndexedSecurity<?> bond, final double dirtyPrice) { final double notional = bond.getCoupon().getNthPayment(0).getNotional(); return dirtyPrice - bond.getAccruedInterest() / notional; } /** * Computes the clean nominal price of a bond security from a dirty real price. * * @param bond * The bond security. * @param dirtyPrice * The dirty price. * @return The clean price. */ public double cleanNominalPriceFromDirtyNominalPrice(final BondCapitalIndexedSecurity<?> bond, final double dirtyPrice) { final double notional = bond.getCoupon().getNthPayment(0).getNotional(); final double indexRatio = bond.getIndexRatio(); return dirtyPrice - bond.getAccruedInterest() / notional * indexRatio; } /** * Computes the clean price of a bond security from curves. * * @param bond * The bond security. * @param issuerMulticurves * The issuer and multi-curves provider. * @return The clean price. */ public double cleanRealPriceFromCurves(final BondCapitalIndexedSecurity<?> bond, final InflationIssuerProviderInterface issuerMulticurves) { final double indexRatio = bond.getIndexRatio(); final double notional = bond.getCoupon().getNthPayment(0).getNotional(); final double df = issuerMulticurves.getMulticurveProvider().getDiscountFactor(bond.getCurrency(), bond.getSettlementTime()); final double pvReal = presentValue(bond, issuerMulticurves).getAmount(bond.getCurrency()) / indexRatio / df / notional; return pvReal - bond.getAccruedInterest() / notional; } /** * Computes the clean price of a bond security from curves. * * @param bond * The bond security. * @param issuerMulticurves * The issuer and multi-curves provider. * @return The clean price. */ public double cleanNominalPriceFromCurves(final BondCapitalIndexedSecurity<?> bond, final InflationIssuerProviderInterface issuerMulticurves) { final double dirtyNominalPrice = dirtyNominalPriceFromCurves(bond, issuerMulticurves); return cleanNominalPriceFromDirtyNominalPrice(bond, dirtyNominalPrice); } /** * Computes the clean real price of a bond security from a dirty real price. * * @param bond * The bond security. * @param cleanNominalPrice * The clean nominal price. * @param issuerMulticurves * The issuer and multi-curves provider. * @return The clean price. */ public double cleanRealPriceFromCleanNominalPrice(final BondCapitalIndexedSecurity<?> bond, final double cleanNominalPrice, final InflationIssuerProviderInterface issuerMulticurves) { final double indexRatio = bond.getIndexRatio(); return cleanNominalPrice / indexRatio; } /** * Compute the dirty price of a bond security from curves. * * @param bond * The bond security. * @param issuerMulticurves * The issuer and multi-curves provider. * @return The dirty price. */ public double dirtyNominalPriceFromCurves(final BondCapitalIndexedSecurity<?> bond, final InflationIssuerProviderInterface issuerMulticurves) { ArgumentChecker.notNull(bond, "Bond"); ArgumentChecker.notNull(issuerMulticurves, "Issuer and multi-curves provider"); final MultipleCurrencyAmount pv = presentValue(bond, issuerMulticurves); final double df = issuerMulticurves.getMulticurveProvider().getDiscountFactor(bond.getCurrency(), bond.getSettlementTime()); final double notional = bond.getCoupon().getNthPayment(0).getNotional(); return pv.getAmount(bond.getCurrency()) / df / notional; } /** * Compute the dirty price of a bond security from curves. * * @param bond * The bond security. * @param issuerMulticurves * The issuer and multi-curves provider. * @return The dirty price. */ public double dirtyRealPriceFromCurves(final BondCapitalIndexedSecurity<?> bond, final InflationIssuerProviderInterface issuerMulticurves) { ArgumentChecker.notNull(bond, "Bond"); ArgumentChecker.notNull(issuerMulticurves, "Issuer and multi-curves provider"); final MultipleCurrencyAmount pv = presentValue(bond, issuerMulticurves); final double settlement = bond.getIndexRatio(); final double notional = bond.getCoupon().getNthPayment(0).getNotional(); return pv.getAmount(bond.getCurrency()) / settlement / notional; } /** * Computes the dirty real price of a bond security from the clean real price. * * @param bond * The bond security. * @param cleanPrice * The clean price. * @return The clean price. */ public double dirtyRealPriceFromCleanRealPrice(final BondCapitalIndexedSecurity<?> bond, final double cleanPrice) { final double notional = bond.getCoupon().getNthPayment(0).getNotional(); return cleanPrice + bond.getAccruedInterest() / notional; } /** * The net amount paid at settlement date for a given clean real price. * * @param bond * The bond. * @param market * The market. * @param cleanPriceReal * The clean real price. * @return The net amount. */ public MultipleCurrencyAmount netAmount(final BondCapitalIndexedSecurity<Coupon> bond, final InflationIssuerProviderInterface market, final double cleanPriceReal) { final double notional = bond.getCoupon().getNthPayment(0).getNotional(); final double netAmountRealByUnit = cleanPriceReal + bond.getAccruedInterest() / notional; final MultipleCurrencyAmount netAmount = bond.getSettlement().accept(NAIC, market.getInflationProvider()); return netAmount.multipliedBy(netAmountRealByUnit); } /** * Computes the dirty (real or nominal depending of the convention) price from the conventional real yield. * * @param bond * The bond security. * @param yield * The bond yield. * @return The dirty price. */ public double dirtyPriceFromRealYield(final BondCapitalIndexedSecurity<?> bond, final double yield) { Validate.isTrue(bond.getNominal().getNumberOfPayments() == 1, "Yield: more than one nominal repayment."); final int nbCoupon = bond.getCoupon().getNumberOfPayments(); final YieldConvention yieldConvention = bond.getYieldConvention(); if (yieldConvention.equals(US_IL_REAL)) { // Coupon period rate to next coupon and simple rate from next coupon to settlement. double pvAtFirstCoupon; if (Math.abs(yield) > 1.0E-8) { final double factorOnPeriod = 1 + yield / bond.getCouponPerYear(); final double vn = Math.pow(factorOnPeriod, 1 - nbCoupon); pvAtFirstCoupon = ((CouponInflationGearing) bond.getCoupon().getNthPayment(0)).getFactor() / yield * (factorOnPeriod - vn) + vn; } else { pvAtFirstCoupon = ((CouponInflationGearing) bond.getCoupon().getNthPayment(0)).getFactor() / bond.getCouponPerYear() * nbCoupon + 1; } return pvAtFirstCoupon / (1 + bond.getAccrualFactorToNextCoupon() * yield / bond.getCouponPerYear()); } if (yieldConvention.equals(INDEX_LINKED_FLOAT)) { final double realRate = ((CouponInflationGearing) bond.getCoupon().getNthPayment(1)).getFactor(); final double firstYearFraction = bond.getCoupon().getNthPayment(0).getPaymentYearFraction(); double firstCouponEndFixingTime = 0.0; double firstCouponPayementTime = 0.0; if (bond.getCoupon().getNthPayment(1) instanceof CouponInflationZeroCouponInterpolationGearing) { firstCouponEndFixingTime = ((CouponInflationZeroCouponInterpolationGearing) bond.getCoupon().getNthPayment(1)).getReferenceEndTime()[1]; firstCouponPayementTime = ((CouponInflationZeroCouponInterpolationGearing) bond.getCoupon().getNthPayment(1)).getPaymentTime(); } else if (bond.getCoupon().getNthPayment(1) instanceof CouponInflationZeroCouponMonthlyGearing) { firstCouponEndFixingTime = ((CouponInflationZeroCouponMonthlyGearing) bond.getCoupon().getNthPayment(1)).getReferenceEndTime(); firstCouponPayementTime = ((CouponInflationZeroCouponMonthlyGearing) bond.getCoupon().getNthPayment(1)).getPaymentTime(); } final double lag = firstCouponPayementTime - firstCouponEndFixingTime; final double v = 1 / (1 + yield / bond.getCouponPerYear()); final double rpibase = bond.getIndexStartValue(); final double rpiLast = bond.getLastIndexKnownFixing(); final double indexRatio = rpiLast / rpibase; final int nbMonth = (int) Math.max(Math.round((bond.getLastKnownFixingTime() - bond.getCoupon().getNthPayment(0).getPaymentTime() + lag) * 12), 0.0); final double u = Math.pow(1 / (1 + .03), .5); final double a = indexRatio * Math.pow(u, 2.0 * nbMonth / 12.0); final double firstCashFlow = firstYearFraction * realRate * indexRatio; if (bond.getCoupon().getNumberOfPayments() == 1) { return Math.pow(u * v, bond.getAccrualFactorToNextCoupon()) * (firstCashFlow + 1) * a / u; } final double secondYearFraction = bond.getCoupon().getNthPayment(1).getPaymentYearFraction(); final double secondCashFlow = secondYearFraction * realRate * indexRatio; final double vn = Math.pow(v, nbCoupon - 1); final double pvAtFirstCoupon = firstCashFlow + secondCashFlow * u * v + a * realRate * v * v * (1 - vn / v) / (1 - v) + a * vn; return pvAtFirstCoupon * Math.pow(u * v, bond.getRatioPeriodToNextCoupon()); } if (yieldConvention.equals(UK_IL_BOND)) { final double firstYearFraction = bond.getCoupon().getNthPayment(0).getPaymentYearFraction(); final double realRate = ((CouponInflationGearing) bond.getCoupon().getNthPayment(1)).getFactor(); // Real rate adjusted by the number of coupons, i.e. annual rate / 2 for UK bonds final double firstCashFlow = firstYearFraction * realRate; final double v = 1 / (1 + yield / bond.getCouponPerYear()); if (bond.getCoupon().getNumberOfPayments() == 1) { return Math.pow(v, bond.getAccrualFactorToNextCoupon()) * (firstCashFlow + 1); } final double secondYearFraction = bond.getCoupon().getNthPayment(1).getPaymentYearFraction(); final double secondCashFlow = secondYearFraction * realRate; final double vn = Math.pow(v, nbCoupon - 1); final double pvAtFirstCoupon = firstCashFlow + secondCashFlow * v + realRate * v * v * (1 - vn / v) / (1 - v) + vn; return pvAtFirstCoupon * Math.pow(v, bond.getAccrualFactorToNextCoupon()); } throw new UnsupportedOperationException("The convention " + bond.getYieldConvention().getName() + " is not supported."); } /** * Computes the clean price (real or nominal depending on the convention) from the conventional real yield. * * @param bond * The bond security. * @param yield * The bond yield. * @return The clean price. */ public double cleanPriceFromYield(final BondCapitalIndexedSecurity<?> bond, final double yield) { Validate.isTrue(bond.getNominal().getNumberOfPayments() == 1, "Yield: more than one nominal repayment."); final double dirtyPrice = dirtyPriceFromRealYield(bond, yield); if (bond.getYieldConvention().equals(INDEX_LINKED_FLOAT)) { return cleanNominalPriceFromDirtyNominalPrice(bond, dirtyPrice); } return cleanRealPriceFromDirtyRealPrice(bond, dirtyPrice); } /** * Compute the conventional yield from the dirty price. * * @param bond * The bond security. * @param dirtyPrice * The bond dirty price. * @return The yield. */ public double yieldRealFromDirtyRealPrice(final BondCapitalIndexedSecurity<?> bond, final double dirtyPrice) { /** * Inner function used to find the yield. */ final Function1D<Double, Double> priceResidual = new Function1D<Double, Double>() { @Override public Double evaluate(final Double y) { return dirtyPriceFromRealYield(bond, y) - dirtyPrice; } }; final double[] range = BRACKETER.getBracketedPoints(priceResidual, -0.05, 0.10); final double yield = ROOT_FINDER.getRoot(priceResidual, range[0], range[1]); return yield; } /** * Computes the present value sensitivity of a capital indexed bound by index estimation and discounting. The sensitivity is the sensitivity of the nominal * and the coupons but not the settlement. * * @param bond * The bond. * @param provider * The provider. * @return The present value. */ public MultipleCurrencyInflationSensitivity presentValueCurveSensitivity(final BondCapitalIndexedSecurity<?> bond, final InflationIssuerProviderInterface provider) { ArgumentChecker.notNull(bond, "Bond"); final InflationProviderInterface creditDiscounting = new InflationProviderDecoratedIssuer(provider, bond.getCurrency(), bond.getIssuerEntity()); final MultipleCurrencyInflationSensitivity sensitivityNominal = bond.getNominal().accept(PVCSIC, creditDiscounting); final MultipleCurrencyInflationSensitivity sensitivityCoupon = bond.getCoupon().accept(PVCSIC, creditDiscounting); return sensitivityNominal.plus(sensitivityCoupon); } /** * Compute the conventional yield from the clean price. * * @param bond * The bond security. * @param cleanPrice * The bond clean price. * @return The yield. */ public double yieldRealFromCleanPrice(final BondCapitalIndexedSecurity<?> bond, final double cleanPrice) { /** * Inner function used to find the yield. */ final Function1D<Double, Double> priceResidual = new Function1D<Double, Double>() { @Override public Double evaluate(final Double y) { return cleanPriceFromYield(bond, y) - cleanPrice; } }; final double[] range = BRACKETER.getBracketedPoints(priceResidual, -0.05, 0.10); final double yield = ROOT_FINDER.getRoot(priceResidual, range[0], range[1]); return yield; } /** * Calculates the modified duration from a standard yield. * * @param bond * The bond * @param yield * The yield * @return The modified duration */ public double modifiedDurationFromYieldStandard(final BondCapitalIndexedSecurity<?> bond, final double yield) { ArgumentChecker.isTrue(bond.getNominal().getNumberOfPayments() == 1, "Yield: more than one nominal repayment."); final int nbCoupon = bond.getCoupon().getNumberOfPayments(); final double nominal = bond.getNominal().getNthPayment(0).getNotional(); final double factorOnPeriod = 1 + yield / bond.getCouponPerYear(); double mdAtFirstCoupon = 0; double pvAtFirstCoupon = 0; for (int loopcpn = 0; loopcpn < nbCoupon; loopcpn++) { mdAtFirstCoupon += bond.getCoupon().getNthPayment(loopcpn).getNotional() / Math.pow(factorOnPeriod, loopcpn + 1) * (loopcpn + bond.getAccrualFactorToNextCoupon()) / bond.getCouponPerYear(); pvAtFirstCoupon += bond.getCoupon().getNthPayment(loopcpn).getNotional() / Math.pow(factorOnPeriod, loopcpn); } mdAtFirstCoupon += nominal / Math.pow(factorOnPeriod, nbCoupon) * (nbCoupon - 1 + bond.getAccrualFactorToNextCoupon()) / bond.getCouponPerYear(); pvAtFirstCoupon += nominal / Math.pow(factorOnPeriod, nbCoupon - 1); final double pv = pvAtFirstCoupon * Math.pow(factorOnPeriod, -bond.getAccrualFactorToNextCoupon()); final double md = mdAtFirstCoupon * Math.pow(factorOnPeriod, -bond.getAccrualFactorToNextCoupon()) / pv; return md; } /** * Calculates the modified duration from a standard yield. * * @param bond * The bond * @param yield * The yield * @return The modified duration */ public double modifiedDurationFromYieldFiniteDifference(final BondCapitalIndexedSecurity<?> bond, final double yield) { ArgumentChecker.isTrue(bond.getNominal().getNumberOfPayments() == 1, "Yield: more than one nominal repayment."); final double price = cleanPriceFromYield(bond, yield); final double priceplus = cleanPriceFromYield(bond, yield + 10e-6); final double priceminus = cleanPriceFromYield(bond, yield - 10e-6); return -(priceplus - priceminus) / (2 * price * 10e-6); } /** * Calculates the modified duration from a standard yield. * * @param bond * The bond * @param yield * The yield * @return The modified duration */ public double convexityFromYieldFiniteDifference(final BondCapitalIndexedSecurity<?> bond, final double yield) { ArgumentChecker.isTrue(bond.getNominal().getNumberOfPayments() == 1, "Yield: more than one nominal repayment."); ArgumentChecker.isTrue(bond.getNominal().getNumberOfPayments() == 1, "Yield: more than one nominal repayment."); final double price = cleanPriceFromYield(bond, yield); final double priceplus = cleanPriceFromYield(bond, yield + 10e-6); final double priceminus = cleanPriceFromYield(bond, yield - 10e-6); return (priceplus - 2 * price + priceminus) / (price * 10e-6 * 10e-6); } /** * Computes the bill yield from the curves. The yield is in the bill yield convention. * * @param bond * The bond. * @param provider * The inflation and multi-curves provider. * @return The yield. */ public double yieldRealFromCurves(final BondCapitalIndexedSecurity<?> bond, final InflationIssuerProviderInterface provider) { ArgumentChecker.notNull(bond, "Bond"); ArgumentChecker.notNull(provider, "inflation and multi-curves provider"); double dirtyPrice; if (bond.getYieldConvention().equals(INDEX_LINKED_FLOAT)) { dirtyPrice = dirtyNominalPriceFromCurves(bond, provider); } else { dirtyPrice = dirtyRealPriceFromCurves(bond, provider); } final double yield = yieldRealFromDirtyRealPrice(bond, dirtyPrice); return yield; } /** * Computes the modified duration of a bond from the curves. * * @param bond * The bond security. * @param issuerMulticurves * The issuer and multi-curves provider. * @return The modified duration. */ public double modifiedDurationFromCurves(final BondCapitalIndexedSecurity<?> bond, final InflationIssuerProviderInterface issuerMulticurves) { final double yield = yieldRealFromCurves(bond, issuerMulticurves); return modifiedDurationFromYieldFiniteDifference(bond, yield); } /** * Compute the conventional yield from the clean price. * * @param bond * The bond security. * @param cleanPrice * The bond clean price. * @return The yield. */ public double yieldRealFromCleanRealPrice(final BondCapitalIndexedSecurity<?> bond, final double cleanPrice) { final double dirtyPrice = dirtyRealPriceFromCleanRealPrice(bond, cleanPrice); final double yield = yieldRealFromDirtyRealPrice(bond, dirtyPrice); return yield; } /** * Computes the modified duration of a bond from the clean price. * * @param bond * The bond security. * @param cleanPrice * The bond clean price. * @return The modified duration. */ public double modifiedDurationFromCleanPrice(final BondCapitalIndexedSecurity<?> bond, final double cleanPrice) { final double yield = yieldRealFromCleanPrice(bond, cleanPrice); return modifiedDurationFromYieldFiniteDifference(bond, yield); } /** * Calculates the convexity from a standard yield. * * @param bond * The bond * @param yield * The yield * @return The convexity */ public double convexityFromYieldStandard(final BondCapitalIndexedSecurity<?> bond, final double yield) { ArgumentChecker.isTrue(bond.getNominal().getNumberOfPayments() == 1, "Yield: more than one nominal repayment."); final int nbCoupon = bond.getCoupon().getNumberOfPayments(); final double nominal = bond.getNominal().getNthPayment(bond.getNominal().getNumberOfPayments() - 1).getNotional(); final double factorOnPeriod = 1 + yield / bond.getCouponPerYear(); double cvAtFirstCoupon = 0; double pvAtFirstCoupon = 0; for (int loopcpn = 0; loopcpn < nbCoupon; loopcpn++) { cvAtFirstCoupon += bond.getCoupon().getNthPayment(loopcpn).getNotional() / Math.pow(factorOnPeriod, loopcpn + 2) * (loopcpn + bond.getAccrualFactorToNextCoupon()) * (loopcpn + bond.getAccrualFactorToNextCoupon() + 1) / (bond.getCouponPerYear() * bond.getCouponPerYear()); pvAtFirstCoupon += bond.getCoupon().getNthPayment(loopcpn).getNotional() / Math.pow(factorOnPeriod, loopcpn); } cvAtFirstCoupon += nominal / Math.pow(factorOnPeriod, nbCoupon + 1) * (nbCoupon - 1 + bond.getAccrualFactorToNextCoupon()) * (nbCoupon + bond.getAccrualFactorToNextCoupon()) / (bond.getCouponPerYear() * bond.getCouponPerYear()); pvAtFirstCoupon += nominal / Math.pow(factorOnPeriod, nbCoupon - 1); final double pv = pvAtFirstCoupon * Math.pow(factorOnPeriod, -bond.getAccrualFactorToNextCoupon()); final double cv = cvAtFirstCoupon * Math.pow(factorOnPeriod, -bond.getAccrualFactorToNextCoupon()) / pv; return cv; } /** * Computes the convexity of a bond from the curves. * * @param bond * The bond security. * @param issuerMulticurves * The issuer and multi-curves provider. * @return The convexity. */ public double convexityFromCurves(final BondCapitalIndexedSecurity<?> bond, final InflationIssuerProviderInterface issuerMulticurves) { final double yield = yieldRealFromCurves(bond, issuerMulticurves); return convexityFromYieldFiniteDifference(bond, yield); } /** * Computes the convexity of a bond from the clean price. * * @param bond * The bond security. * @param cleanPrice * The bond clean price. * @return The convexity. */ public double convexityFromCleanPrice(final BondCapitalIndexedSecurity<?> bond, final double cleanPrice) { final double yield = yieldRealFromCleanPrice(bond, cleanPrice); return convexityFromYieldFiniteDifference(bond, yield); } /** * Computes the present value of a bond security from z-spread. The z-spread is a parallel shift applied to the discounting curve associated to the bond * (Issuer Entity). The parallel shift is done in the curve convention. * * @param bond * The bond security. * @param issuerMulticurves * The issuer and multi-curves provider. * @param zSpread * The z-spread. * @return The present value. */ public MultipleCurrencyAmount presentValueFromZSpread(final BondCapitalIndexedSecurity<?> bond, final InflationIssuerProviderInterface issuerMulticurves, final double zSpread) { final InflationIssuerProviderIssuerDecoratedSpread issuerShifted = new InflationIssuerProviderIssuerDecoratedSpread(issuerMulticurves, bond.getIssuerEntity(), zSpread); return presentValue(bond, issuerShifted); } /** * Computes the present value of a bond security from z-spread. The z-spread is a parallel shift applied to the discounting curve associated to the bond * (Issuer Entity). The parallel shift is done in the curve convention. * * @param bond * The bond security. * @param issuerMulticurves * The issuer and multi-curves provider. * @param zSpread * The z-spread. * @return The present value. */ public double cleanPriceFromZSpread(final BondCapitalIndexedSecurity<?> bond, final InflationIssuerProviderInterface issuerMulticurves, final double zSpread) { final InflationIssuerProviderIssuerDecoratedSpread issuerShifted = new InflationIssuerProviderIssuerDecoratedSpread(issuerMulticurves, bond.getIssuerEntity(), zSpread); return cleanRealPriceFromCurves(bond, issuerShifted); } /** * Computes a bond z-spread from the curves and a present value. The z-spread is a parallel shift applied to the discounting curve associated to the bond * (Issuer Entity) to match the present value. * * @param bond * The bond. * @param issuerMulticurves * The issuer and multi-curves provider. * @param cleanPrice * The target clean price. * @return The z-spread. */ // TODO : this function have been created specially to match the clean price as it come from bloomberg (ie without specification if it is real or nominal), // maybe remove at one point. public double zSpreadFromCurvesAndCleanPriceDirect(final BondCapitalIndexedSecurity<?> bond, final InflationIssuerProviderInterface issuerMulticurves, final double cleanPrice) { ArgumentChecker.notNull(bond, "Bond"); ArgumentChecker.notNull(issuerMulticurves, "Issuer and multi-curves provider"); final Function1D<Double, Double> residual = new Function1D<Double, Double>() { @Override public Double evaluate(final Double z) { final InflationIssuerProviderIssuerDecoratedSpread issuerShifted = new InflationIssuerProviderIssuerDecoratedSpread(issuerMulticurves, bond.getIssuerEntity(), z); if (bond.getYieldConvention().equals(INDEX_LINKED_FLOAT)) { return cleanNominalPriceFromCurves(bond, issuerShifted) - cleanPrice; } return cleanRealPriceFromCurves(bond, issuerShifted) - cleanPrice; } }; final double[] range = BRACKETER.getBracketedPoints(residual, -0.5, 0.5); // Starting range is [-1%, 1%] return ROOT_FINDER.getRoot(residual, range[0], range[1]); } /** * Computes a bond z-spread from the curves and a present value. The z-spread is a parallel shift applied to the discounting curve associated to the bond * (Issuer Entity) to match the present value. * * @param bond * The bond. * @param issuerMulticurves * The issuer and multi-curves provider. * @param cleanRealPrice * The target clean real price. * @return The z-spread. */ public double zSpreadFromCurvesAndCleanRealPriceDirect(final BondCapitalIndexedSecurity<?> bond, final InflationIssuerProviderInterface issuerMulticurves, final double cleanRealPrice) { return zSpreadFromCurvesAndPV(bond, issuerMulticurves, presentValueFromCleanRealPrice(bond, issuerMulticurves, cleanRealPrice)); } /** * Computes a bond z-spread from the curves and a present value. The z-spread is a parallel shift applied to the discounting curve associated to the bond * (Issuer Entity) to match the present value. * * @param bond * The bond. * @param issuerMulticurves * The issuer and multi-curves provider. * @param cleanRealPrice * The target clean real price. * @return The z-spread. */ public double zSpreadFromCurvesAndCleanNominalPriceDirect(final BondCapitalIndexedSecurity<?> bond, final InflationIssuerProviderInterface issuerMulticurves, final double cleanRealPrice) { return zSpreadFromCurvesAndPV(bond, issuerMulticurves, presentValueFromCleanNominalPrice(bond, issuerMulticurves, cleanRealPrice)); } /** * Computes a bond z-spread from the curves and a present value. The z-spread is a parallel shift applied to the discounting curve associated to the bond * (Issuer Entity) to match the present value. * * @param bond * The bond. * @param issuerMulticurves * The issuer and multi-curves provider. * @param pv * The target present value. * @return The z-spread. */ public double zSpreadFromCurvesAndPV(final BondCapitalIndexedSecurity<?> bond, final InflationIssuerProviderInterface issuerMulticurves, final MultipleCurrencyAmount pv) { ArgumentChecker.notNull(bond, "Bond"); ArgumentChecker.notNull(issuerMulticurves, "Issuer and multi-curves provider"); final Currency ccy = bond.getCurrency(); final Function1D<Double, Double> residual = new Function1D<Double, Double>() { @Override public Double evaluate(final Double z) { return presentValueFromZSpread(bond, issuerMulticurves, z).getAmount(ccy) - pv.getAmount(ccy); } }; final double[] range = BRACKETER.getBracketedPoints(residual, -0.5, 0.5); // Starting range is [-1%, 1%] return ROOT_FINDER.getRoot(residual, range[0], range[1]); } /** * Computes a bond z-spread from the curves and a clean price. The z-spread is a parallel shift applied to the discounting curve associated to the bond * (Issuer Entity) to match the CleanPrice present value. * * @param bond * The bond. * @param issuerMulticurves * The issuer and multi-curves provider. * @param cleanPrice * The target clean price. * @return The z-spread. */ public double zSpreadFromCurvesAndCleanPrice(final BondCapitalIndexedSecurity<Coupon> bond, final InflationIssuerProviderInterface issuerMulticurves, final double cleanPrice) { return zSpreadFromCurvesAndPV(bond, issuerMulticurves, presentValueFromCleanRealPrice(bond, issuerMulticurves, cleanPrice)); } }
{'content_hash': 'bf41cecbb9b17767ce1c32de08ed3c2e', 'timestamp': '', 'source': 'github', 'line_count': 803, 'max_line_length': 159, 'avg_line_length': 46.39975093399751, 'alnum_prop': 0.7211680399366596, 'repo_name': 'McLeodMoores/starling', 'id': '75c2be71172ed67d5e22d850113a1b455ad8ea62', 'size': '37396', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'projects/analytics/src/main/java/com/opengamma/analytics/financial/interestrate/bond/provider/BondCapitalIndexedSecurityDiscountingMethod.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '2505'}, {'name': 'CSS', 'bytes': '213501'}, {'name': 'FreeMarker', 'bytes': '310184'}, {'name': 'GAP', 'bytes': '1490'}, {'name': 'Groovy', 'bytes': '11518'}, {'name': 'HTML', 'bytes': '318295'}, {'name': 'Java', 'bytes': '79541905'}, {'name': 'JavaScript', 'bytes': '1511230'}, {'name': 'PLSQL', 'bytes': '398'}, {'name': 'PLpgSQL', 'bytes': '26901'}, {'name': 'Shell', 'bytes': '11481'}, {'name': 'TSQL', 'bytes': '604117'}]}
using System.Windows.Controls; namespace EveMarket.Views { /// <summary> /// Interaction logic for ItemInfoView.xaml /// </summary> public partial class ItemInfoView : UserControl { public ItemInfoView() { InitializeComponent(); } } }
{'content_hash': '7ba1f05fd37f11bdb5e380117173db13', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 51, 'avg_line_length': 19.733333333333334, 'alnum_prop': 0.5945945945945946, 'repo_name': 'Capgemini/Cauldron', 'id': 'a53b3cb45e415caef3f0f5bc85b72982a46f8614', 'size': '298', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'Old/Desktop/Samples/EveMarket.Views/ItemInfoView.xaml.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '603'}, {'name': 'C#', 'bytes': '6246714'}, {'name': 'PowerShell', 'bytes': '8223'}]}
/** * */ package com.aspose.cloud.sdk.slides.api; import android.net.Uri; import com.aspose.cloud.sdk.common.AsposeApp; import com.aspose.cloud.sdk.common.Utils; import com.aspose.cloud.sdk.slides.model.MergePresentationsRequest; import com.aspose.cloud.sdk.slides.model.MergeSelectedSlidesOfPowerPointPresentationsRequest; import com.aspose.cloud.sdk.slides.model.SplitPowerPointPresentationsResponse; import com.aspose.cloud.sdk.slides.model.SplitPowerPointPresentationsResponse.SplitResult; import com.aspose.cloud.sdk.slides.model.ValidSlidesFormats; import com.aspose.cloud.sdk.slides.model.DocumentResponse; import com.aspose.cloud.sdk.slides.model.DocumentResponse.DocumentModel; import com.aspose.cloud.sdk.slides.model.ValidFormatsEnum; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.HashMap; /** * Document --- Using this class you can create a new empty PowerPoint presentation, convert PowerPoint document to other File formats, * merge multiple PowerPoint presentation files and split all or specific slides of a presentation file * @author M. Sohail Ismail */ public class Document { private static final String SLIDES_URI = AsposeApp.BASE_PRODUCT_URI + "/slides/"; public static final String TEXTCOMPRESSION_KEY = "TextCompression"; public static final String EMBEDFULLFONTS_KEY = "EmbedFullFonts"; public static final String COMPLIANCE_KEY = "Compliance"; public static final String JPEGQUALITY_KEY = "JpegQuality"; public static final String SAVEMETAFILESASPNG_KEY = "SaveMetafilesAsPng"; public static final String PDFPASSWORD_KEY = "PdfPassword"; public static final String EMBEDTRUETYPEFONTSFORASCII_KEY = "EmbedTrueTypeFontsForASCII"; /** * Create a new empty PowerPoint presentation * @param fileName Name of the file stored on cloud * @throws java.security.InvalidKeyException If initialization fails because the provided key is null. * @throws java.security.NoSuchAlgorithmException If the specified algorithm (HmacSHA1) is not available by any provider. * @throws java.io.IOException If there is an IO error * @return An object that contains URLs to document properties, slides and images and alternative links to download document in other formats */ public static DocumentModel createEmptyPowerPointPresentation(String fileName) throws InvalidKeyException, NoSuchAlgorithmException, IOException { DocumentModel document = null; if(fileName == null || fileName.length() == 0) { throw new IllegalArgumentException("File name cannot be null or empty"); } //build URL String strURL = SLIDES_URI + Uri.encode(fileName); //sign URL String signedURL = Utils.sign(strURL); InputStream responseStream = Utils.processCommand(signedURL, "PUT"); String jsonStr = Utils.streamToString(responseStream); //Parsing JSON Gson gson = new Gson(); DocumentResponse documentResponse = gson.fromJson(jsonStr, DocumentResponse.class); if(documentResponse.getCode().equals("201") && documentResponse.getStatus().equals("Created")) { document = documentResponse.document; } return document; } /** * Convert PowerPoint document to other File formats * @param fileName Name of the file stored on cloud * @param designatedFormat Valid formats are tiff, pdf, xps, odp, ppsx, pptm, ppsm, potx, potm and html * @param storageName If file is stored at third party storage e.g. Amazon S3, Azure, Dropbox, Google Drive or FTP * @param folderName Path to file if file is not stored at root * @throws java.security.InvalidKeyException If initialization fails because the provided key is null. * @throws java.security.NoSuchAlgorithmException If the specified algorithm (HmacSHA1) is not available by any provider. * @throws java.io.IOException If there is an IO error * @return A path to converted document */ public static String convertPowerPointDocumentToOtherFileFormats(String fileName, ValidFormatsEnum designatedFormat, String storageName, String folderName) throws InvalidKeyException, NoSuchAlgorithmException, IOException { String localFilePath = null; if(fileName == null || fileName.length() == 0) { throw new IllegalArgumentException("File name cannot be null or empty"); } if(designatedFormat == null) { throw new IllegalArgumentException("Designated format cannot be null"); } //build URL StringBuilder strURL = new StringBuilder(SLIDES_URI + Uri.encode(fileName) + "?format=" + designatedFormat); //If document is on the third party storage if(storageName != null && storageName.length() != 0) { strURL.append("&storage=" + storageName); } //In case if file is not at root folder if(folderName != null && folderName.length() != 0) { strURL.append("&folder=" + folderName); } //sign URL String signedURL = Utils.sign(strURL.toString()); InputStream responseStream = Utils.processCommand(signedURL, "GET"); //Replace fileName extension with designated format String[] fileNameAndItsExtensionArray = fileName.split("\\."); fileName = fileNameAndItsExtensionArray[0] + "." + designatedFormat; //Save file on Disk localFilePath = Utils.saveStreamToFile(responseStream, fileName); return localFilePath; } /** * Convert PowerPoint document to other file formats with additional settings * @param fileName Name of the file stored on cloud * @param designatedFormat Valid formats are tiff, pdf, xps, odp, ppsx, pptm, ppsm, potx, potm and html * @param exportOptions Depends of parameter "format" service can receive export options * @throws java.security.InvalidKeyException If initialization fails because the provided key is null. * @throws java.security.NoSuchAlgorithmException If the specified algorithm (HmacSHA1) is not available by any provider. * @throws java.io.IOException If there is an IO error * @return A path to converted document */ public static String convertPowerPointDocumentToOtherFileFormatsWithAdditionalSettings(String fileName, ValidFormatsEnum designatedFormat, HashMap<String, String> exportOptions) throws InvalidKeyException, NoSuchAlgorithmException, IOException { String localFilePath = null; if(fileName == null || fileName.length() <= 3) { throw new IllegalArgumentException("File name cannot be null or empty"); } if(designatedFormat == null) { throw new IllegalArgumentException("Designated format cannot be null"); } //build URL StringBuilder strURL = new StringBuilder(SLIDES_URI + Uri.encode(fileName) + "?format=" + designatedFormat); if(exportOptions.get(TEXTCOMPRESSION_KEY) != null) { strURL.append("&TextCompression=" + exportOptions.get(TEXTCOMPRESSION_KEY)); } if(exportOptions.get(EMBEDFULLFONTS_KEY) != null) { strURL.append("&EmbedFullFonts=" + exportOptions.get(EMBEDFULLFONTS_KEY)); } if(exportOptions.get(COMPLIANCE_KEY) != null) { strURL.append("&Compliance=" + exportOptions.get(COMPLIANCE_KEY)); } if(exportOptions.get(JPEGQUALITY_KEY) != null) { strURL.append("&JpegQuality=" + exportOptions.get(JPEGQUALITY_KEY)); } if(exportOptions.get(SAVEMETAFILESASPNG_KEY) != null) { strURL.append("&SaveMetafilesAsPng=" + exportOptions.get(SAVEMETAFILESASPNG_KEY)); } if(exportOptions.get(PDFPASSWORD_KEY) != null) { strURL.append("&PdfPassword=" + exportOptions.get(PDFPASSWORD_KEY)); } if(exportOptions.get(EMBEDTRUETYPEFONTSFORASCII_KEY) != null) { strURL.append("&EmbedTrueTypeFontsForASCII=" + exportOptions.get(EMBEDTRUETYPEFONTSFORASCII_KEY)); } //sign URL String signedURL = Utils.sign(strURL.toString()); InputStream responseStream = Utils.processCommand(signedURL, "GET"); //Replace fileName extension with designated format String[] fileNameAndItsExtensionArray = fileName.split("\\."); fileName = fileNameAndItsExtensionArray[0] + "." + designatedFormat; //Save file on Disk localFilePath = Utils.saveStreamToFile(responseStream, fileName); return localFilePath; } /** * Convert PowerPoint document stored on device to other file formats * @param localFilePath Name of the file stored on device * @param designatedFormat Valid formats are tiff, pdf, xps, odp, ppsx, pptm, ppsm, potx, potm and html * @throws java.security.InvalidKeyException If initialization fails because the provided key is null. * @throws java.security.NoSuchAlgorithmException If the specified algorithm (HmacSHA1) is not available by any provider. * @throws java.io.IOException If there is an IO error * @return A path to converted document */ public static String convertLocallyStoredPowerPointDocumentToOtherFileFormats(String localFilePath, ValidFormatsEnum designatedFormat) throws InvalidKeyException, NoSuchAlgorithmException, IOException { String updatedFilePath = null; if(localFilePath == null || localFilePath.length() == 0) { throw new IllegalArgumentException("Local file path cannot be null or empty"); } if(designatedFormat == null) { throw new IllegalArgumentException("Designated format cannot be null"); } //Build URI String strURL = SLIDES_URI + "convert?format=" + designatedFormat; //Sign the request URI String signedURL = Utils.sign(strURL); //Convert the local file to InputStream InputStream fileStream = new FileInputStream(localFilePath); //Process the request on server InputStream responseStream = Utils.processCommand(signedURL, "POST", fileStream); //Get fileName from localFilePath String fileName; int index = localFilePath.lastIndexOf("/"); if(index != -1) { fileName = localFilePath.substring(index+1); } else { fileName = localFilePath; } //Replace fileName extension with designated format String[] fileNameAndItsExtensionArray = fileName.split("\\."); fileName = fileNameAndItsExtensionArray[0] + "." + designatedFormat; //Save the stream in response to the disk updatedFilePath = Utils.saveStreamToFile(responseStream, fileName); return updatedFilePath; } /** * You can merge multiple PowerPoint presentation files * @param fileName Name of the file stored on cloud * @param mergePresentationsRequest Contains an array of PowerPoint presentations to be merged with * @throws java.security.InvalidKeyException If initialization fails because the provided key is null. * @throws java.security.NoSuchAlgorithmException If the specified algorithm (HmacSHA1) is not available by any provider. * @throws java.io.IOException If there is an IO error * @return An object that contains URLs to document properties, slides and images and alternative links to download document in other formats */ public static DocumentModel mergePowerPointPresentations(String fileName, MergePresentationsRequest mergePresentationsRequest) throws InvalidKeyException, NoSuchAlgorithmException, IOException { DocumentModel document = null; if(fileName == null || fileName.length() == 0) { throw new IllegalArgumentException("File name cannot be null or empty"); } if(mergePresentationsRequest == null) { throw new IllegalArgumentException("Merge presentations request cannot be null"); } GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); String requestJSONString = gson.toJson(mergePresentationsRequest, MergePresentationsRequest.class); //Build URI String strURL = SLIDES_URI + Uri.encode(fileName) + "/merge"; //Sign the request URI String signedURL = Utils.sign(strURL); InputStream responseStream = Utils.processCommand(signedURL, "POST", requestJSONString); String responseJSONString = Utils.streamToString(responseStream); //Parsing JSON DocumentResponse documentResponse = gson.fromJson(responseJSONString, DocumentResponse.class); if(documentResponse.getCode().equals("200") && documentResponse.getStatus().equals("OK")) { document = documentResponse.document; } return document; } /** * Take selected slides from multiple presentation files and merge into another presentation * @param fileName Name of the file stored on cloud * @param mergePresentationsRequest Contains an array of PowerPoint presentations to be merged with * @throws java.security.InvalidKeyException If initialization fails because the provided key is null. * @throws java.security.NoSuchAlgorithmException If the specified algorithm (HmacSHA1) is not available by any provider. * @throws java.io.IOException If there is an IO error * @return An object that contains URLs to document properties, slides and images and alternative links to download document in other formats */ public static DocumentModel mergeSelectedSlidesOfPowerPointPresentations(String fileName, MergeSelectedSlidesOfPowerPointPresentationsRequest mergePresentationsRequest) throws InvalidKeyException, NoSuchAlgorithmException, IOException { DocumentModel document = null; if(fileName == null || fileName.length() == 0) { throw new IllegalArgumentException("File name cannot be null or empty"); } if(mergePresentationsRequest == null) { throw new IllegalArgumentException("Merge presentations request cannot be null"); } GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); String requestJSONString = gson.toJson(mergePresentationsRequest, MergeSelectedSlidesOfPowerPointPresentationsRequest.class); //Build URI String strURL = SLIDES_URI + Uri.encode(fileName) + "/merge"; //Sign the request URI String signedURL = Utils.sign(strURL); InputStream responseStream = Utils.processCommand(signedURL, "PUT", requestJSONString); String responseJSONString = Utils.streamToString(responseStream); //Parsing JSON DocumentResponse documentResponse = gson.fromJson(responseJSONString, DocumentResponse.class); if(documentResponse.getCode().equals("200") && documentResponse.getStatus().equals("OK")) { document = documentResponse.document; } return document; } /** * Split all slides of a presentation file and save each slide as a new HTML or any supported image format * @param fileName Name of the file stored on cloud * @throws java.security.InvalidKeyException If initialization fails because the provided key is null. * @throws java.security.NoSuchAlgorithmException If the specified algorithm (HmacSHA1) is not available by any provider. * @throws java.io.IOException If there is an IO error * @return An object that contains URLs to slides */ public static SplitResult splitPowerPointPresentations(String fileName) throws InvalidKeyException, NoSuchAlgorithmException, IOException { SplitResult splitResult = null; if(fileName == null || fileName.length() <= 3) { throw new IllegalArgumentException("File name cannot be null or empty"); } //build URL String strURL = SLIDES_URI + Uri.encode(fileName) + "/split"; //sign URL String signedURL = Utils.sign(strURL); InputStream responseStream = Utils.processCommand(signedURL, "POST"); String responseJSONString = Utils.streamToString(responseStream); //Parsing JSON Gson gson = new Gson(); SplitPowerPointPresentationsResponse splitPowerPointPresentationResponse = gson.fromJson(responseJSONString, SplitPowerPointPresentationsResponse.class); if(splitPowerPointPresentationResponse.getCode().equals("200") && splitPowerPointPresentationResponse.getStatus().equals("OK")) { splitResult = splitPowerPointPresentationResponse.splitResult; } return splitResult; } /** * Split specific slides of a presentation file and save each slide as a new HTML or any supported image format * @param fileName Name of the file stored on cloud * @param from The start slide number for splitting * @param to The last slide number for splitting * @param designatedFormat Valid formats are tiff, jpeg, png, bmp and gif * @throws java.security.InvalidKeyException If initialization fails because the provided key is null. * @throws java.security.NoSuchAlgorithmException If the specified algorithm (HmacSHA1) is not available by any provider. * @throws java.io.IOException If there is an IO error * @return An object that contains URLs to slides */ public static SplitResult splitPowerPointPresentations(String fileName, int from, int to, ValidSlidesFormats designatedFormat) throws InvalidKeyException, NoSuchAlgorithmException, IOException { SplitResult splitResult = null; if(fileName == null || fileName.length() <= 3) { throw new IllegalArgumentException("File name cannot be null or empty"); } if(designatedFormat == null) { throw new IllegalArgumentException("Designated format cannot be null"); } //build URL String strURL = SLIDES_URI + Uri.encode(fileName) + "/split?from=" + from + "&to=" + to + "&format=" + designatedFormat; //sign URL String signedURL = Utils.sign(strURL); InputStream responseStream = Utils.processCommand(signedURL, "POST"); String responseJSONString = Utils.streamToString(responseStream); //Parsing JSON Gson gson = new Gson(); SplitPowerPointPresentationsResponse splitPowerPointPresentationResponse = gson.fromJson(responseJSONString, SplitPowerPointPresentationsResponse.class); if(splitPowerPointPresentationResponse.getCode().equals("200") && splitPowerPointPresentationResponse.getStatus().equals("OK")) { splitResult = splitPowerPointPresentationResponse.splitResult; } return splitResult; } }
{'content_hash': '4e9a9c40037494141cc182d3d22182b4', 'timestamp': '', 'source': 'github', 'line_count': 389, 'max_line_length': 246, 'avg_line_length': 45.52956298200514, 'alnum_prop': 0.7584551973349896, 'repo_name': 'asposeforcloud/Aspose_Cloud_SDK_For_Android', 'id': '910d43031fde05302ba3e225638fc69affb2ed36', 'size': '17711', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'asposecloudsdk/src/main/java/com/aspose/cloud/sdk/slides/api/Document.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '1039150'}]}
import React from 'react' import ReactDOM from 'react-dom' import {Provider} from 'react-redux' import store from './store' import AppContainer from './components/containers/AppContainer' import './css/index.css' ReactDOM.render( <Provider store={store} > <AppContainer /> </Provider>, document.getElementById('root') );
{'content_hash': 'a1e7a363296d902730d59fc1d1902d6a', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 63, 'avg_line_length': 26.46153846153846, 'alnum_prop': 0.7063953488372093, 'repo_name': 'TheHappyKoala/Gravity-Playground', 'id': '0b57d94f377e15bf5a05bd5c9b2d64d07cd55ca0', 'size': '344', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/index.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '4821'}, {'name': 'HTML', 'bytes': '1018'}, {'name': 'JavaScript', 'bytes': '73640'}]}
package org.jeo.feature; import java.util.List; import java.util.Map; import org.osgeo.proj4j.CoordinateReferenceSystem; import com.vividsolutions.jts.geom.Geometry; /** * An object consisting of a set of named attributes, any of which may be a vector geometry. * * @see ListFeature * @see MapFeature * * @author Justin Deoliveira, OpenGeo */ public interface Feature { /** * Feature identifier. */ String getId(); /** * Coordinate reference system for the feature. * <p> * Generally the method {@link #crs()} should be used. * </p> * @return The crs, or <code>null</code> if none been set. */ CoordinateReferenceSystem getCRS(); /** * Sets the coordinate reference system for the feature. */ void setCRS(CoordinateReferenceSystem crs); /** * The derived coordinate reference system for the feature. * <p> * If {@link #getCRS()} returns a value it is returned, otherwise if the feature has a * schema object then {@link Schema#crs()} is returned. Otherwise this method returns * <code>null</code>. * </p> * @return The derived crs. */ CoordinateReferenceSystem crs(); /** * Gets a named attribute of the feature. * <p> * This method should return <code>null</code> if no such attribute named <tt>key</tt> exists. * </p> * @param key The key or name of the attribute. * * @return The attribute value or <code>null</code>. */ Object get(String key); /** * Geometry of the feature. * * @return a {@link Geometry} object, or <code>null</code> if the feature has no geometry. */ Geometry geometry(); /** * Sets a named attribute of the feature. * * @param key The key or name of the attribute. * @param val The new value of the attribute. */ void put(String key, Object val); /** * Sets the geometry of the feature. */ void put(Geometry g); /** * The created schema for the feature. */ Schema schema(); /** * Returns an immutable list view of the feature */ abstract List<Object> list(); /** * Returns an immutable map view of the feature. */ abstract Map<String,Object> map(); }
{'content_hash': '25b85ea7cf0616e0c9a13c9dc7e429af', 'timestamp': '', 'source': 'github', 'line_count': 95, 'max_line_length': 98, 'avg_line_length': 24.305263157894736, 'alnum_prop': 0.6071892594196622, 'repo_name': 'geosolutions-it/jeo', 'id': '74c496f62ee7efccdc5715f2f38fcd9106a3008b', 'size': '2309', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'core/src/main/java/org/jeo/feature/Feature.java', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
package org.hl7.hibernate; import java.lang.reflect.Method; import java.util.List; import org.hl7.types.BAG; import org.hl7.types.impl.BAGjuListAdapter; import org.hl7.types.impl.BAGnull; /** * Access a BAG property and wrap/unwrap the underlying bag. * * @author Gunther Schadow */ public class WrappingBagAccessor extends StrategicPropertyAccessor { private static class BAGWrapper implements StrategicPropertyAccessor.FieldWrappingStrategy { public Object bean2DBValue(Object beanValue) { if (beanValue == null) { return null; } else if (beanValue instanceof BAG) { final BAG bagValue = (BAG) beanValue; if (bagValue.isNull().isTrue()) { return null; } else if (bagValue instanceof BAGjuListAdapter) { return ((BAGjuListAdapter) bagValue)._hibernateUnwrap(); } } throw new RuntimeException("class not supported here: " + beanValue.getClass()); } public Object db2BeanValue(Object dbValue) { return dbValue == null ? BAGnull.NI : BAGjuListAdapter._hibernateWrap((List) dbValue); } } @Override public StrategicPropertyAccessor.FieldWrappingStrategy getWrappingStrategy() { return new BAGWrapper(); } }
{'content_hash': '9518e9df3676f438cab9914e3904dada', 'timestamp': '', 'source': 'github', 'line_count': 45, 'max_line_length': 92, 'avg_line_length': 26.666666666666668, 'alnum_prop': 0.7208333333333333, 'repo_name': 'markusgumbel/dshl7', 'id': 'd61c50bee9ffa8a9167a68a55c859b9be95ddbd7', 'size': '1942', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'hl7-javasig/src/org/hl7/hibernate/WrappingBagAccessor.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Groovy', 'bytes': '25055'}, {'name': 'Java', 'bytes': '3897443'}, {'name': 'Perl', 'bytes': '9821'}, {'name': 'Python', 'bytes': '3285'}, {'name': 'Scala', 'bytes': '100505'}, {'name': 'Shell', 'bytes': '974'}]}
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package MyProcess; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; /** * * @author amungen */ public class GetImagesT extends Thread { String generalpath = "/Volumes/Levent-Taha/Flicker/"; public void run() { allprocess(); } public static void main(String[] args) { GetImagesT g = new GetImagesT(); g.allprocess(); // g.deleteimage("adadada"); } public void allprocess() { // for (int i = 400; i < 700; i++) { createnewfolder(i+""); } // for (int i = 0; i < 1000; i++) { downloadimages(); // } } public void downloadimages() { Connection conn = null; Statement st = null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); String dbUrl = "jdbc:mysql://omitechnology.com/omitechn_flick?useUnicode=true&characterEncode=UTF-8"; conn = DriverManager.getConnection(dbUrl, "omite_flick", "flick"); conn.createStatement(); st = conn.createStatement(); int sayac = 0; rs = st.executeQuery("Select url_o,ID,PHOTOID FROM photos WHERE downimage=0"); int id; String folderpath = "1"; String photoid; String link; while (rs.next()) { id = rs.getInt("id"); photoid = rs.getString("photoid"); folderpath = ((id / 500) + 1) + "/"; link = rs.getString("url_o"); if (link.length() > 10) { singledownloadimage(id, link, folderpath, photoid); sayac++; if (sayac % 10 == 0) { System.out.println("Toplam Basarili Download = " + sayac); } if (sayac % 4 == 0) { System.out.println("Break"); break; } } } conn.close(); rs.close(); st.close(); } catch (Exception e) { e.printStackTrace(); } } public void singledownloadimage(int ID, String link, String folderpath, String photoid) { try { // System.out.println("link = " + link); // System.out.println("1 = " + link.lastIndexOf(".")); // System.out.println("2 = " + link.length()); String extention = link.substring(link.lastIndexOf("."), link.length()); // System.out.println("extention = " + extention); URL url = new URL(link); InputStream in = new BufferedInputStream(url.openStream()); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int n = 0; while (-1 != (n = in.read(buf))) { out.write(buf, 0, n); } out.close(); in.close(); byte[] response = out.toByteArray(); if (response.length > 10000) { FileOutputStream fos = new FileOutputStream(generalpath + folderpath + photoid + extention); fos.write(response); fos.close(); updateimagestatus(ID); } else { deleteimage(photoid); } } catch (Exception e) { e.printStackTrace(); } } public void createnewfolder(String foldername) { try { // File newDir = new File("/Users/amungen/Desktop/flicker/" + foldername); File newDir = new File(generalpath + foldername); boolean success = newDir.mkdir(); } catch (Exception e) { e.printStackTrace(); } } public void updateimagestatus(int ID) { Connection conn = null; Statement st = null; ResultSet rs = null; try { // omitechn_youtubecraw omite_youtubecra ahmet Class.forName("com.mysql.jdbc.Driver").newInstance(); String dbUrl = "jdbc:mysql://omitechnology.com/omitechn_flick?useUnicode=true&characterEncode=UTF-8"; conn = DriverManager.getConnection(dbUrl, "omite_flick", "flick"); st = conn.createStatement(); st.executeUpdate("UPDATE photos set downimage=1 WHERE id='" + ID + "'"); if (rs != null) { rs.close(); } if (st != null) { st.close(); } if (conn != null) { conn.close(); } } catch (Exception e) { e.printStackTrace(); } } public void deleteimage(String imageID) { //DELETE FROM photos WHERE photoid='+imageID; Connection conn = null; Statement st = null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); String dbUrl = "jdbc:mysql://omitechnology.com/omitechn_flick?useUnicode=true&characterEncode=UTF-8"; conn = DriverManager.getConnection(dbUrl, "omite_flick", "flick"); st = conn.createStatement(); String sql = "DELETE FROM photos WHERE photoid='" + imageID + "'"; // System.out.println("sql = " + sql); st.executeUpdate(sql); statisticdeletefile(); if (rs != null) { rs.close(); } if (st != null) { st.close(); } if (conn != null) { conn.close(); } } catch (Exception e) { e.printStackTrace(); } } public void statisticdeletefile() { //UPDATE WRONG SET WrongSize = WrongSize + 1 Connection conn = null; Statement st = null; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); String dbUrl = "jdbc:mysql://omitechnology.com/omitechn_flick?useUnicode=true&characterEncode=UTF-8"; conn = DriverManager.getConnection(dbUrl, "omite_flick", "flick"); st = conn.createStatement(); String sqlquery = "UPDATE statistic SET deletedimagesize = deletedimagesize + 1"; st.execute(sqlquery); conn.close(); st.close(); // System.out.println("link yok"); } catch (Exception e) { e.printStackTrace(); } } }
{'content_hash': 'c8c9d5e01a9027a5daa5f6df40ce6862', 'timestamp': '', 'source': 'github', 'line_count': 233, 'max_line_length': 113, 'avg_line_length': 29.44206008583691, 'alnum_prop': 0.5112244897959184, 'repo_name': 'pcvlab/Flicker-Data-Integration', 'id': '78e9093fd6abe915bd718f22546ed634f29cf49c', 'size': '6860', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'FlickerWeb3/src/java/MyProcess/GetImagesT.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '172413'}]}
import rethinkdb as r conn = r.connect('localhost', 28015) r.db('rethinkdb').table('cluster_config').get('auth').update( {'auth_key': 'cloudroutes'} ).run(conn)
{'content_hash': 'a5210b21ba9d9f65439026c2688fd29d', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 61, 'avg_line_length': 27.666666666666668, 'alnum_prop': 0.6746987951807228, 'repo_name': 'Runbook/runbook', 'id': 'f823089a6e019a470d8c7217fba30608b30d2096', 'size': '166', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'src/bridge/mgmtscripts/set_rethink_auth_key.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '17816'}, {'name': 'HTML', 'bytes': '227999'}, {'name': 'JavaScript', 'bytes': '4250'}, {'name': 'Python', 'bytes': '754910'}, {'name': 'Shell', 'bytes': '5859'}]}
using namespace v8; Persistent<Function> PriorityQ::constructor; PriorityQ::PriorityQ() { auto compare = [](const std::shared_ptr<QObjectHolder> &lhs, const std::shared_ptr<QObjectHolder> &rhs) -> bool { return lhs->priority < rhs->priority; }; hq_ = std::make_shared<HolderQ>(compare); } PriorityQ::PriorityQ(Isolate *isolate, Local<Function> cmp) { HandleScope handle_scope(isolate); LOGD("Setting up comparotor") if (cmp.IsEmpty()) { LOGD("cmp is EMPTY!"); } else { LOGD("CMP WAS NOT EMPTY") } hasComparator_ = true; CopyablePersistentObject pcmp; pcmp.Reset(isolate, cmp); auto ptrCmp = std::make_shared<CopyablePersistentObject>(std::move(pcmp)); auto compare = [ptrCmp, isolate](const std::shared_ptr<QObjectHolder> &lhs, const std::shared_ptr<QObjectHolder> &rhs) -> bool { //return lhs->priority < rhs->priority; LOGD("CALLING JS COMPARATOR !") Local<Object> g = ptrCmp->Get(isolate); if (g.IsEmpty()) { LOGD("comparotor was empty inside persistent") } else { LOGD("cmp was NOT empty in persistent") } Local<Function> fn = Local<Function>::Cast(g); LOGD("CP AFTER CAST") Handle<Value> argv[2]; Local<Value> o1 = lhs->cpo.Get(isolate); argv[0] = o1; LOGD("AFTER ARG0") Local<Value> o2 = rhs->cpo.Get(isolate); argv[1] = o2; LOGD("ADTER ARG2") MaybeLocal<Value> res = fn->Call(Null(isolate), 2, argv); if (res.IsEmpty()) { LOGD("!!!!!!!!!!!!!! BAD FUNCTION CALL. No RESULT !!!!!!!!") return false; } else { return res.ToLocalChecked()->BooleanValue(); } }; hq_ = std::make_shared<HolderQ>(compare); } void PriorityQ::Init(v8::Local<v8::Object> exports) { Isolate *isolate = exports->GetIsolate(); // Prepare constructor template Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New); tpl->SetClassName(String::NewFromUtf8(isolate, "priority_queue_native")); tpl->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(tpl, "push", Push); NODE_SET_PROTOTYPE_METHOD(tpl, "top", Top); NODE_SET_PROTOTYPE_METHOD(tpl, "pop", Pop); NODE_SET_PROTOTYPE_METHOD(tpl, "size", Size); NODE_SET_PROTOTYPE_METHOD(tpl, "next", Next); NODE_SET_ITERATOR_METHOD(tpl, GetIterator); constructor.Reset(isolate, tpl->GetFunction()); exports->Set(String::NewFromUtf8(isolate, "PriorityQueue"), tpl->GetFunction()); exports->Set(String::NewFromUtf8(isolate, "PriorityQueueCompare"), tpl->GetFunction()); } void PriorityQ::New(const v8::FunctionCallbackInfo<v8::Value> &args) { Isolate *isolate = args.GetIsolate(); if (args.IsConstructCall()) { PriorityQ *obj; // Invoked as constructor if (args[0]->IsFunction()) { Local<Function> cmp = Local<Function>::Cast(args[0]); obj = new PriorityQ(isolate, cmp); } else { obj = new PriorityQ(); } obj->Wrap(args.This()); args.GetReturnValue().Set(args.This()); } else { // Invoked as plain function, turn into construct call. const int argc = 1; Local<Value> argv[argc] = {args[0]}; Local<Function> cons = Local<Function>::New(isolate, constructor); MaybeLocal<Object> o = cons->NewInstance(isolate->GetCurrentContext(), argc, argv); args.GetReturnValue().Set(o.ToLocalChecked()); } } void PriorityQ::Push(const v8::FunctionCallbackInfo<v8::Value> &args) { Isolate *isolate = args.GetIsolate(); PriorityQ *obj = Unwrap<PriorityQ>(args.Holder()); double d = 0; LocalType t; Local<Value> lo; if (args[0]->IsNumber()) { t = LocalType::NUMBER; lo = args[0]->ToNumber(isolate); } else if (args[0]->IsString()) { t = LocalType::STRING; lo = args[0]->ToString(isolate); } else if (args[0]->IsBoolean()) { t = LocalType::BOOLEAN; lo = args[0]->ToBoolean(isolate); } else { t = LocalType::OBJECT; lo = args[0]->ToObject(isolate); } // Check for second arg requirements // its required ONLY if there is no comparator if (!obj->hasComparator_) { Local<Number> ln = args[1]->ToNumber(isolate); d = ln->NumberValue(); LOGD2("~ Adding to hq_ with priority=", d); } obj->hq_->push(std::make_shared<QObjectHolder>(d, isolate, lo, t)); LOGD("Item pushed to queue"); } Local<Value> PriorityQ::Top_(const v8::FunctionCallbackInfo<v8::Value> &args) { Isolate *isolate = args.GetIsolate(); EscapableHandleScope my_handle_scope(isolate); PriorityQ *obj = Unwrap<PriorityQ>(args.Holder()); // Very important to check size first // if queue is empty then calling top and pop // will result in segmentation fault // wrapping this inside native try/catch will not help if (obj->hq_->size() > 0) { LOGD("Inside Top :: Have items in queue") auto top = obj->hq_->top(); Local<Value> lo = top->cpo.Get(isolate); LocalType t = top->T_; switch (t) { case LocalType::NUMBER: LOGD("RETURNING AS NUMBER") return my_handle_scope.Escape(lo->ToNumber(isolate)); case LocalType::STRING: LOGD("RETURNING AS STRING") return my_handle_scope.Escape(lo->ToString(isolate)); case LocalType::BOOLEAN: LOGD("RETURNING AS BOOLEAN") return my_handle_scope.Escape(lo->ToBoolean(isolate)); default: LOGD("RETURNING AS OBJECT") return my_handle_scope.Escape(lo->ToObject(isolate)); } } else { LOGD("NO ITEMS IN QUEUE. WILL RETURN UNDEFINED TO TOP") return my_handle_scope.Escape(Undefined(isolate)); } } void PriorityQ::Top(const v8::FunctionCallbackInfo<v8::Value> &args) { args.GetReturnValue().Set(Top_(args)); } void PriorityQ::Pop(const v8::FunctionCallbackInfo<v8::Value> &args) { LOGD("ENTERED POP"); PriorityQ *obj = Unwrap<PriorityQ>(args.Holder()); args.GetReturnValue().Set(Top_(args)); if (obj->hq_->size() > 0) { obj->hq_->pop(); } } void PriorityQ::Size(const v8::FunctionCallbackInfo<v8::Value> &args) { Isolate *isolate = args.GetIsolate(); PriorityQ *obj = Unwrap<PriorityQ>(args.Holder()); LOGD("Looking for size") size_t sz = obj->hq_->size(); args.GetReturnValue().Set(Number::New(isolate, sz)); } void PriorityQ::GetIterator(const v8::FunctionCallbackInfo<v8::Value> &args) { args.GetReturnValue().Set(args.This()); } void PriorityQ::Next(const FunctionCallbackInfo<Value> &args) { Isolate *isolate = args.GetIsolate(); PriorityQ *obj = Unwrap<PriorityQ>(args.Holder()); Local<Object> retObj = Object::New(isolate); Local<Value> lv; if (obj->hq_->size() > 0) { LOGD("Inside Pop :: Have items in queue") lv = Top_(args); obj->hq_->pop(); // now we must create local object with properties that iterator // is expected to return // retObj->Set(String::NewFromUtf8(isolate, ITER_VALUE), lv); retObj->Set(String::NewFromUtf8(isolate, ITER_DONE), Boolean::New(isolate, false)); } else { LOGD("ITERATOR::NEXT NO ITEMS IN QUEUE") retObj->Set(String::NewFromUtf8(isolate, ITER_VALUE), Undefined(isolate)); retObj->Set(String::NewFromUtf8(isolate, ITER_DONE), Boolean::New(isolate, true)); } args.GetReturnValue().Set(retObj); } // If implementing optional return method of iterator // its very important that it returns IteratorResult from it, otherwise // some v8 versions will crash. void PriorityQ::Return(const v8::FunctionCallbackInfo<v8::Value> &args) { LOGD("^^^^^^^^^^^^^ ITER::Return called ^^^^^^^^^^^^^"); Isolate *isolate = args.GetIsolate(); Local<Object> retObj = Object::New(isolate); retObj->Set(String::NewFromUtf8(isolate, ITER_DONE), Boolean::New(isolate, true)); args.GetReturnValue().Set(retObj); } void InitAll(Local<Object> exports) { PriorityQ::Init(exports); } NODE_MODULE(mypq, InitAll)
{'content_hash': '8e1f35c79a2a3bd0980c13350f82478b', 'timestamp': '', 'source': 'github', 'line_count': 293, 'max_line_length': 117, 'avg_line_length': 28.75085324232082, 'alnum_prop': 0.6043447293447294, 'repo_name': 'snytkine/node_priority_queue_native', 'id': '7c5034ccfd29d0c9defe8926612c7f11e66f5d01', 'size': '8576', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/priorityqueue_native.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '14573'}, {'name': 'CMake', 'bytes': '511'}, {'name': 'Python', 'bytes': '631'}]}
/* This file is part of the WebKit open source project. This file has been generated by generate-bindings.pl. DO NOT MODIFY! This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "config.h" #include "V8SVGFETurbulenceElement.h" #if ENABLE(SVG) && ENABLE(FILTERS) #include "CSSMutableStyleDeclaration.h" #include "ExceptionCode.h" #include "RuntimeEnabledFeatures.h" #include "V8Binding.h" #include "V8BindingMacros.h" #include "V8BindingState.h" #include "V8CSSStyleDeclaration.h" #include "V8CSSValue.h" #include "V8DOMWrapper.h" #include "V8IsolatedContext.h" #include "V8Proxy.h" #include "V8SVGAnimatedEnumeration.h" #include "V8SVGAnimatedInteger.h" #include "V8SVGAnimatedLength.h" #include "V8SVGAnimatedNumber.h" #include "V8SVGAnimatedString.h" #include "V8SVGElement.h" #include <wtf/GetPtr.h> #include <wtf/RefCounted.h> #include <wtf/RefPtr.h> namespace WebCore { WrapperTypeInfo V8SVGFETurbulenceElement::info = { V8SVGFETurbulenceElement::GetTemplate, V8SVGFETurbulenceElement::derefObject, 0, &V8SVGElement::info }; namespace SVGFETurbulenceElementInternal { template <typename T> void V8_USE(T) { } static v8::Handle<v8::Value> baseFrequencyXAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.SVGFETurbulenceElement.baseFrequencyX._get"); SVGFETurbulenceElement* imp = V8SVGFETurbulenceElement::toNative(info.Holder()); return toV8(imp->baseFrequencyXAnimated()); } static v8::Handle<v8::Value> baseFrequencyYAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.SVGFETurbulenceElement.baseFrequencyY._get"); SVGFETurbulenceElement* imp = V8SVGFETurbulenceElement::toNative(info.Holder()); return toV8(imp->baseFrequencyYAnimated()); } static v8::Handle<v8::Value> numOctavesAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.SVGFETurbulenceElement.numOctaves._get"); SVGFETurbulenceElement* imp = V8SVGFETurbulenceElement::toNative(info.Holder()); return toV8(imp->numOctavesAnimated()); } static v8::Handle<v8::Value> seedAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.SVGFETurbulenceElement.seed._get"); SVGFETurbulenceElement* imp = V8SVGFETurbulenceElement::toNative(info.Holder()); return toV8(imp->seedAnimated()); } static v8::Handle<v8::Value> stitchTilesAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.SVGFETurbulenceElement.stitchTiles._get"); SVGFETurbulenceElement* imp = V8SVGFETurbulenceElement::toNative(info.Holder()); return toV8(static_pointer_cast<SVGAnimatedEnumeration>(imp->stitchTilesAnimated())); } static v8::Handle<v8::Value> typeAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.SVGFETurbulenceElement.type._get"); SVGFETurbulenceElement* imp = V8SVGFETurbulenceElement::toNative(info.Holder()); return toV8(static_pointer_cast<SVGAnimatedEnumeration>(imp->typeAnimated())); } static v8::Handle<v8::Value> xAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.SVGFETurbulenceElement.x._get"); SVGFETurbulenceElement* imp = V8SVGFETurbulenceElement::toNative(info.Holder()); return toV8(imp->xAnimated()); } static v8::Handle<v8::Value> yAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.SVGFETurbulenceElement.y._get"); SVGFETurbulenceElement* imp = V8SVGFETurbulenceElement::toNative(info.Holder()); return toV8(imp->yAnimated()); } static v8::Handle<v8::Value> widthAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.SVGFETurbulenceElement.width._get"); SVGFETurbulenceElement* imp = V8SVGFETurbulenceElement::toNative(info.Holder()); return toV8(imp->widthAnimated()); } static v8::Handle<v8::Value> heightAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.SVGFETurbulenceElement.height._get"); SVGFETurbulenceElement* imp = V8SVGFETurbulenceElement::toNative(info.Holder()); return toV8(imp->heightAnimated()); } static v8::Handle<v8::Value> resultAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.SVGFETurbulenceElement.result._get"); SVGFETurbulenceElement* imp = V8SVGFETurbulenceElement::toNative(info.Holder()); return toV8(imp->resultAnimated()); } static v8::Handle<v8::Value> classNameAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.SVGFETurbulenceElement.className._get"); SVGFETurbulenceElement* imp = V8SVGFETurbulenceElement::toNative(info.Holder()); return toV8(imp->classNameAnimated()); } static v8::Handle<v8::Value> styleAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info) { INC_STATS("DOM.SVGFETurbulenceElement.style._get"); SVGFETurbulenceElement* imp = V8SVGFETurbulenceElement::toNative(info.Holder()); return toV8(imp->style()); } static v8::Handle<v8::Value> getPresentationAttributeCallback(const v8::Arguments& args) { INC_STATS("DOM.SVGFETurbulenceElement.getPresentationAttribute"); SVGFETurbulenceElement* imp = V8SVGFETurbulenceElement::toNative(args.Holder()); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, name, MAYBE_MISSING_PARAMETER(args, 0, MissingIsUndefined)); return toV8(imp->getPresentationAttribute(name)); } } // namespace SVGFETurbulenceElementInternal static const BatchedAttribute SVGFETurbulenceElementAttrs[] = { // Attribute 'baseFrequencyX' (Type: 'readonly attribute' ExtAttr: '') {"baseFrequencyX", SVGFETurbulenceElementInternal::baseFrequencyXAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'baseFrequencyY' (Type: 'readonly attribute' ExtAttr: '') {"baseFrequencyY", SVGFETurbulenceElementInternal::baseFrequencyYAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'numOctaves' (Type: 'readonly attribute' ExtAttr: '') {"numOctaves", SVGFETurbulenceElementInternal::numOctavesAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'seed' (Type: 'readonly attribute' ExtAttr: '') {"seed", SVGFETurbulenceElementInternal::seedAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'stitchTiles' (Type: 'readonly attribute' ExtAttr: '') {"stitchTiles", SVGFETurbulenceElementInternal::stitchTilesAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'type' (Type: 'readonly attribute' ExtAttr: '') {"type", SVGFETurbulenceElementInternal::typeAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'x' (Type: 'readonly attribute' ExtAttr: '') {"x", SVGFETurbulenceElementInternal::xAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'y' (Type: 'readonly attribute' ExtAttr: '') {"y", SVGFETurbulenceElementInternal::yAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'width' (Type: 'readonly attribute' ExtAttr: '') {"width", SVGFETurbulenceElementInternal::widthAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'height' (Type: 'readonly attribute' ExtAttr: '') {"height", SVGFETurbulenceElementInternal::heightAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'result' (Type: 'readonly attribute' ExtAttr: '') {"result", SVGFETurbulenceElementInternal::resultAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'className' (Type: 'readonly attribute' ExtAttr: '') {"className", SVGFETurbulenceElementInternal::classNameAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, // Attribute 'style' (Type: 'readonly attribute' ExtAttr: '') {"style", SVGFETurbulenceElementInternal::styleAttrGetter, 0, 0 /* no data */, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, }; static const BatchedCallback SVGFETurbulenceElementCallbacks[] = { {"getPresentationAttribute", SVGFETurbulenceElementInternal::getPresentationAttributeCallback}, }; static const BatchedConstant SVGFETurbulenceElementConsts[] = { {"SVG_TURBULENCE_TYPE_UNKNOWN", static_cast<signed int>(0)}, {"SVG_TURBULENCE_TYPE_FRACTALNOISE", static_cast<signed int>(1)}, {"SVG_TURBULENCE_TYPE_TURBULENCE", static_cast<signed int>(2)}, {"SVG_STITCHTYPE_UNKNOWN", static_cast<signed int>(0)}, {"SVG_STITCHTYPE_STITCH", static_cast<signed int>(1)}, {"SVG_STITCHTYPE_NOSTITCH", static_cast<signed int>(2)}, }; static v8::Persistent<v8::FunctionTemplate> ConfigureV8SVGFETurbulenceElementTemplate(v8::Persistent<v8::FunctionTemplate> desc) { desc->ReadOnlyPrototype(); v8::Local<v8::Signature> defaultSignature = configureTemplate(desc, "SVGFETurbulenceElement", V8SVGElement::GetTemplate(), V8SVGFETurbulenceElement::internalFieldCount, SVGFETurbulenceElementAttrs, WTF_ARRAY_LENGTH(SVGFETurbulenceElementAttrs), SVGFETurbulenceElementCallbacks, WTF_ARRAY_LENGTH(SVGFETurbulenceElementCallbacks)); v8::Local<v8::ObjectTemplate> instance = desc->InstanceTemplate(); v8::Local<v8::ObjectTemplate> proto = desc->PrototypeTemplate(); batchConfigureConstants(desc, proto, SVGFETurbulenceElementConsts, WTF_ARRAY_LENGTH(SVGFETurbulenceElementConsts)); // Custom toString template desc->Set(getToStringName(), getToStringTemplate()); return desc; } v8::Persistent<v8::FunctionTemplate> V8SVGFETurbulenceElement::GetRawTemplate() { V8BindingPerIsolateData* data = V8BindingPerIsolateData::current(); V8BindingPerIsolateData::TemplateMap::iterator result = data->rawTemplateMap().find(&info); if (result != data->rawTemplateMap().end()) return result->second; v8::HandleScope handleScope; v8::Persistent<v8::FunctionTemplate> templ = createRawTemplate(); data->rawTemplateMap().add(&info, templ); return templ; } v8::Persistent<v8::FunctionTemplate> V8SVGFETurbulenceElement::GetTemplate() { V8BindingPerIsolateData* data = V8BindingPerIsolateData::current(); V8BindingPerIsolateData::TemplateMap::iterator result = data->templateMap().find(&info); if (result != data->templateMap().end()) return result->second; v8::HandleScope handleScope; v8::Persistent<v8::FunctionTemplate> templ = ConfigureV8SVGFETurbulenceElementTemplate(GetRawTemplate()); data->templateMap().add(&info, templ); return templ; } bool V8SVGFETurbulenceElement::HasInstance(v8::Handle<v8::Value> value) { return GetRawTemplate()->HasInstance(value); } v8::Handle<v8::Object> V8SVGFETurbulenceElement::wrapSlow(SVGFETurbulenceElement* impl) { v8::Handle<v8::Object> wrapper; V8Proxy* proxy = 0; if (impl->document()) { proxy = V8Proxy::retrieve(impl->document()->frame()); if (proxy && static_cast<Node*>(impl->document()) == static_cast<Node*>(impl)) { if (proxy->windowShell()->initContextIfNeeded()) { // initContextIfNeeded may have created a wrapper for the object, retry from the start. return V8SVGFETurbulenceElement::wrap(impl); } } } v8::Handle<v8::Context> context; if (proxy) context = proxy->context(); // Enter the node's context and create the wrapper in that context. if (!context.IsEmpty()) context->Enter(); wrapper = V8DOMWrapper::instantiateV8Object(proxy, &info, impl); // Exit the node's context if it was entered. if (!context.IsEmpty()) context->Exit(); if (wrapper.IsEmpty()) return wrapper; impl->ref(); v8::Persistent<v8::Object> wrapperHandle = v8::Persistent<v8::Object>::New(wrapper); if (!hasDependentLifetime) wrapperHandle.MarkIndependent(); wrapperHandle.SetWrapperClassId(v8DOMSubtreeClassId); getDOMNodeMap().set(impl, wrapperHandle); return wrapper; } void V8SVGFETurbulenceElement::derefObject(void* object) { static_cast<SVGFETurbulenceElement*>(object)->deref(); } } // namespace WebCore #endif // ENABLE(SVG) && ENABLE(FILTERS)
{'content_hash': 'c86795024df3a1976bbfa5591ff239ed', 'timestamp': '', 'source': 'github', 'line_count': 294, 'max_line_length': 213, 'avg_line_length': 47.54081632653061, 'alnum_prop': 0.7255491164055233, 'repo_name': 'Treeeater/WebPermission', 'id': '2639810f3f0f575252c83425bb27d61b77f2fe2b', 'size': '13977', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src_chrome_Release_obj_global_intermediate_webcore/bindings/V8SVGFETurbulenceElement.cpp', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Assembly', 'bytes': '1301'}, {'name': 'C', 'bytes': '1820540'}, {'name': 'C++', 'bytes': '38574524'}, {'name': 'Java', 'bytes': '4882'}, {'name': 'JavaScript', 'bytes': '2238901'}, {'name': 'Objective-C', 'bytes': '1768529'}, {'name': 'PHP', 'bytes': '606'}, {'name': 'Perl', 'bytes': '699893'}, {'name': 'Prolog', 'bytes': '142937'}, {'name': 'Python', 'bytes': '131318'}, {'name': 'R', 'bytes': '290'}, {'name': 'Ruby', 'bytes': '3798'}, {'name': 'Shell', 'bytes': '52312'}]}
""" The `compat` module provides support for backwards compatibility with older versions of Django/Python, and compatibility wrappers around optional packages. """ # flake8: noqa from __future__ import unicode_literals import inspect import django from django.apps import apps from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db import connection, models, transaction from django.template import Context, RequestContext, Template from django.utils import six from django.views.generic import View try: from django.urls import ( NoReverseMatch, RegexURLPattern, RegexURLResolver, ResolverMatch, Resolver404, get_script_prefix, reverse, reverse_lazy, resolve ) except ImportError: from django.core.urlresolvers import ( # Will be removed in Django 2.0 NoReverseMatch, RegexURLPattern, RegexURLResolver, ResolverMatch, Resolver404, get_script_prefix, reverse, reverse_lazy, resolve ) try: import urlparse # Python 2.x except ImportError: import urllib.parse as urlparse def unicode_repr(instance): # Get the repr of an instance, but ensure it is a unicode string # on both python 3 (already the case) and 2 (not the case). if six.PY2: return repr(instance).decode('utf-8') return repr(instance) def unicode_to_repr(value): # Coerce a unicode string to the correct repr return type, depending on # the Python version. We wrap all our `__repr__` implementations with # this and then use unicode throughout internally. if six.PY2: return value.encode('utf-8') return value def unicode_http_header(value): # Coerce HTTP header value to unicode. if isinstance(value, six.binary_type): return value.decode('iso-8859-1') return value def total_seconds(timedelta): # TimeDelta.total_seconds() is only available in Python 2.7 if hasattr(timedelta, 'total_seconds'): return timedelta.total_seconds() else: return (timedelta.days * 86400.0) + float(timedelta.seconds) + (timedelta.microseconds / 1000000.0) def distinct(queryset, base): if settings.DATABASES[queryset.db]["ENGINE"] == "django.db.backends.oracle": # distinct analogue for Oracle users return base.filter(pk__in=set(queryset.values_list('pk', flat=True))) return queryset.distinct() # Obtaining manager instances and names from model options differs after 1.10. def get_names_and_managers(options): if django.VERSION >= (1, 10): # Django 1.10 onwards provides a `.managers` property on the Options. return [ (manager.name, manager) for manager in options.managers ] # For Django 1.8 and 1.9, use the three-tuple information provided # by .concrete_managers and .abstract_managers return [ (manager_info[1], manager_info[2]) for manager_info in (options.concrete_managers + options.abstract_managers) ] # field.rel is deprecated from 1.9 onwards def get_remote_field(field, **kwargs): if 'default' in kwargs: if django.VERSION < (1, 9): return getattr(field, 'rel', kwargs['default']) return getattr(field, 'remote_field', kwargs['default']) if django.VERSION < (1, 9): return field.rel return field.remote_field def _resolve_model(obj): """ Resolve supplied `obj` to a Django model class. `obj` must be a Django model class itself, or a string representation of one. Useful in situations like GH #1225 where Django may not have resolved a string-based reference to a model in another model's foreign key definition. String representations should have the format: 'appname.ModelName' """ if isinstance(obj, six.string_types) and len(obj.split('.')) == 2: app_name, model_name = obj.split('.') resolved_model = apps.get_model(app_name, model_name) if resolved_model is None: msg = "Django did not return a model for {0}.{1}" raise ImproperlyConfigured(msg.format(app_name, model_name)) return resolved_model elif inspect.isclass(obj) and issubclass(obj, models.Model): return obj raise ValueError("{0} is not a Django model".format(obj)) def is_authenticated(user): if django.VERSION < (1, 10): return user.is_authenticated() return user.is_authenticated def is_anonymous(user): if django.VERSION < (1, 10): return user.is_anonymous() return user.is_anonymous def get_related_model(field): if django.VERSION < (1, 9): return _resolve_model(field.rel.to) return field.remote_field.model def value_from_object(field, obj): if django.VERSION < (1, 9): return field._get_val_from_obj(obj) return field.value_from_object(obj) # contrib.postgres only supported from 1.8 onwards. try: from django.contrib.postgres import fields as postgres_fields except ImportError: postgres_fields = None # JSONField is only supported from 1.9 onwards try: from django.contrib.postgres.fields import JSONField except ImportError: JSONField = None # coreapi is optional (Note that uritemplate is a dependency of coreapi) try: import coreapi import uritemplate except (ImportError, SyntaxError): # SyntaxError is possible under python 3.2 coreapi = None uritemplate = None # coreschema is optional try: import coreschema except ImportError: coreschema = None # django-filter is optional try: import django_filters except ImportError: django_filters = None # django-crispy-forms is optional try: import crispy_forms except ImportError: crispy_forms = None # requests is optional try: import requests except ImportError: requests = None # Django-guardian is optional. Import only if guardian is in INSTALLED_APPS # Fixes (#1712). We keep the try/except for the test suite. guardian = None try: if 'guardian' in settings.INSTALLED_APPS: import guardian except ImportError: pass # PATCH method is not implemented by Django if 'patch' not in View.http_method_names: View.http_method_names = View.http_method_names + ['patch'] # Markdown is optional try: import markdown if markdown.version <= '2.2': HEADERID_EXT_PATH = 'headerid' LEVEL_PARAM = 'level' elif markdown.version < '2.6': HEADERID_EXT_PATH = 'markdown.extensions.headerid' LEVEL_PARAM = 'level' else: HEADERID_EXT_PATH = 'markdown.extensions.toc' LEVEL_PARAM = 'baselevel' def apply_markdown(text): """ Simple wrapper around :func:`markdown.markdown` to set the base level of '#' style headers to <h2>. """ extensions = [HEADERID_EXT_PATH] extension_configs = { HEADERID_EXT_PATH: { LEVEL_PARAM: '2' } } md = markdown.Markdown( extensions=extensions, extension_configs=extension_configs ) return md.convert(text) except ImportError: apply_markdown = None markdown = None try: import pygments from pygments.lexers import get_lexer_by_name from pygments.formatters import HtmlFormatter def pygments_highlight(text, lang, style): lexer = get_lexer_by_name(lang, stripall=False) formatter = HtmlFormatter(nowrap=True, style=style) return pygments.highlight(text, lexer, formatter) def pygments_css(style): formatter = HtmlFormatter(style=style) return formatter.get_style_defs('.highlight') except ImportError: pygments = None def pygments_highlight(text, lang, style): return text def pygments_css(style): return None # `separators` argument to `json.dumps()` differs between 2.x and 3.x # See: http://bugs.python.org/issue22767 if six.PY3: SHORT_SEPARATORS = (',', ':') LONG_SEPARATORS = (', ', ': ') INDENT_SEPARATORS = (',', ': ') else: SHORT_SEPARATORS = (b',', b':') LONG_SEPARATORS = (b', ', b': ') INDENT_SEPARATORS = (b',', b': ') try: # DecimalValidator is unavailable in Django < 1.9 from django.core.validators import DecimalValidator except ImportError: DecimalValidator = None def set_rollback(): if hasattr(transaction, 'set_rollback'): if connection.settings_dict.get('ATOMIC_REQUESTS', False): # If running in >=1.6 then mark a rollback as required, # and allow it to be handled by Django. if connection.in_atomic_block: transaction.set_rollback(True) elif transaction.is_managed(): # Otherwise handle it explicitly if in managed mode. if transaction.is_dirty(): transaction.rollback() transaction.leave_transaction_management() else: # transaction not managed pass def template_render(template, context=None, request=None): """ Passing Context or RequestContext to Template.render is deprecated in 1.9+, see https://github.com/django/django/pull/3883 and https://github.com/django/django/blob/1.9/django/template/backends/django.py#L82-L84 :param template: Template instance :param context: dict :param request: Request instance :return: rendered template as SafeText instance """ if isinstance(template, Template): if request: context = RequestContext(request, context) else: context = Context(context) return template.render(context) # backends template, e.g. django.template.backends.django.Template else: return template.render(context, request=request) def set_many(instance, field, value): if django.VERSION < (1, 10): setattr(instance, field, value) else: field = getattr(instance, field) field.set(value) def include(module, namespace=None, app_name=None): from django.conf.urls import include if django.VERSION < (1,9): return include(module, namespace, app_name) else: return include((module, app_name), namespace)
{'content_hash': '0bdefcfe7929383e99b8e6e17e3d101a', 'timestamp': '', 'source': 'github', 'line_count': 347, 'max_line_length': 136, 'avg_line_length': 29.259365994236312, 'alnum_prop': 0.6717226435536294, 'repo_name': 'BassantMorsi/finderApp', 'id': '45ac498417378ba92e6968d4026d473c8dfca7b3', 'size': '10153', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'lib/python2.7/site-packages/rest_framework/compat.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '220402'}, {'name': 'C++', 'bytes': '96699'}, {'name': 'CSS', 'bytes': '84455'}, {'name': 'Fortran', 'bytes': '7439'}, {'name': 'HTML', 'bytes': '217197'}, {'name': 'JavaScript', 'bytes': '365169'}, {'name': 'Objective-C', 'bytes': '567'}, {'name': 'Python', 'bytes': '14137616'}, {'name': 'Shell', 'bytes': '3238'}]}
package org.drools.core.base.accumulators; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; /** * An implementation of an accumulator capable of calculating maximum values */ public class MaxAccumulateFunction extends AbstractAccumulateFunction<MaxAccumulateFunction.MaxData> { public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { } public void writeExternal(ObjectOutput out) throws IOException { } protected static class MaxData implements Externalizable { public Comparable max = null; public MaxData() {} public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { max = (Comparable) in.readObject(); } public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(max); } @Override public String toString() { return "max"; } } public MaxData createContext() { return new MaxData(); } public void init(MaxData data) { data.max = null; } public void accumulate(MaxData data, Object value) { if (value != null) { data.max = data.max == null || data.max.compareTo( value ) < 0 ? (Comparable) value : data.max; } } public void reverse(MaxData data, Object value) { } public Object getResult(MaxData data) { return data.max; } public boolean supportsReverse() { return false; } public Class<?> getResultType() { return Comparable.class; } }
{'content_hash': '1562e44275c09a6af042ef699efb7972', 'timestamp': '', 'source': 'github', 'line_count': 74, 'max_line_length': 102, 'avg_line_length': 23.783783783783782, 'alnum_prop': 0.6102272727272727, 'repo_name': 'droolsjbpm/drools', 'id': '64873471281cc3964259e5d29164d9b26f61aecb', 'size': '2380', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'drools-core/src/main/java/org/drools/core/base/accumulators/MaxAccumulateFunction.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '2554'}, {'name': 'CSS', 'bytes': '1412'}, {'name': 'GAP', 'bytes': '197127'}, {'name': 'HTML', 'bytes': '9298'}, {'name': 'Java', 'bytes': '26871006'}, {'name': 'Protocol Buffer', 'bytes': '13855'}, {'name': 'Python', 'bytes': '4555'}, {'name': 'Ruby', 'bytes': '491'}, {'name': 'Shell', 'bytes': '1120'}, {'name': 'Standard ML', 'bytes': '82260'}, {'name': 'XSLT', 'bytes': '24302'}]}
/** * @file safety.c * Safety button logic. */ #include <px4_config.h> #include <stdbool.h> #include <drivers/drv_hrt.h> #include "px4io.h" static struct hrt_call arming_call; static struct hrt_call failsafe_call; /* * Count the number of times in a row that we see the arming button * held down. */ static unsigned counter = 0; /* * Define the various LED flash sequences for each system state. */ #define LED_PATTERN_FMU_OK_TO_ARM 0x0003 /**< slow blinking */ #define LED_PATTERN_FMU_REFUSE_TO_ARM 0x5555 /**< fast blinking */ #define LED_PATTERN_IO_ARMED 0x5050 /**< long off, then double blink */ #define LED_PATTERN_FMU_ARMED 0x5500 /**< long off, then quad blink */ #define LED_PATTERN_IO_FMU_ARMED 0xffff /**< constantly on */ static unsigned blink_counter = 0; /* * IMPORTANT: The arming state machine critically * depends on using the same threshold * for arming and disarming. Since disarming * is quite deadly for the system, a similar * length can be justified. */ #define ARM_COUNTER_THRESHOLD 10 static bool safety_button_pressed; static void safety_check_button(void *arg); static void failsafe_blink(void *arg); void safety_init(void) { /* arrange for the button handler to be called at 10Hz */ hrt_call_every(&arming_call, 1000, 100000, safety_check_button, NULL); } void failsafe_led_init(void) { /* arrange for the failsafe blinker to be called at 8Hz */ hrt_call_every(&failsafe_call, 1000, 125000, failsafe_blink, NULL); } static void safety_check_button(void *arg) { /* * Debounce the safety button, change state if it has been held for long enough. * */ safety_button_pressed = BUTTON_SAFETY; /* * Keep pressed for a while to arm. * * Note that the counting sequence has to be same length * for arming / disarming in order to end up as proper * state machine, keep ARM_COUNTER_THRESHOLD the same * length in all cases of the if/else struct below. */ if (safety_button_pressed && !(r_status_flags & PX4IO_P_STATUS_FLAGS_SAFETY_OFF) && (r_setup_arming & PX4IO_P_SETUP_ARMING_IO_ARM_OK)) { if (counter < ARM_COUNTER_THRESHOLD) { counter++; } else if (counter == ARM_COUNTER_THRESHOLD) { /* switch to armed state */ r_status_flags |= PX4IO_P_STATUS_FLAGS_SAFETY_OFF; counter++; } } else if (safety_button_pressed && (r_status_flags & PX4IO_P_STATUS_FLAGS_SAFETY_OFF)) { if (counter < ARM_COUNTER_THRESHOLD) { counter++; } else if (counter == ARM_COUNTER_THRESHOLD) { /* change to disarmed state and notify the FMU */ r_status_flags &= ~PX4IO_P_STATUS_FLAGS_SAFETY_OFF; counter++; } } else { counter = 0; } /* Select the appropriate LED flash pattern depending on the current IO/FMU arm state */ uint16_t pattern = LED_PATTERN_FMU_REFUSE_TO_ARM; if (r_status_flags & PX4IO_P_STATUS_FLAGS_SAFETY_OFF) { if (r_setup_arming & PX4IO_P_SETUP_ARMING_FMU_ARMED) { pattern = LED_PATTERN_IO_FMU_ARMED; } else { pattern = LED_PATTERN_IO_ARMED; } } else if (r_setup_arming & PX4IO_P_SETUP_ARMING_FMU_ARMED) { pattern = LED_PATTERN_FMU_ARMED; } else if (r_setup_arming & PX4IO_P_SETUP_ARMING_IO_ARM_OK) { pattern = LED_PATTERN_FMU_OK_TO_ARM; } /* Turn the LED on if we have a 1 at the current bit position */ LED_SAFETY(pattern & (1 << blink_counter++)); if (blink_counter > 15) { blink_counter = 0; } } static void failsafe_blink(void *arg) { /* indicate that a serious initialisation error occured */ if (!(r_status_flags & PX4IO_P_STATUS_FLAGS_INIT_OK)) { LED_AMBER(true); return; } static bool failsafe = false; /* blink the failsafe LED if we don't have FMU input */ if (!(r_status_flags & PX4IO_P_STATUS_FLAGS_FMU_OK)) { failsafe = !failsafe; } else { failsafe = false; } LED_AMBER(failsafe); }
{'content_hash': '4a2ea0d2b2a9a3a5d3fccc2d5f4342ba', 'timestamp': '', 'source': 'github', 'line_count': 155, 'max_line_length': 90, 'avg_line_length': 24.787096774193547, 'alnum_prop': 0.6717855283706403, 'repo_name': 'darknight-007/Firmware', 'id': 'f4ab74a45a6c347140b937064aa1ef4876ea7789', 'size': '5579', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'src/modules/px4iofirmware/safety.c', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '2610222'}, {'name': 'C++', 'bytes': '5712694'}, {'name': 'CMake', 'bytes': '548423'}, {'name': 'GDB', 'bytes': '785'}, {'name': 'Io', 'bytes': '241'}, {'name': 'Makefile', 'bytes': '45018'}, {'name': 'Matlab', 'bytes': '43628'}, {'name': 'Python', 'bytes': '646848'}, {'name': 'Scilab', 'bytes': '1502'}, {'name': 'Shell', 'bytes': '70591'}]}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_22) on Wed May 30 16:48:33 EEST 2012 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class org.apache.wicket.util.tester.DummyPanelPage (Wicket Parent 1.5.7 API) </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="Uses of Class org.apache.wicket.util.tester.DummyPanelPage (Wicket Parent 1.5.7 API)"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/wicket/util/tester/DummyPanelPage.html" title="class in org.apache.wicket.util.tester"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/wicket/util/tester/class-use/DummyPanelPage.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="DummyPanelPage.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.wicket.util.tester.DummyPanelPage</B></H2> </CENTER> No usage of org.apache.wicket.util.tester.DummyPanelPage <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/wicket/util/tester/DummyPanelPage.html" title="class in org.apache.wicket.util.tester"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/wicket/util/tester/class-use/DummyPanelPage.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="DummyPanelPage.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 2006-2012 <a href="http://apache.org">Apache Software Foundation</a>. All Rights Reserved. </BODY> </HTML>
{'content_hash': 'c8641c978838a780d9b05db9dc38a548', 'timestamp': '', 'source': 'github', 'line_count': 141, 'max_line_length': 233, 'avg_line_length': 43.46808510638298, 'alnum_prop': 0.6165769293522597, 'repo_name': 'afiantara/apache-wicket-1.5.7', 'id': '656a7e16f22cd07b917dcbc0126511bd187d4541', 'size': '6129', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'apidocs/org/apache/wicket/util/tester/class-use/DummyPanelPage.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Groovy', 'bytes': '17122'}, {'name': 'Java', 'bytes': '10812577'}, {'name': 'JavaScript', 'bytes': '232484'}]}
layout: post date: 2015-11-27 title: "Camille La Vie Beaded Mesh Two-Tone Dress Sleeveless Floor-Length Mermaid/Trumpet" category: Camille La Vie tags: [Camille La Vie,Mermaid/Trumpet,Spaghetti Straps,Floor-Length,Sleeveless] --- ### Camille La Vie Beaded Mesh Two-Tone Dress Just **$279.99** ### Sleeveless Floor-Length Mermaid/Trumpet <table><tr><td>BRANDS</td><td>Camille La Vie</td></tr><tr><td>Silhouette</td><td>Mermaid/Trumpet</td></tr><tr><td>Neckline</td><td>Spaghetti Straps</td></tr><tr><td>Hemline/Train</td><td>Floor-Length</td></tr><tr><td>Sleeve</td><td>Sleeveless</td></tr></table> <a href="https://www.readybrides.com/en/camille-la-vie/10191-camille-la-vie-beaded-mesh-two-tone-dress.html"><img src="//img.readybrides.com/23347/camille-la-vie-beaded-mesh-two-tone-dress.jpg" alt="Camille La Vie Beaded Mesh Two-Tone Dress" style="width:100%;" /></a> <!-- break --><a href="https://www.readybrides.com/en/camille-la-vie/10191-camille-la-vie-beaded-mesh-two-tone-dress.html"><img src="//img.readybrides.com/23346/camille-la-vie-beaded-mesh-two-tone-dress.jpg" alt="Camille La Vie Beaded Mesh Two-Tone Dress" style="width:100%;" /></a> Buy it: [https://www.readybrides.com/en/camille-la-vie/10191-camille-la-vie-beaded-mesh-two-tone-dress.html](https://www.readybrides.com/en/camille-la-vie/10191-camille-la-vie-beaded-mesh-two-tone-dress.html)
{'content_hash': '32cfb1d4c19b5facf3a4c6174d0137bc', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 282, 'avg_line_length': 97.35714285714286, 'alnum_prop': 0.7351430667644901, 'repo_name': 'HOLEIN/HOLEIN.github.io', 'id': '7a714faf1774f6d00daa209332c1f8094ed3ddf2', 'size': '1367', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '_posts/2015-11-27-Camille-La-Vie-Beaded-Mesh-TwoTone-Dress-Sleeveless-FloorLength-MermaidTrumpet.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '83876'}, {'name': 'HTML', 'bytes': '14547'}, {'name': 'Ruby', 'bytes': '897'}]}
import React from 'react' import { useLocation } from 'react-router' import Modal from 'v2/components/UI/Modal/Portal' import ModalFullscreenDialog from 'v2/components/UI/ModalFullscreenDialog' import { ModalFullBlock } from 'v2/components/ModalFullBlock' import { useParams } from 'react-router' export const ModalBlockWrapper: React.FC = () => { const location = useLocation() const params = useParams() const state = location.state as any const context = state.context const set = new Set<string>( context ?.filter( k => k?.__typename !== 'Channel' && k?.__typename !== 'Group' && k?.__typename !== 'User' && !!k?.id ) .map(k => k.id.toString()) ) const ids = Array.from(set) return ( <Modal Dialog={ModalFullscreenDialog} bg="utility.opaque"> <ModalFullBlock id={parseInt(params.id)} ids={ids} /> </Modal> ) }
{'content_hash': '67d9517c01ffc14b4752ab4dca458196', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 74, 'avg_line_length': 26.34285714285714, 'alnum_prop': 0.6290672451193059, 'repo_name': 'aredotna/ervell', 'id': '448d862a2d81e6d6e04e61f1d40c6db302ec835f', 'size': '922', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/v2/pages/block/ModalBlockWrapper.tsx', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1214'}, {'name': 'CoffeeScript', 'bytes': '115860'}, {'name': 'HTML', 'bytes': '808'}, {'name': 'JavaScript', 'bytes': '589816'}, {'name': 'Procfile', 'bytes': '70'}, {'name': 'Pug', 'bytes': '89001'}, {'name': 'Shell', 'bytes': '1210'}, {'name': 'Stylus', 'bytes': '49151'}, {'name': 'Swift', 'bytes': '15963'}, {'name': 'TypeScript', 'bytes': '1251781'}]}
from led import LED, MAX_BRIGHTNESS def set_all(num, red, green, blue, brightness=MAX_BRIGHTNESS): states = [] for i in range(num): states.append(LED(red, green, blue, brightness)) return states def all_off(num): return set_all(num, 0, 0, 0, 0)
{'content_hash': '24ce121efb93fb4ba9f2a661efd24f8f', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 62, 'avg_line_length': 22.75, 'alnum_prop': 0.6446886446886447, 'repo_name': 'DavidAntliff/apa102', 'id': 'd1828a32dd236378d5b609fee0f852dfe036fa7f', 'size': '273', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'led_list.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '18505'}]}
================================ For this assignment, write an http server that will act as a simple data store. It should respond to GET/POST/PUT/PATCH/DELETE requests for a single resource of your choosing. The data coming in from a post request should be saved to a json file in a data folder in your repository, do not commit your data folder to git. For example if a request is sent to /notes with a body of {noteBody: 'hello world'} the json data in the body should be stored in it's own json file. You can pick a naming scheme for the file but I would recommend using the number of files that you have received so far. Submit as a pull request to your own repository. Rubric: Handles REST requests: 3pts JSON storage: 3pts Tests: 2pts Project Organization and Development Files: 2pts
{'content_hash': '1fd017f40a1a5fc32cd9de307b4774dd', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 641, 'avg_line_length': 66.33333333333333, 'alnum_prop': 0.75, 'repo_name': 'kasimsiddiqui/HTTP_server_simple_persistence', 'id': '2d3097181ad0c0ae6599518e8a7ee678ced8db98', 'size': '829', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '3399'}]}
' 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. Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp <ExportSignatureHelpProvider("PredefinedCastExpressionSignatureHelpProvider", LanguageNames.VisualBasic), [Shared]> Partial Friend Class PredefinedCastExpressionSignatureHelpProvider Inherits AbstractIntrinsicOperatorSignatureHelpProvider(Of PredefinedCastExpressionSyntax) <ImportingConstructor> Public Sub New() End Sub Protected Overrides Function GetIntrinsicOperatorDocumentationAsync(node As PredefinedCastExpressionSyntax, document As Document, cancellationToken As CancellationToken) As ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation)) Return New ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))(GetIntrinsicOperatorDocumentationImplAsync(node, document, cancellationToken)) End Function Private Async Function GetIntrinsicOperatorDocumentationImplAsync(node As PredefinedCastExpressionSyntax, document As Document, cancellationToken As CancellationToken) As Task(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation)) Return SpecializedCollections.SingletonEnumerable(New PredefinedCastExpressionDocumentation(node.Keyword.Kind, Await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(False))) End Function Protected Overrides Function IsTriggerToken(token As SyntaxToken) As Boolean Return token.IsChildToken(Of PredefinedCastExpressionSyntax)(Function(ce) ce.OpenParenToken) End Function Public Overrides Function IsTriggerCharacter(ch As Char) As Boolean Return ch = "("c End Function Public Overrides Function IsRetriggerCharacter(ch As Char) As Boolean Return ch = ")"c End Function Protected Overrides Function IsArgumentListToken(node As PredefinedCastExpressionSyntax, token As SyntaxToken) As Boolean Return node.Keyword <> token AndAlso node.CloseParenToken <> token End Function End Class End Namespace
{'content_hash': '7cda3dd24f3eba5bfe688239efcef120', 'timestamp': '', 'source': 'github', 'line_count': 45, 'max_line_length': 249, 'avg_line_length': 55.644444444444446, 'alnum_prop': 0.7891373801916933, 'repo_name': 'abock/roslyn', 'id': '1a48d05e3573fd6aa77431a7e2f3e064e7c66868', 'size': '2506', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/Features/VisualBasic/Portable/SignatureHelp/PredefinedCastExpressionSignatureHelpProvider.vb', 'mode': '33188', 'license': 'mit', 'language': [{'name': '1C Enterprise', 'bytes': '289100'}, {'name': 'Batchfile', 'bytes': '9059'}, {'name': 'C#', 'bytes': '126276814'}, {'name': 'C++', 'bytes': '5602'}, {'name': 'CMake', 'bytes': '8276'}, {'name': 'Dockerfile', 'bytes': '2450'}, {'name': 'F#', 'bytes': '549'}, {'name': 'PowerShell', 'bytes': '236203'}, {'name': 'Shell', 'bytes': '94929'}, {'name': 'Visual Basic .NET', 'bytes': '70520200'}]}
<?php $test = isset( $_GET['variant-test'] ) ? $_GET['variant-test'] : 'main'; switch($test){ case 'new': require_once('variant/new.php'); break; case 'edit': require_once('variant/edit.php'); break; case 'main': default: require_once('variant/variant.php'); break; }
{'content_hash': '6cc1dfcef8465141ae16882b31a7aa34', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 72, 'avg_line_length': 21.142857142857142, 'alnum_prop': 0.5945945945945946, 'repo_name': '20steps/alexa', 'id': '710d6ae89a30ce9e7a87bad4b436d82c24e0a17d', 'size': '296', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'web/wp-content/plugins/modules/modal/views/variant.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '4889348'}, {'name': 'CoffeeScript', 'bytes': '8023'}, {'name': 'Gherkin', 'bytes': '4336'}, {'name': 'HTML', 'bytes': '357026'}, {'name': 'JavaScript', 'bytes': '9076289'}, {'name': 'PHP', 'bytes': '33450039'}, {'name': 'Perl', 'bytes': '365'}, {'name': 'Ruby', 'bytes': '3054'}, {'name': 'Shell', 'bytes': '30158'}, {'name': 'TypeScript', 'bytes': '35051'}, {'name': 'VCL', 'bytes': '22958'}, {'name': 'XSLT', 'bytes': '5437'}]}
clones all public repositories of a github profile to local fs
{'content_hash': '5afc309e0a962b2f0e5349dc2228df8a', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 62, 'avg_line_length': 62.0, 'alnum_prop': 0.8387096774193549, 'repo_name': 'garmann/playground', 'id': 'fde850d1e75d25d1dc73e6ac35615842f16659f2', 'size': '72', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'python/github-repo-checkout/README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Dockerfile', 'bytes': '394'}, {'name': 'Go', 'bytes': '2566'}, {'name': 'HTML', 'bytes': '16705'}, {'name': 'JavaScript', 'bytes': '5479'}, {'name': 'Python', 'bytes': '18233'}, {'name': 'Ruby', 'bytes': '2336'}, {'name': 'Shell', 'bytes': '1176'}, {'name': 'TSQL', 'bytes': '1834'}]}
package end2end import pb "github.com/poy/talaria/api/v1" //go:generate hel type NodeServer interface { pb.NodeServer }
{'content_hash': '64e82398bc0b6e1e2879e86965bde684', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 41, 'avg_line_length': 13.777777777777779, 'alnum_prop': 0.7580645161290323, 'repo_name': 'apoydence/loggrebutterfly', 'id': '23b140b056383d19bef0714786a31d5ab4ca217e', 'size': '124', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'datanode/internal/end2end/doc.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Go', 'bytes': '192742'}, {'name': 'Protocol Buffer', 'bytes': '2421'}, {'name': 'Shell', 'bytes': '1219'}]}
package com.github.st1hy.countthemcalories.core.meals; import com.github.st1hy.countthemcalories.R; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.junit.Before; import org.junit.Test; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; public class DefaultNamePlTest { DefaultNamePl defaultNameEn; @Before public void setUp() { DateTimeZone.setDefault(DateTimeZone.UTC); defaultNameEn = new DefaultNamePl(); } @Test public void matchDate() throws Exception { assertThat(defaultNameEn.matchDate(new DateTime().withTime(8,0,0,0)), equalTo(R.string.add_meal_name_breakfast)); assertThat(defaultNameEn.matchDate(new DateTime().withTime(12,0,0,0)), equalTo(R.string.add_meal_name_dinner)); assertThat(defaultNameEn.matchDate(new DateTime().withTime(16,0,0,0)), equalTo(R.string.add_meal_name_dinner)); assertThat(defaultNameEn.matchDate(new DateTime().withTime(17,0,0,0)), equalTo(R.string.add_meal_name_supper)); assertThat(defaultNameEn.matchDate(new DateTime().withTime(0,0,0,0)), equalTo(R.string.add_meal_name_supper)); } }
{'content_hash': '15db395b61576638a7f388920b88fd18', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 78, 'avg_line_length': 33.21052631578947, 'alnum_prop': 0.6862123613312203, 'repo_name': 'st1hy/Count-Them-Calories', 'id': 'ee4897c41e62cb65f4fe0d3db75bb73b20118fc6', 'size': '1262', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'app/src/test/java/com/github/st1hy/countthemcalories/core/meals/DefaultNamePlTest.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '780367'}]}
ACCEPTED #### According to NUB Generator [autonym] #### Published in null #### Original name null ### Remarks null
{'content_hash': '89f56c52d78acb06e17e1e8b193afcca', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 23, 'avg_line_length': 9.076923076923077, 'alnum_prop': 0.6779661016949152, 'repo_name': 'mdoering/backbone', 'id': '60b97884fc7d447b3233bcbb479d7fe6c075e796', 'size': '178', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Pteridophyta/Polypodiopsida/Hymenophyllales/Hymenophyllaceae/Hymenophyllum/Hymenophyllum hirsutum/Hymenophyllum ciliatum ciliatum/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
<?xml version="1.0" encoding="UTF-8"?> <ivy-module version="2.0" xmlns:e="http://ant.apache.org/ivy/extra"> <info organisation="org.scala-sbt.temp" module="temp-module-98ec89c315ed408f615fff2c4774286d17323b01" revision="1.1.7" status="integration" publication="20180731110715" /> <configurations> <conf name="compile" visibility="public" description=""/> <conf name="runtime" visibility="public" description="" extends="compile"/> <conf name="test" visibility="public" description="" extends="runtime"/> <conf name="provided" visibility="public" description=""/> <conf name="optional" visibility="public" description=""/> </configurations> <publications> </publications> <dependencies> <dependency org="org.scala-sbt" name="compiler-bridge_2.12" rev="1.1.7" conf="compile->default(compile)"> <artifact name="compiler-bridge_2.12" type="src" ext="jar" conf="*" e:classifier="sources"/> </dependency> </dependencies> </ivy-module>
{'content_hash': '650d078e4607e24c11d53184eac16278', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 107, 'avg_line_length': 41.82608695652174, 'alnum_prop': 0.7110187110187111, 'repo_name': 'Bigsby/PoC', 'id': 'c9218f98e57ff80e3ff80f42283f5e138ff1ec9e', 'size': '962', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'java/sbting/first-play/target/scala-2.12/resolution-cache/org.scala-sbt.temp/temp-module-98ec89c315ed408f615fff2c4774286d17323b01/1.1.7/resolved.xml.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP.NET', 'bytes': '1063'}, {'name': 'Assembly', 'bytes': '1596'}, {'name': 'Batchfile', 'bytes': '239'}, {'name': 'C', 'bytes': '3627'}, {'name': 'C#', 'bytes': '1224655'}, {'name': 'C++', 'bytes': '3472'}, {'name': 'CSS', 'bytes': '463261'}, {'name': 'Dockerfile', 'bytes': '604'}, {'name': 'EJS', 'bytes': '551'}, {'name': 'F#', 'bytes': '32014'}, {'name': 'Gherkin', 'bytes': '306'}, {'name': 'HTML', 'bytes': '1768740'}, {'name': 'Java', 'bytes': '6809'}, {'name': 'JavaScript', 'bytes': '19893309'}, {'name': 'Less', 'bytes': '82171'}, {'name': 'Makefile', 'bytes': '1185'}, {'name': 'Perl', 'bytes': '414'}, {'name': 'PowerShell', 'bytes': '18992'}, {'name': 'Python', 'bytes': '9118'}, {'name': 'Ruby', 'bytes': '953'}, {'name': 'Rust', 'bytes': '45'}, {'name': 'SCSS', 'bytes': '80'}, {'name': 'Scala', 'bytes': '14006'}, {'name': 'Shell', 'bytes': '469'}, {'name': 'TypeScript', 'bytes': '89628'}, {'name': 'Visual Basic .NET', 'bytes': '13131'}, {'name': 'Vue', 'bytes': '11685'}, {'name': 'XSLT', 'bytes': '62979'}]}
http_path = "/" css_dir = "css" sass_dir = "scss" images_dir = "images" javascripts_dir = "js" # You can select your preferred output style here (can be overridden via the command line): output_style = :expanded #:compressed #:compact # To enable relative paths to assets via compass helper functions. Uncomment: relative_assets = true # To disable debugging comments that display the original location of your selectors. Uncomment: line_comments = false # If you prefer the indented syntax, you might want to regenerate this # project again passing --syntax sass, or you can uncomment this: # preferred_syntax = :sass # and then run: # sass-convert -R --from scss --to sass sass scss && rm -rf sass && mv scss sass
{'content_hash': '067f69a088f73733a1d295232c16214e', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 96, 'avg_line_length': 31.956521739130434, 'alnum_prop': 0.7238095238095238, 'repo_name': 'jo32/Retina-Sprites-for-Compass', 'id': '4e19bf989371379f4f5d7e82f23e9bfcab524f0e', 'size': '839', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'demo/config.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '11505'}, {'name': 'HTML', 'bytes': '563'}, {'name': 'Ruby', 'bytes': '839'}]}
using System.Collections.Generic; using System.Text; using SchoolSystemLogic.Core; namespace SchoolSystemLogic.Commands { public class StudentListMarksCommand : ICommand { public string Execute(IList<string> parameters) { var indexOfTheStudent = int.Parse(parameters[0]); var marks = Engine.Students[indexOfTheStudent].ListMarks(); var result = new StringBuilder(); if (marks.Length == 0) { result.Append("This student has no marks."); } else { result.AppendLine("The student has these marks:"); result.AppendLine(marks); } return result.ToString(); } } }
{'content_hash': '9836c370df33b1dc6003136cd33783b3', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 71, 'avg_line_length': 26.379310344827587, 'alnum_prop': 0.5607843137254902, 'repo_name': 'RuzmanovDev/Telerik-Academy-Season-2016-2017', 'id': 'b43a72cd516f2cc472e0798473e24c90fcd9a66b', 'size': '767', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Modul-II/01.High-Quality-Code/03.HQC-Part-Two/Exam/SchoolSystem/Exam/SchoolSystemLogic/Commands/StudentListMarksCommand.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '156062'}, {'name': 'C#', 'bytes': '6854317'}, {'name': 'CSS', 'bytes': '151173'}, {'name': 'CoffeeScript', 'bytes': '3700'}, {'name': 'HTML', 'bytes': '3848453'}, {'name': 'JavaScript', 'bytes': '2098645'}, {'name': 'PowerShell', 'bytes': '287'}, {'name': 'SQLPL', 'bytes': '4671'}, {'name': 'XSLT', 'bytes': '3306'}]}
<?php namespace SilverStripe\Security; use Controller; use Form; use Member; use Object; /** * Abstract base class for an authentication method * * This class is used as a base class for the different authentication * methods like {@link MemberAuthenticator} or {@link OpenIDAuthenticator}. * * @author Markus Lanthaler <[email protected]> * @package framework * @subpackage security */ abstract class Authenticator extends Object { /** * This variable holds all full namespaced authenticators that should be used * * @var array */ private static $authenticators = array('SilverStripe\Security\MemberAuthenticator'); /** * Used to influence the order of authenticators on the login-screen * (default shows first). * * @var string */ private static $default_authenticator = 'SilverStripe\Security\MemberAuthenticator'; /** * Method to authenticate an user * * @param array $RAW_data Raw data to authenticate the user * @param Form $form Optional: If passed, better error messages can be * produced by using * {@link Form::sessionMessage()} * * @return bool|Member Returns FALSE if authentication fails, otherwise * the member object */ public static function authenticate($RAW_data, Form $form = null) { } /** * Method that creates the login form for this authentication method * * @param Controller $controller The parent controller, necessary to create the * appropriate form action tag * * @return Form Returns the login form to use with this authentication * method */ public static function get_login_form(Controller $controller) { } /** * Method that creates the re-authentication form for the in-CMS view * * @param Controller $controller */ public static function get_cms_login_form(Controller $controller) { } /** * Determine if this authenticator supports in-cms reauthentication * * @return bool */ public static function supports_cms() { return false; } /** * Get the name of the authentication method * * @return string Returns the name of the authentication method. */ public static function get_name() { } public static function register($authenticator) { self::register_authenticator($authenticator); } /** * Register a new authenticator * * The new authenticator has to exist and to be derived from the * {@link Authenticator}. * Every authenticator can be registered only once. * * @param string $authenticator Name of the authenticator class to * register * * @return bool Returns TRUE on success, FALSE otherwise. */ public static function register_authenticator($authenticator) { $authenticator = trim($authenticator); if (class_exists($authenticator) === false) { return false; } if (is_subclass_of($authenticator, 'Authenticator') === false) { return false; } if (in_array($authenticator, self::$authenticators, null) === false) { if (call_user_func(array($authenticator, 'on_register')) === true) { self::$authenticators[] = $authenticator; } else { return false; } } return true; } public static function unregister($authenticator) { self::unregister_authenticator($authenticator); } /** * Remove a previously registered authenticator * * @param string $authenticator Name of the authenticator class to register * * @return bool Returns TRUE on success, FALSE otherwise. */ public static function unregister_authenticator($authenticator) { if (call_user_func(array($authenticator, 'on_unregister')) === true && in_array($authenticator, self::$authenticators, null) ) { unset(self::$authenticators[array_search($authenticator, self::$authenticators, null)]); } } /** * Check if a given authenticator is registered * * @param string $authenticator Name of the authenticator class to check * * @return bool Returns TRUE if the authenticator is registered, FALSE * otherwise. */ public static function is_registered($authenticator) { return in_array($authenticator, self::$authenticators, null); } /** * Get all registered authenticators * * @return array Returns an array with the class names of all registered * authenticators. */ public static function get_authenticators() { // put default authenticator first (mainly for tab-order on loginform) if ($key = array_search(self::$default_authenticator, self::$authenticators, null)) { unset(self::$authenticators[$key]); array_unshift(self::$authenticators, self::$default_authenticator); } return self::$authenticators; } /** * Set a default authenticator (shows first in tabs) * * @param string */ public static function set_default_authenticator($authenticator) { self::$default_authenticator = $authenticator; } /** * @return string */ public static function get_default_authenticator() { return self::$default_authenticator; } /** * Callback function that is called when the authenticator is registered * * Use this method for initialization of a newly registered authenticator. * Just overload this method and it will be called when the authenticator * is registered. * <b>If the method returns FALSE, the authenticator won't be * registered!</b> * * @return bool Returns TRUE on success, FALSE otherwise. */ protected static function on_register() { return true; } /** * Callback function that is called when an authenticator is removed. * * @return bool */ protected static function on_unregister() { return true; } }
{'content_hash': '5633d6e839d8db5ecfdb8a8c160b881b', 'timestamp': '', 'source': 'github', 'line_count': 238, 'max_line_length': 91, 'avg_line_length': 24.071428571428573, 'alnum_prop': 0.6844126374585443, 'repo_name': 'CasaLaguna/silverstripe-security', 'id': 'c1169657f9287ceb93143c97c360cdcad04c39f4', 'size': '5729', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'code/Authentication/Authenticator.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'PHP', 'bytes': '386361'}]}
package php.runtime; import org.junit.Assert; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.runners.MethodSorters; import php.runtime.memory.*; @RunWith(JUnit4.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class MemoryTest { @Test public void testNull(){ Memory memory = Memory.NULL; Assert.assertEquals(Memory.Type.NULL, memory.type); Assert.assertFalse(memory.toBoolean()); Assert.assertEquals("", memory.toString()); Assert.assertEquals(0.0, memory.toDouble(), 0.000001); Assert.assertEquals(0, memory.toLong()); Assert.assertNotNull(memory.toNumeric()); Assert.assertEquals(Memory.Type.INT, memory.toNumeric().type); Assert.assertEquals(0, memory.toNumeric().toLong()); Assert.assertEquals(memory, memory.toImmutable()); Assert.assertTrue(memory.isImmutable()); } @Test public void testFalse(){ Memory memory = Memory.FALSE; Assert.assertEquals(Memory.Type.BOOL, memory.type); Assert.assertFalse(memory.toBoolean()); Assert.assertEquals("", memory.toString()); Assert.assertEquals(0.0, memory.toDouble(), 0.000001); Assert.assertEquals(0, memory.toLong()); Assert.assertNotNull(memory.toNumeric()); Assert.assertEquals(Memory.Type.INT, memory.toNumeric().type); Assert.assertEquals(0, memory.toNumeric().toLong()); Assert.assertEquals(memory, memory.toImmutable()); Assert.assertTrue(memory.isImmutable()); } @Test public void testTrue(){ Memory memory = Memory.TRUE; Assert.assertEquals(Memory.Type.BOOL, memory.type); Assert.assertTrue(memory.toBoolean()); Assert.assertEquals("1", memory.toString()); Assert.assertEquals(1.0, memory.toDouble(), 0.000001); Assert.assertEquals(1, memory.toLong()); Assert.assertNotNull(memory.toNumeric()); Assert.assertEquals(Memory.Type.INT, memory.toNumeric().type); Assert.assertEquals(1, memory.toNumeric().toLong()); Assert.assertEquals(memory, memory.toImmutable()); Assert.assertTrue(memory.isImmutable()); } @Test public void testLong(){ LongMemory memory = new LongMemory(100); Assert.assertEquals(Memory.Type.INT, memory.type); Assert.assertTrue(memory.toBoolean()); Assert.assertEquals("100", memory.toString()); Assert.assertEquals(100, memory.toDouble(), 0.000001); Assert.assertEquals(100, memory.toLong()); Assert.assertNotNull(memory.toNumeric()); Assert.assertEquals(Memory.Type.INT, memory.toNumeric().type); Assert.assertEquals(100, memory.toNumeric().toLong()); Assert.assertEquals(memory, memory.toImmutable()); Assert.assertTrue(memory.isImmutable()); } @Test public void testDouble(){ DoubleMemory memory = new DoubleMemory(50); Assert.assertEquals(Memory.Type.DOUBLE, memory.type); Assert.assertTrue(memory.toBoolean()); Assert.assertEquals("50", memory.toString()); Assert.assertEquals(50, memory.toDouble(), 0.000001); Assert.assertEquals(50, memory.toLong()); Assert.assertNotNull(memory.toNumeric()); Assert.assertEquals(Memory.Type.DOUBLE, memory.toNumeric().type); Assert.assertEquals(50, memory.toNumeric().toLong()); Assert.assertEquals(memory, memory.toImmutable()); Assert.assertTrue(memory.isImmutable()); } @Test public void testString(){ StringMemory memory = new StringMemory("foobar"); Assert.assertEquals(Memory.Type.STRING, memory.type); Assert.assertTrue(memory.toBoolean()); Assert.assertEquals("foobar", memory.toString()); Assert.assertEquals(0.0, memory.toDouble(), 0.000001); Assert.assertEquals(0, memory.toLong()); Assert.assertNotNull(memory.toNumeric()); Assert.assertEquals(Memory.Type.INT, memory.toNumeric().type); Assert.assertEquals(0, memory.toNumeric().toLong()); Assert.assertEquals(memory, memory.toImmutable()); Assert.assertTrue(memory.isImmutable()); Assert.assertNull(StringMemory.toLong("-")); Assert.assertEquals(-1, StringMemory.toLong("-1").toLong()); Assert.assertEquals(32, StringMemory.toLong("32").toLong()); Assert.assertTrue(new BinaryMemory(new byte[]{1,2}).toBoolean()); Assert.assertFalse(new BinaryMemory(new byte[]{}).toBoolean()); Assert.assertFalse(new BinaryMemory().toBoolean()); Assert.assertFalse(new BinaryMemory(new byte[]{'0'}).toBoolean()); Assert.assertEquals(StringMemory.valueOf("-").toNumeric().toLong(), 0); Assert.assertEquals(StringMemory.valueOf("-").toLong(), 0); } @Test public void testReference(){ ReferenceMemory memory = new ReferenceMemory(Memory.TRUE); Assert.assertEquals(Memory.Type.REFERENCE, memory.type); Assert.assertTrue(memory.toBoolean()); Assert.assertEquals("1", memory.toString()); Assert.assertEquals(1, memory.toDouble(), 0.000001); Assert.assertEquals(1, memory.toLong()); Assert.assertNotNull(memory.toNumeric()); Assert.assertEquals(Memory.Type.INT, memory.toNumeric().type); Assert.assertEquals(1, memory.toNumeric().toLong()); Assert.assertNotEquals(memory, memory.toImmutable()); Assert.assertEquals(Memory.TRUE, memory.toImmutable()); Assert.assertFalse(memory.isImmutable()); } }
{'content_hash': 'cc2290b486b161933e9b12a4c53e4943', 'timestamp': '', 'source': 'github', 'line_count': 153, 'max_line_length': 79, 'avg_line_length': 37.03921568627451, 'alnum_prop': 0.6656079054173284, 'repo_name': 'jphp-compiler/jphp', 'id': '8fd727785024cbdb6904cef7e30d4edb33edeff8', 'size': '5667', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'jphp-core/tests/php/runtime/MemoryTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '2124'}, {'name': 'HTML', 'bytes': '4259'}, {'name': 'Inno Setup', 'bytes': '2041'}, {'name': 'Java', 'bytes': '4396883'}, {'name': 'PHP', 'bytes': '1570052'}, {'name': 'Shell', 'bytes': '5234'}]}
package controllers import ( "github.com/revel/examples/chat/app/chatroom" "github.com/revel/revel" ) type LongPolling struct { *revel.Controller } func (c LongPolling) Room(user string) revel.Result { chatroom.Join(user) return c.Render(user) } func (c LongPolling) Say(user, message string) revel.Result { chatroom.Say(user, message) return nil } func (c LongPolling) WaitMessages(lastReceived int) revel.Result { subscription := chatroom.Subscribe() defer subscription.Cancel() // See if anything is new in the archive. var events []chatroom.Event for _, event := range subscription.Archive { if event.Timestamp > lastReceived { events = append(events, event) } } // If we found one, grand. if len(events) > 0 { return c.RenderJSON(events) } // Else, wait for something new. event := <-subscription.New return c.RenderJSON([]chatroom.Event{event}) } func (c LongPolling) Leave(user string) revel.Result { chatroom.Leave(user) return c.Redirect(Application.Index) }
{'content_hash': '4e9e12d93a9c60b9b959157cdbb905cc', 'timestamp': '', 'source': 'github', 'line_count': 47, 'max_line_length': 66, 'avg_line_length': 21.425531914893618, 'alnum_prop': 0.7239324726911619, 'repo_name': 'zhyhang/gofirst', 'id': '49a238d3f1041c63a492152cdbc23955ad0a0c38', 'size': '1007', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'example/revel/chat/app/controllers/longpolling.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2056'}, {'name': 'Go', 'bytes': '95000'}, {'name': 'HTML', 'bytes': '10530'}, {'name': 'JavaScript', 'bytes': '1192'}]}
ACCEPTED #### According to Index Fungorum #### Published in Nuovo Giorn. Bot. Ital. 8: 161 (1892) #### Original name Cytospora oleina Berl. ### Remarks null
{'content_hash': 'a79765625d8b2727b7002af9c65a696c', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 37, 'avg_line_length': 12.307692307692308, 'alnum_prop': 0.6875, 'repo_name': 'mdoering/backbone', 'id': 'f4a467fe14952d23a5ff507a1d6ca73d02ca5221', 'size': '206', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Fungi/Ascomycota/Sordariomycetes/Diaporthales/Valsaceae/Cytospora/Cytospora oleina/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
CREATE TABLE `users` ( `id` int unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY, `access` int NOT NULL DEFAULT 1, `created` int(10) unsigned NOT NULL, `last_seen` int(10) unsigned NOT NULL ) ENGINE='InnoDB';
{'content_hash': '5823964ee6e3a982725d5ecd1c16311e', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 55, 'avg_line_length': 34.666666666666664, 'alnum_prop': 0.7211538461538461, 'repo_name': 'daGrevis/daGrevis.lv-PHP', 'id': '9226aa667ca66671bd2d474251617a8fb54d085b', 'size': '208', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'application/sql/users.sql', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '3145'}, {'name': 'PHP', 'bytes': '50433'}, {'name': 'Perl', 'bytes': '529'}]}
#ifndef _flint_h_ #define _flint_h_ #include <math.h> /* For real-time applications you need big integers: the number of recorded samples will exceed the maximum 32-bit signed integer after only 13.5 hours. So having int64_t would be best, and that is indeed what Praat uses for these same purposes, but the Vokaturi library has to be able to run with old compilers and linkers. Not all old compilers support int64_t, and not all old linkers support 64-bit division without calling external functions. So we simply employ the type "double", which can contain signed integers up to 54 bits. */ typedef double flint; /* On these high-precision "integers", the integer division (with its rounding down) and the modulo function cannot be performed with the usual operator symbols for integer types (which are "/" and "%", respectively), so for those operations we use inline functions instead. */ inline static flint flint_div (flint a, flint b) { return floor (a / b); } inline static flint flint_mod (flint a, flint b) { return a - floor (a / b) * b; } /* End of file flint.h */ #endif
{'content_hash': '68d3df25c82141c73c7e3d6fb0ac1dab', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 82, 'avg_line_length': 37.733333333333334, 'alnum_prop': 0.7217314487632509, 'repo_name': 'equilibrium-catalyst/yadayada-rest-api', 'id': '978dfc7f3308bc7a3097e124e2be4b57d0e529a9', 'size': '1940', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'restapi/speech/src/flint.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '21030'}]}
namespace PetFinder.Data.Migrations { using System.Data.Entity.Migrations; using System.Linq; public sealed class Configuration : DbMigrationsConfiguration<AppDbContext> { public Configuration() { this.AutomaticMigrationsEnabled = true; this.AutomaticMigrationDataLossAllowed = false; } protected override void Seed(AppDbContext context) { if (context.Users.Any()) { return; } var dataSeed = new DataSeed(context); dataSeed.SeedRoles(); dataSeed.SeedAdmin(); dataSeed.SeedUsers(); dataSeed.SeedRegions(); dataSeed.SeedPostCategories(); dataSeed.SeedPets(); dataSeed.SeedPostsWithComments( context.Users.ToList(), context.PostCategories.ToList(), context.Pets.ToList(), context.Regions.ToList()); dataSeed.SeedImages(context.Posts.ToList()); } } }
{'content_hash': '991f9cb39b01a28858e3f71c18617a1f', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 79, 'avg_line_length': 30.02777777777778, 'alnum_prop': 0.5504162812210915, 'repo_name': 'DennyGD/PetFinder', 'id': 'ce7745cbd097fdea31bc2926bab80a7c0a1ea2ec', 'size': '1083', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Source/Data/PetFinder.Data/Migrations/Configuration.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '104'}, {'name': 'C#', 'bytes': '232406'}, {'name': 'CSS', 'bytes': '513'}, {'name': 'JavaScript', 'bytes': '1116'}]}
using SurgSim::Graphics::OsgTexture1d; OsgTexture1d::OsgTexture1d() : OsgTexture(new osg::Texture1D()) { } void OsgTexture1d::setSize(int width) { getOsgTexture1d()->setTextureWidth(width); } void OsgTexture1d::getSize(int* width) const { *width = getOsgTexture1d()->getTextureWidth(); if (*width == 0 && getOsgTexture()->getNumImages() > 0) { *width = getOsgTexture()->getImage(0)->s(); } }
{'content_hash': '272594718947a868e6f9dcfae58792f1', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 63, 'avg_line_length': 21.157894736842106, 'alnum_prop': 0.6965174129353234, 'repo_name': 'simquest/opensurgsim', 'id': 'e0263cd888c5839f4b7f04b2b05afa9a4ade5175', 'size': '1099', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'SurgSim/Graphics/OsgTexture1d.cpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '75121'}, {'name': 'C++', 'bytes': '7422720'}, {'name': 'CMake', 'bytes': '198446'}, {'name': 'GLSL', 'bytes': '72925'}, {'name': 'JavaScript', 'bytes': '2659'}, {'name': 'Python', 'bytes': '56744'}]}
package com.asakusafw.testdriver.html; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import java.io.File; import java.io.IOException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.asakusafw.testdriver.core.DataModelDefinition; import com.asakusafw.testdriver.core.Difference; import com.asakusafw.testdriver.core.DifferenceSink; import com.asakusafw.testdriver.core.DifferenceSinkFactory; import com.asakusafw.testdriver.core.TestContext; import com.asakusafw.testdriver.core.TestToolRepository; import com.asakusafw.testdriver.excel.Simple; import com.asakusafw.testdriver.model.SimpleDataModelDefinition; /** * Test for {@link HtmlDifferenceSinkProvider}. */ public class HtmlDifferenceSinkProviderTest { static final DataModelDefinition<Simple> SIMPLE = new SimpleDataModelDefinition<>(Simple.class); /** * temporary folder. */ @Rule public final TemporaryFolder temp = new TemporaryFolder(); /** * Load the provider via SPI. * @throws Exception if failed */ @Test public void spi() throws Exception { TestToolRepository repo = new TestToolRepository(getClass().getClassLoader()); File file = temp.newFile("example.html"); file.delete(); DifferenceSinkFactory factory = repo.getDifferenceSinkFactory(file.toURI()); try (DifferenceSink sink = factory.createSink(SIMPLE, new TestContext.Empty())) { Simple expected = new Simple(); expected.text = "expected"; Simple actual = new Simple(); actual.text = "actual"; sink.put(new Difference( SIMPLE.toReflection(expected), SIMPLE.toReflection(actual), "testing")); } assertThat(file.exists(), is(true)); } /** * Attempt to load the provider via SPI, but its extension is wrong. * @throws Exception if failed */ @Test public void spi_wrong_extension() throws Exception { TestToolRepository repo = new TestToolRepository(getClass().getClassLoader()); File file = temp.newFile("example.invalid"); file.delete(); DifferenceSinkFactory factory = repo.getDifferenceSinkFactory(file.toURI()); try (DifferenceSink sink = factory.createSink(SIMPLE, new TestContext.Empty())) { sink.close(); fail(); } catch (IOException e) { // ok. } } }
{'content_hash': '06ba7d52dc3272f5a8656026c07a2459', 'timestamp': '', 'source': 'github', 'line_count': 81, 'max_line_length': 100, 'avg_line_length': 31.19753086419753, 'alnum_prop': 0.66798575385833, 'repo_name': 'akirakw/asakusafw', 'id': 'f7eb1cebdf6f0b727632f7d81ab06632039a0382', 'size': '3139', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'testing-project/asakusa-test-data-provider/src/test/java/com/asakusafw/testdriver/html/HtmlDifferenceSinkProviderTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '31'}, {'name': 'CSS', 'bytes': '650'}, {'name': 'Groovy', 'bytes': '275943'}, {'name': 'Java', 'bytes': '12250766'}, {'name': 'Lex', 'bytes': '12506'}, {'name': 'Shell', 'bytes': '10149'}]}
//Love on the web var Love; Love = Love || defineLove(); //TODO: Look into Web Audio API for more advanced compatibility Love.Audio = (function() { function Audio() { define(this); } function define(self) { var ctx = new AudioContext() || new webkitAudioContext(); var volNode = ctx.createGain(); volNode.connect(ctx.destination); var panNode = ctx.createPanner(); panNode.connect(volNode); var orientation = [ 0, 0, -1, 0, 1, 0 ]; var position = [ 0, 0, 0 ]; var velocity = [ 0, 0, 0 ]; self.getDistanceModel = function() { return panNode.distanceModel; }; self.getDopplerScale = function() { return 0; }; self.getOrientation = function() { return orientation; }; self.getPosition = function() { return position; }; self.getSourceCount = function() { return 0; }; self.getVelocity = function() { return velocity; }; self.getVolume = function() { return volNode.gain.volume; }; self.newSource = function(name) { return new Love.Audio.Source(name, ctx); }; self.pause = function(source) { }; self.play = function(source) { }; self.resume = function(source) { }; self.rewind = function(source) { }; self.setDistanceModel = function() { unimplemented("love.audio.setDistanceModel"); }; self.setDopplerScale = function() { unimplemented("love.audio.setDopplerScale"); }; self.setOrientation = function() { unimplemented("love.audio.setOrientation"); }; self.setPosition = function() { unimplemented("love.audio.setPosition"); }; self.setVelocity = function() { unimplemented("love.audio.setVelocity"); }; self.setVolume = function(volume) { volNode.gain.volume = volume; }; self.stop = function(source) { }; } return Audio; })(); Love.Audio.Source = (function() { function ASource(path, ctx) { this.panner = ctx.createPanner(); var req = new XMLHttpRequest(); req.open("GET", "lua/" + path, true); req.responseType = "arraybuffer"; req.onload = wrap(this, function(e) { ctx.decodeAudioData(req.response, wrap(this, function(buffer) { this.buffer = buffer; })); }); req.send(); } ASource.prototype.clone = function(self) { }; ASource.prototype.getAttenuationDistance = function(self) { unimplemented("Source:getAttenuationDistance"); }; ASource.prototype.getChannels = function(self) { if(self.buffer == null) return 0; return self.buffer.numberOfChannels; }; ASource.prototype.getCone = function() { }; return ASource; })();;Love = Love || defineLove(); Love.Color = (function() { function Color(r, g, b, a) { if (typeof r != "number") { if(typeof r == "string") { var d = parseInt(/#([A-Fa-f0-9]*)/.exec(r)[1], 16); this.r = d >> 16; this.g = (d >> 8) & 255; this.b = d & 255; this.a = 255; } else { this.r = r.getMember(1) || 0; this.g = r.getMember(2) || 0; this.b = r.getMember(3) || 0; this.a = r.getMember(4) || 255; } } else { this.r = r || 0; this.g = g || 0; this.b = b || 0; this.a = a || 255; } //this.as_string = (this.r << 16 | this.g << 8 | this.b).toString(16); this.as_string = "rgb(" + this.r + "," + this.g + "," + this.b + ")"; } return Color; })();;Love = Love || defineLove(); Love.Event = (function() { function Event() { define(this); this.queue = []; } function define(self) { self.clear = function() { self.queue = []; }; self.push = function(eType, a1, a2, a3, a4) { var event = [eType, a1, a2, a3, a4]; self.queue.push(event); }; self.quit = function() { self.push("quit"); }; self.pump = function() { /* Uneeded In JS */ }; self.poll = function() { unimplemented("love.event.poll"); }; self.wait = function() { unimplemented("love.event.wait"); } } return Event; })(); ;Love = Love || defineLove(); //Most of FileSystem can't be reinplemented but local storage will help Love.FileSystem = (function() { function FileSystem() { define(this); } function define(self) { //Things that will work self.append = function(name, data) { localStorage[name] += data; }; self.areSymlinksEnabled = function() { return false; }; self.createDirectory = function(name) { //Unneeded in JS }; self.exists = function(name) { return localStorage.getItem(name) != null; }; self.getAppdataDirectory = function() { return ""; }; self.getDirectoryItems = function(dir) { return new shine.Table(); }; self.getIdentity = function() { return ""; }; self.getSaveDirectory = function() { return ""; }; self.getSourceBaseDirectory = function() { return ""; }; self.getUserDirectory = function() { return ""; }; self.getWorkingDirectory = function() { return ""; }; self.init = function() { //Unneeded in JS }; self.isDirectory = function(name) { return false; }; self.isFile = function(name) { return typeof localStorage[name] == "string"; }; self.isFused = function() { return false; }; self.isSymlink = function() { return false; }; self.lines = function(filename) { return new shine.Table(localStorage[filename].split("\n")); }; self.read = function(filename) { return localStorage[filename]; }; self.remove = function(name) { localStorage.removeItem(name); }; self.write = function(name, data) { localStorage.setItem(name, data); }; //Things that won't work self.getLastModified = function() { neverimplemented("love.filesystem.getLastModified"); }; self.getRealDirectory = function() { neverimplemented("love.filesystem.getRealDirectory"); }; self.getSize = function() { neverimplemented("love.filesystem.getSize"); }; self.load = function() { neverimplemented("love.filesystem.load"); }; self.mount = function() { neverimplemented("love.filesystem.mount"); }; self.newFile = function() { neverimplemented("love.filesystem.newFile"); }; self.newFileData = function() { neverimplemented("love.filesystem.newFileData"); }; self.setIdentity = function() { neverimplemented("love.filsystem.setIdentity"); }; self.setSource = function() { neverimplemented("love.filesystem.setSource"); }; self.setSymlinkEnabled = function() { neverimplemented("love.filesystem.setSymlinkEnabled"); }; self.unmount = function() { neverimplemented("love.filesystem.unmount"); }; } return FileSystem; })(); ;Love = Love || defineLove(); Love.Font = (function() { function Font() { define(this); } function define(self) { self.newGlyphData = function() { neverimplemented("love.font.newGlyphData"); }; self.newRasterizer = function() { neverimplemented("love.font.newRasterizer"); }; } return Font; })(); ;Love = Love || defineLove(); Love.Graphics = (function() { function Graphics(width, height) { define(this); if(Love.element == null) { this.canvas = new Love.Graphics.Canvas2D(width, height, null, this); document.body.appendChild(this.canvas.elem); Love.element = this.canvas.elem; } else { this.canvas = new Love.Graphics.Canvas2D(width, height, Love.element, this); } //Show the canvas that will be on screen this.canvas.elem.style.display = "block"; this.__mainCanvas = this.canvas; this.ctx = this.canvas.ctx; this.__matrix = this.canvas.matrix; this.setColor(255, 255, 255); this.setBackgroundColor(0, 0, 0); } function define(self) { self.arc = function(mode, x, y, rad, a1, a2, segments) { segments = segments || 10; var ctx = self.ctx, interval, i, cx, cy; ctx.beginPath(); if(mode == "fill") { ctx.moveTo(x, y); } else { ctx.moveTo(x + Math.cos(a1) * rad, y + Math.sin(a1) * rad); } interval = (a2 - a1) / segments; for(i = a1; i <= a2; i += interval) { cx = Math.cos(i) * rad + x; cy = Math.sin(i) * rad + y; ctx.lineTo(cx, cy); } if(mode == "fill") { ctx.closePath(); ctx.fill(); } else { ctx.stroke(); } }; self.circle = function(mode, x, y, rad, segments) { if(rad < 0) return; self.arc(mode, x, y, rad, 0, Math.PI * 2, segments); }; self.clear = function(r, g, b, a) { var c, ctx = self.ctx; if(r == null) { c = self.canvas.backgroundColor; } else { if(typeof r == "number") { c = new Love.Color(r, g, b, a); } else { c = new Love.Color(r); } } if(c.a == 0) { return; } ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.fillStyle = c.as_string; ctx.globalAlpha = c.a / 255; ctx.fillRect(0, 0, self.canvas.width, self.canvas.height); ctx.restore(); }; self.draw = function(drawable, quad, x, y, r, sx, sy, ox, oy, kx, ky) { if(typeof quad == "number") { __drawWhole(drawable, quad || 0, x || 0, y || 0, r || 1, sx || 1, sy || 0, ox || 0, oy || 0, kx || 0); } else { __drawWithQuad(drawable, quad, x || 0, y || 0, r || 0, sx || 1, sy || 1, ox || 0, oy || 0, kx || 0, ky || 0); } }; var __drawWhole = function(drawable, x, y, r, sx, sy, ox, oy, kx, ky) { var ctx = self.ctx; var c = r == 0 ? 1 : Math.cos(r); var s = r == 0 ? 0 : Math.sin(r); var matrix = self.__matrix.x($M([ [sx * c - kx * sy * s, ky * sx * c - sy * s, x - ox], [sx * s + kx * sy * c, ky * sx * s + sy * c, y - oy], [0, 0, 1 ] ])); ctx.save(); self.__updateTransform(matrix); ctx.drawImage(drawable.elem, 0, 0); ctx.restore(); }; var __drawWithQuad = function(drawable, quad, x, y, r, sx, sy, ox, oy, kx, ky) { var ctx = self.ctx, w = drawable.getWidth(), h = drawable.getHeight(); var c = r == 0 ? 1 : Math.cos(r); var s = r == 0 ? 0 : Math.sin(r); var matrix = self.__matrix.x($M([ [sx * c - kx * sy * s, ky * sx * c - sy * s, x - ox], [sx * s + kx * sy * c, ky * sx * s + sy * c, y - oy], [0, 0, 1 ] ])); ctx.save(); self.__updateTransform(matrix); ctx.drawImage(drawable.elem, quad.x, quad.y, quad.w, quad.h, 0, 0, w, h); ctx.restore(); }; self.line = function(x1, y1, x2, y2) { var ctx = self.ctx; ctx.beginPath(); if(typeof x1 == "number") { ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke(); } else { ctx.moveTo(x1.getMember(1), x1.getMember(2)); ctx.lineTo(x1.getMember(3), x1.getMember(4)); ctx.stroke(); } ctx.closePath(); }; self.point = function(x, y) { self.ctx.fillRect(x, y, 1, 1); }; self.polygon = function(mode, verts) { var ctx = self.ctx, i, x, y; ctx.beginPath(); ctx.moveTo(verts.getMember(1), verts.getMember(2)); for(i = 3; i <= verts.__shine.numValues.length; i += 2) { x = verts.getMember(i); y = verts.getMember(i + 1); ctx.lineTo(x, y); } ctx.closePath(); if(mode == "fill") { ctx.fill(); } else { ctx.stroke(); } }; self.present = function() { /*Uneeded in JS*/ }; self.print = function(text, x, y, r, sx, sy, ox, oy, kx, ky) { }; self.printf = function(text, x, y, limit, align, r, sx, sy, ox, oy, kx, ky) { }; self.rectangle = function(mode, x, y, w, h) { if(mode == "fill") { self.ctx.fillRect(x, y, w, h); } else { self.ctx.strokeRect(x, y, w, h); } }; //Transformations self.__updateTransform = function(m) { var matrix = m || self.__matrix; self.ctx.setTransform(matrix.e(1, 1), matrix.e(2, 1), matrix.e(1, 2), matrix.e(2, 2), matrix.e(1, 3), matrix.e(2, 3)); }; self.origin = function() { self.__matrix = Matrix.I(3); self.__updateTransform(); }; self.pop = function() { self.ctx.restore(); }; self.push = function() { self.ctx.save(); }; self.scale = function(x, y) { self.__matrix = self.__matrix.x($M([ [x, 0, 0], [0, y, 0], [0, 0, 1] ])); self.__updateTransform(); }; self.translate = function(x, y) { self.__matrix = self.__matrix.x($M([ [1, 0, x], [0, 1, y], [0, 0, 1] ])); self.__updateTransform(); }; self.rotate = function(rad) { var c = Math.cos(rad); var s = Math.sin(rad); self.__matrix = self.__matrix.x($M([ [c, -s, 0], [s, c, 0], [0, 0, 1] ])); self.__updateTransform(); }; self.shear = function(x, y) { self.__matrix = self.__matrix.x($M([ [1, y, 0], [x, 1, 0], [0, 0, 1] ])); self.__updateTransform(); }; //Constructors self.newCanvas = function(width, height) { return new Love.Graphics.Canvas2D(width, height, this); }; self.newImage = function(path) { return new Love.Graphics.Image(path); }; self.newQuad = function(x, y, w, h, sw, sh) { return new Love.Graphics.Quad(x, y, w, h); }; self.newFont = function(name, size) { return new Love.Graphics.Font(name, size); }; self.newImageFont = function(name, glyphs) { return new Love.Graphics.ImageFont(name, glyphs); }; //Window type things self.getWidth = function() { return self.canvas.width; }; self.getHeight = function() { return self.canvas.height; }; self.getDimensions = function() { return self.canvas.getDimensions(); }; //State //TODO: Implement all state functions self.getBackgroundColor = function() { var c = self.canvas.backgroundColor; return [ c.r, c.g, c.b, c.a ]; }; self.getBlendMode = function() { var c = self.ctx; if(c.globalCompositeOperation == "source-over") { return "alpha"; } else if(c.globalCompositeOperation == "multiply") { return "multiplicative"; } else if(c.globalCompositeOperation == "lighten") { return "additive"; } else { return "normal"; } }; self.getCanvas = function() { return self.canvas; }; self.getColor = function() { var c = new Love.Color(self.ctx.fillStyle); return [c.r, c.g, c.b, self.ctx.globalAlpha * 255]; }; self.setCanvas = function(canvas) { self.canvas = canvas || self.__mainCanvas; self.ctx = self.canvas.ctx; self.__matrix = self.canvas.matrix; self.__updateTransform(); }; self.setColor = function(r, g, b, a) { var c = new Love.Color(r, g, b, a), ctx = self.ctx; ctx.fillStyle = c.as_string; ctx.strokeStyle = c.as_string; ctx.globalAlpha = c.a / 255; }; self.setBackgroundColor = function(r, g, b, a) { self.canvas.setBackgroundColor(r, g, b, a); }; } return Graphics; })(); //TODO: Look at the pull request on punchdrunk for ideas to make this proper Love.Graphics.Font = (function() { function Font(name, size) { define(this); this.name = name; this.size = size; this.code = size + "px " + name; } function define(self) { //Most of these functions will not be properly implemented self.getAscent = function() { return 0; }; self.getBaseline = function() { return 0; }; self.getDescent = function() { return 0; }; self.getFilter = function() { return ["nearest", "nearest", 1]; }; self.getHeight = function() { return self.size; }; self.getLineHeight = function() { return self.size; }; self.getWidth = function(_, line) { unimplemented("Font:getWidth"); }; self.getWrap = function(_, lines, width) { unimplemented("Font:getWrap"); }; self.hasGlyphs = function() { return false; }; self.setFilter = function() { unimplemented("Font:setFilter"); }; self.setLineHeight = function() { unimplemented("Font:setLineHeight"); }; } return Font; })(); Love.Graphics.ImageFont = (function() { function ImageFont(name, glyphs) { this.name = name; this.glyphs = glyphs; this.chars = {}; define(this); } function define(self) { new Love.Graphics.Image(self.name, function(img) { self.__img = img; var charwidth = img.getWidth() / self.glyphs.length, i; for(i = 0; i < self.glyphs.length; i++) { self.chars[self.glyphs.charAt(i)] = new Love.Graphics.Quad(i * charwidth, 0, charwidth, img.getHeight()); } }); //Most of these functions will not be properly implemented self.getAscent = function() { return 0; }; self.getBaseline = function() { return 0; }; self.getDescent = function() { return 0; }; self.getFilter = function() { return ["nearest", "nearest", 1]; }; self.getHeight = function() { return self.__img.getHeight(); }; self.getLineHeight = function() { return self.__img.getHeight(); }; self.getWidth = function(_, line) { return self.__img.getWidth() / self.glyphs.length; }; self.getWrap = function(_, lines, width) { unimplemented("ImageFont:getWrap"); }; self.hasGlyphs = function() { return false; }; self.setFilter = function() { unimplemented("ImageFont:setFilter"); }; self.setLineHeight = function() { unimplemented("ImageFont:setLineHeight"); }; } return ImageFont; })(); Love.Graphics.Image = (function() { function LImage(path, onload) { define(this); var cFunc = wrap(this, function() { if(onload) onload.call(null, this); }); if(typeof path == "string") { this.elem = document.querySelector("[src='lua/"+path+"']"); if(this.elem == null) { this.elem = document.createElement("img"); this.elem.src = "lua/" + path; this.elem.onload = cFunc; } else { cFunc.call(); } } else { this.elem = document.createElement("img"); this.elem.src = "data:image/" + path.getExtension(path) + ";base64," + path.getString(path); this.elem.onload = cFunc; } } function define(self) { self.getData = function() { return new shine.Table(); }; self.getDimensions = function() { return [self.elem.width, self.elem.height]; }; self.getFilter = function() { neverimplemented("Image:getFilter"); }; self.getHeight = function() { return self.elem.height; }; self.getMipmapFilter = function() { neverimplemented("Image:getMipmapFilter"); }; self.getWidth = function() { return self.elem.width; }; self.getWrap = function() { return "none"; }; self.isCompressed = function() { return false; }; self.refresh = function() { unimplemented("Image:refresh"); }; self.setFilter = function() { neverimplemented("Image:setFilter"); }; self.setMipmapFilter = function() { neverimplemented("Image:setMipmapFilter"); }; self.setWrap = function() { neverimplemented("Image:setWrap"); }; } return LImage; })(); Love.Graphics.Quad = (function() { function Quad(x, y, w, h) { this.x = x; this.y = y; this.w = w; this.h = h; } Quad.prototype.getViewport = function(self) { return [self.x, self.y, self.w, self.h]; }; Quad.prototype.setViewport = function(self, x, y, w, h) { self.x = x; self.y = y; self.w = w; self.h = h; }; return Quad; })(); Love.Graphics.Canvas2D = (function() { function Canvas2D(width, height, elem, graphics) { define(this, graphics); this.elem = elem || document.createElement("canvas"); //Hide canvas by default for off-screen rendering this.elem.style.display = "none"; this.setDimensions(width, height); this.matrix = $M([ [1, 0, 0], [0, 1, 0], [0, 0, 1] ]); this.ctx = elem.getContext("2d"); this.setBackgroundColor(0, 0, 0, 255); } function define(self, graphics) { self.getDimensions = function() { return [self.width, self.height]; }; self.getFilter = function() { if(self.ctx.imageSmoothingEnabled) { return "linear"; } else { return "nearest"; } }; self.getFormat = function() { return "normal"; }; self.getHeight = function() { return self.height; }; self.getImageData = function() { var data = self.ctx.getImageData(0, 0, self.width, self.height); return new ImageData(data); }; self.getMSAA = function() { return 0; }; self.getPixel = function(_, x, y) { var data = self.ctx.getImageData(x, y, 1, 1); return [data[0], data[1], data[2], data[3]]; }; self.getWidth = function() { return self.width; }; self.getWrap = function() { return "none"; }; self.renderTo = function(_, func) { graphics.setCanvas(self); func.call(); graphics.setCanvas(); }; self.setFilter = function(_, filter) { var smoothing = filter == "linear", ctx = self.ctx; ctx.imageSmoothingEnabled = smoothing; ctx.mozImageSmoothingEnabled = smoothing; ctx.webkitImageSmoothingEnabled = smoothing; ctx.msImageSmoothingEnabled = smoothing; }; self.setWrap = function() { unimplemented("Canvas:setWrap"); }; //These are non-standard but are used thoughout the engine self.setDimensions = function(width, height) { self.setWidth(width); self.setHeight(height); }; self.setWidth = function(width) { self.width = width; self.elem.setAttribute('width', width); }; self.setHeight = function(height) { self.height = height; self.elem.setAttribute('height', height); }; self.setBackgroundColor = function(r, g, b, a) { var c = new Love.Color(r, g, b, a); self.backgroundColor = c; }; } return Canvas2D; })(); ;Love = Love || defineLove(); Love.Joystick = (function() { function Joystick() { } return Joystick; })();;Love = Love || defineLove(); //TODO: Add key repeating and text-input Love.Keyboard = (function() { function Keyboard(event) { define(this, event); } function define(self, event) { var keysDown = {}; var repeat = false; document.addEventListener("keydown", function(e) { e.preventDefault(); e.stopPropagation(); key = getKey(e); if(keysDown[key] && repeat) { event.push("keypressed", key, true); } if(!keysDown[key] && !repeat) { event.push("keypressed", key, false); } keysDown[key] = true; }, true); document.addEventListener("keyup", function(e) { e.preventDefault(); e.stopPropagation(); key = getKey(e); keysDown[key] = false; event.push("keyreleased", key); }, true); var keys = { 8: "backspace", 9: "tab", 13: "return", 16: "shift", 17: "ctrl", 18: "alt", 19: "pause", 20: "capslock", 27: "escape", 33: "pageup", 34: "pagedown", 35: "end", 36: "home", 45: "insert", 46: "delete", 37: "left", 38: "up", 39: "right", 40: "down", 91: "lmeta", 92: "rmeta", 93: "mode", 96: "kp0", 97: "kp1", 98: "kp2", 99: "kp3", 100: "kp4", 101: "kp5", 102: "kp6", 103: "kp7", 104: "kp8", 105: "kp9", 106: "kp*", 107: "kp+", 109: "kp-", 110: "kp.", 111: "kp/", 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8", 120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scrolllock", 186: ",", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",221: "]", 222: "'" }; var shiftKeys = { 192:"~", 48:")", 49:"!", 50:"@", 51:"#", 52:"$", 53:"%", 54:"^", 55:"&", 56:"*", 57:"(", 109:"_", 61:"+", 219:"{", 221:"}", 220:"|", 59:":", 222:"\"", 188:"<", 189:">", 191:"?", 96:"insert", 97:"end", 98:"down", 99:"pagedown", 100:"left", 102:"right", 103:"home", 104:"up", 105:"pageup" }; var rightKeys = { 16: "rshift", 17: "rctrl", 18: "ralt" }; function getKey(e) { var code, key; code = e.which; if(event.location && event.location > 1) { key = rightKeys[code]; } else if(event.shiftKey) { key = shiftKeys[code] || keys[code]; } else { key = keys[code]; } if (typeof key == "undefined") { key = String.fromCharCode(code); if(!e.shiftKey) { key = key.toLowerCase(); } } return key; } self.hasKeyRepeat = function() { return repeat; }; self.hasTextInput = function() { return false; }; self.isDown = function(key) { if(!keysDown[key]) { return false; } else { return keysDown[key]; } }; self.setKeyRepeat = function(r) { repeat = r; }; self.setTextInput = function() { unimplemented("love.keyboard.setTextInput"); }; self.getScancodeFromKey = function() { neverimplemented("love.keyboard.getScancodeFromKey"); }; self.getKeyFromScancode = function() { neverimplemented("love.keyboard.getKeyFromScancode"); }; } return Keyboard; })();;function defineLove() { return (function() { function Love(elem, conf) { wrap = function(t, f) { return function() { f.apply(t, arguments); } }; unimplemented = function(name) { console.warn("[", name, "] hasn't been implemented yet"); }; neverimplemented = function(name) { console.warn("[", name, "] can not be implemented in JS"); }; elem = elem || null; Love.element = elem; this.graphics = new Love.Graphics(conf.width, conf.height); this.event = new Love.Event(); this.window = new Love.Window(this.graphics, this.event); this.audio = new Love.Audio(); this.filesystem = new Love.FileSystem(); this.font = new Love.Font(); this.joystick = new Love.Joystick(); this.keyboard = new Love.Keyboard(this.event); this.math = new Love.Math(); this.mouse = new Love.Mouse(this.event, this.window); this.sound = new Love.Sound(); this.system = new Love.System(); this.timer = new Love.Timer(); this.run = wrap(this, this.run); } Love.prototype.load = function() { }; Love.prototype.update = function() { }; Love.prototype.draw = function() { }; Love.prototype.quit = function() { }; Love.prototype.keypressed = function() { }; Love.prototype.keyreleased = function() { }; Love.prototype.mousefocus = function() { }; Love.prototype.mousemoved = function() { }; Love.prototype.mousepressed = function() { }; Love.prototype.mousereleased = function() { }; Love.prototype.resize = function() { }; Love.prototype.run = function() { this.load.call(); this.timer.step(); // Step the timer so it doesn't count load time var i = 0, e; var gameloop = (function(self) { return function() { for(i = 0; i < self.event.queue.length; i++) { e = self.event.queue[i]; self[e[0]].apply(null, e.slice(1, e.length)); } self.event.clear(); self.timer.step(); self.update.call(null, self.timer.getDelta()); self.graphics.origin() self.graphics.clear(); self.draw.call(); self.timer.nextFrame(gameloop); }; })(this); this.timer.nextFrame(gameloop); }; Love.prototype.visible = function() { }; return Love; })(); };Love = Love || defineLove(); Love.Math = (function() { function LMath() { define(this); } function define(self) { } return LMath; })();;Love = Love || defineLove(); //TODO: Implement Pointer-lock api for setGrabbed Love.Mouse = (function() { function Mouse(event, win) { define(this, event, win); } function define(self, event, win) { var buttons = { "l" : false, "m" : false, "r" : false, "wd": false, "wu": false, "x1": false, "x2": false }; var love_buttons = ["l", "m", "r", "x1", "x2"]; var __x = 0; var __y = 0; var __cursor = new Love.Mouse.Cursor(); Love.element.addEventListener("mousedown", function(e) { var x, y, dims, rect = Love.element.getBoundingClientRect(); e.preventDefault(); e.stopPropagation(); x = e.clientX - rect.left; y = e.clientY - rect.top; if(win.getFullscreen()) { dims = win.getDimensions(); x *= (dims[0] / window.innerWidth); y *= (dims[1] / window.innerHeight); } buttons[e.which] = true; __x = x; __y = y; event.push("mousepressed", x, y, love_buttons[e.which - 1]); }, true); Love.element.addEventListener("mouseup", function(e) { var x, y, dims, rect = Love.element.getBoundingClientRect(); e.preventDefault(); e.stopPropagation(); x = e.clientX - rect.left; y = e.clientY - rect.top; if(win.getFullscreen()) { dims = win.getDimensions(); x *= (dims[0] / window.innerWidth); y *= (dims[1] / window.innerHeight); } buttons[e.which] = false; __x = x; __y = y; event.push("mousereleased", x, y, love_buttons[e.which - 1]); }, true); Love.element.addEventListener("mousemove", function(e) { var x, y, dims, dx, dy, rect = Love.element.getBoundingClientRect(); e.preventDefault(); e.stopPropagation(); x = e.clientX - rect.left; y = e.clientY - rect.top; if(win.getFullscreen()) { dims = win.getDimensions(); x *= (dims[0] / window.innerWidth); y *= (dims[1] / window.innerHeight); } dx = x - __x; dy = y - __y; __x = x; __y = y; event.push("mousemoved", x, y, dx, dy); }, true); Love.element.addEventListener("wheel", function(e) { var x, y, dims, rect = Love.element.getBoundingClientRect(), up; e.preventDefault(); e.stopPropagation(); x = e.clientX - rect.left; y = e.clientY - rect.top; if(win.getFullscreen()) { dims = win.getDimensions(); x *= (dims[0] / window.innerWidth); y *= (dims[1] / window.innerHeight); } up = e.deltaY < 0; event.push("mousepressed", x, y, up ? "wu" : "wd"); }, true); self.getCursor = function() { return __cursor; }; self.getPosition = function() { return [__x, __y]; }; self.getRelativeMode = function() { return false; }; self.getSystemCursor = function(type) { return new Love.Mouse.Cursor(type); }; self.getX = function() { return __x; }; self.getY = function() { return __y; }; self.isDown = function(button) { return buttons[button]; }; self.isGrabbed = function() { return false; }; self.isVisible = function() { return __cursor.__visible; }; self.newCursor = function(data) { unimplemented("love.mouse.newCursor"); }; self.setCursor = function(cursor) { __cursor = cursor; Love.element.style.cursor = __cursor.__getHtmlType(); }; self.setGrabbed = function() { neverimplemented("love.mouse.setGrabbed"); }; self.setPosition = function() { neverimplemented("love.mouse.setPosition"); }; self.setRelativeMode = function() { neverimplemented("love.mouse.setRelativeMode"); }; self.setVisible = function(visible) { __cursor.__visible = visible; Love.element.style.cursor = __cursor.__getHtmlType(); }; self.setX = function() { neverimplemented("love.mouse.setX"); }; self.setY = function() { neverimplemented("love.mouse.setY"); }; } return Mouse; })(); Love.Mouse.Cursor = (function() { function Cursor(type, visible) { this.type = type || "arrow"; this.__visible = visible != null ? visible : true; } var htmlcursor = { "arrow" : "default", "ibeam" : "text", "wait" : "wait", "waitarrow" : "progress", "crosshair" : "crosshair", "sizenwse" : "nwse-resize", "sizenesw" : "nesw-resize", "sizewe" : "ew-resize", "sizens" : "ns-resize", "sizeall" : "move", "no" : "not-allowed", "hand" : "grab" } Cursor.prototype.__getHtmlType = function() { return !this.__visible ? "none" : htmlcursor[this.type]; }; Cursor.prototype.getType = function(self) { return self.type; }; return Cursor; })();;//Ha ha ha ha ha no....;Love = Love || defineLove(); Love.Sound = (function() { function Sound() { define(this); } function define(self) { self.newDecoder = function() { neverimplemented("love.sound.newDecoder"); }; self.newSoundData = function() { neverimplemented("love.sound.newSoundData"); }; } return Sound; })();;Love = Love || defineLove(); Love.System = (function() { function System() { define(this); navigator.battery = navigator.battery || navigator.webkitBattery || navigator.mozBattery || navigator.msBattery; if(!navigator.battery) { //NOTE: This will not update as the program continues navigator.getBattery().then(function(battery) { navigator.battery = battery; }); } } function define(self) { var clipboardText = ""; self.getClipboardText = function() { return clipboardText; }; self.setClipboardText = function(text) { clipboardText = text; }; self.getOS = function() { return "Web " + navigator.appVersion; }; self.getPowerInfo = function() { if(navigator.battery) { var state = "", percent = Math.floor(navigator.battery.level * 100), discharge = navigator.battery.dischargingTime; if(navigator.battery.charging) { if(percent >= 99) { state = "charged"; } else { state = "charging"; } } else { state = "battery"; } return [state, percent, discharge]; } else { return ["nobattery", null, null]; } }; self.getProcessorCount = function() { return navigator.hardwareConcurrency || 1; }; self.openURL = function(url) { window.open(url); }; } return System; })();;Love = Love || defineLove(); Love.Timer = (function() { function Timer() { define(this); window.requestAnimationFrame = window.requestAnimationFrame || function(c) { setTimeout(c, 60/1000); }; } function define(self) { var dtLimit = 0.25; var dt = 0; var tp = Date.now(); self.getDelta = function() { return dt; }; self.getTime = function() { return tp; }; self.getFPS = function() { if(dt == 0) { return 0; } return 1 / dt; }; self.sleep = function() { unimplemented("love.timer.sleep"); }; self.step = function() { var delta = (Date.now() - tp) / 1000; dt = Math.max(0, Math.min(dtLimit, delta)); tp += dt * 1000; }; self.nextFrame = function(callback) { window.requestAnimationFrame(callback); }; } return Timer; })();;Love = Love || defineLove(); Love.Window = (function() { function Window(graphics, event) { define(this, graphics); window.onbeforeunload = function() { event.quit(); }; window.onblur = function() { event.push("visible", false); event.push("mousefocus", false); }; window.onfocus = function() { event.push("visible", true); event.push("mousefocus", true); }; document.oncontextmenu = function(e) { e.preventDefault(); }; } function define(self, graphics) { var ts = 0; var handler = function() { var elem = document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.msFullScreenElement; if(elem != Love.element) { fullscreen = false; self.setFullscreen(false, true); } else { fullscreen = true; } }; document.addEventListener("webkitfullscreenchange", handler, true); document.addEventListener("mozfullscreenchange", handler, true); document.addEventListener("fullscreenchange", handler, true); document.addEventListener("MSFullscreenchange", handler, true); var fullscreen = false; self.fromPixels = function() { unimplemented("love.window.fromPixels"); }; self.getDesktopDimensions = function() { return [window.screen.width, window.screen.height]; }; self.getDimensions = function() { return graphics.getDimensions(); }; self.getDisplayCount = function() { return 1; }; self.getDisplayNames = function() { return window.document.title; }; self.getFullscreen = function() { return fullscreen; }; self.getFullscreenModes = function() { return [ new shine.Table({ width: window.screen.width, height: window.screen.height }) ]; }; self.getHeight = function() { return graphics.getHeight(); }; self.getIcon = function() { unimplemented("love.window.getIcon"); }; self.getMode = function() { return [self.getWidth(), self.getHeight(), null]; }; self.getPixelScale = function() { return window.devicePixelRatio; }; self.getPosition = function() { return [0, 0, 1]; }; self.getTitle = function() { return window.document.title; }; self.getWidth = function() { return graphics.getWidth(); }; self.hasFocus = function() { return document.activeElement == Love.element; }; self.hasMouseFocus = function() { return document.activeElement == Love.element; }; self.isCreated = function() { return true; }; self.isVisible = function() { return true; }; self.setFullscreen = function(fs, fromCallback) { fromCallback = fromCallback == null ? false : fromCallback; if(fs) { Love.element.requestFullscreen = Love.element.mozRequestFullScreen || Love.element.webkitRequestFullscreen || Love.element.msRequestFullscreen || Love.element.requestFullscreen; document.getElementById("fs-text").setAttribute("style", "display: block;"); document.getElementById("fs-btn").addEventListener("click", function() { ts = Date.now(); Love.element.requestFullscreen(); var dims = self.getDesktopDimensions(); Love.element.setAttribute("style", "width: " + dims[0] + "px; height: " + dims[1] + "px;"); }); } else { document.exitFullscreen = document.exitFullscreen || document.mozCancelFullScreen || document.webkitExitFullscreen || document.msExitFullscreen; document.exitFullscreen(); var dims = self.getDimensions(); Love.element.setAttribute("style", "width: " + dims[0] + "px; height: " + dims[1] + "px;"); //Dont remove the message unless the love2d program says to if(!fromCallback) { document.getElementById("fs-text").setAttribute("style", "display: none;"); document.getElementById("fs-btn").removeEventListener("click", null); } } }; self.setIcon = function() { unimplemented("love.window.setIcon"); }; self.setMode = function(width, height, flags) { graphics.__mainCanvas.setDimensions(width, height); if(flags.getMember("fullscreen")) { self.setFullscreen(flags.getMember("fullscreen")); } }; self.setPosition = function(x, y) { //Unneeded in JS }; self.setTitle = function(title) { window.document.title = title; }; self.showMessageBox = function(title, message, type, attachtowindow) { window.alert(title + "\n " + message); }; self.toPixels = function() { unimplemented("love.window.toPixels"); }; } return Window; })();
{'content_hash': '51738947df609d3ca9e82f1f2349fc74', 'timestamp': '', 'source': 'github', 'line_count': 1722, 'max_line_length': 131, 'avg_line_length': 29.42624854819977, 'alnum_prop': 0.4500710451531418, 'repo_name': 'brendanfh/love-web', 'id': 'e7198c6d82261a1f14ccbf82b4ca7c033d76a5a0', 'size': '50672', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'js/love.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '824'}, {'name': 'JavaScript', 'bytes': '294458'}, {'name': 'Lua', 'bytes': '1510'}]}
""" Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.6.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import kubernetes.client from kubernetes.client.rest import ApiException from kubernetes.client.models.extensions_v1beta1_deployment_rollback import ExtensionsV1beta1DeploymentRollback class TestExtensionsV1beta1DeploymentRollback(unittest.TestCase): """ ExtensionsV1beta1DeploymentRollback unit test stubs """ def setUp(self): pass def tearDown(self): pass def testExtensionsV1beta1DeploymentRollback(self): """ Test ExtensionsV1beta1DeploymentRollback """ model = kubernetes.client.models.extensions_v1beta1_deployment_rollback.ExtensionsV1beta1DeploymentRollback() if __name__ == '__main__': unittest.main()
{'content_hash': '706052f5d4357e068cdc389fdc624aa2', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 117, 'avg_line_length': 25.1, 'alnum_prop': 0.7390438247011952, 'repo_name': 'skuda/client-python', 'id': '0a54b2cb12592a727de268f5093fcae0e9a866b1', 'size': '1021', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'kubernetes/test/test_extensions_v1beta1_deployment_rollback.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '5907789'}, {'name': 'Shell', 'bytes': '8195'}]}
<resources> <string name="app_name">UserGuideLibrary</string> </resources>
{'content_hash': '585a3d12bd733597d6a0547746be7cd1', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 53, 'avg_line_length': 26.333333333333332, 'alnum_prop': 0.7215189873417721, 'repo_name': 'binarylife/Ydkd', 'id': '07be03c67f6be7890f8e8c32517df94f16108a3d', 'size': '79', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'library/UserGuide/src/main/res/values/strings.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '902080'}]}
package govaluate import ( "bytes" "fmt" "reflect" "testing" "time" "unicode" ) /* Represents a test of parsing all tokens correctly from a string */ type TokenParsingTest struct { Name string Input string Functions map[string]ExpressionFunction Expected []ExpressionToken } func TestConstantParsing(test *testing.T) { tokenParsingTests := []TokenParsingTest{ TokenParsingTest{ Name: "Single numeric", Input: "1", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, }, }, TokenParsingTest{ Name: "Single two-digit numeric", Input: "50", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 50.0, }, }, }, TokenParsingTest{ Name: "Zero", Input: "0", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 0.0, }, }, }, TokenParsingTest{ Name: "One digit hex", Input: "0x1", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, }, }, TokenParsingTest{ Name: "Two digit hex", Input: "0x10", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 16.0, }, }, }, TokenParsingTest{ Name: "Hex with lowercase", Input: "0xabcdef", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 11259375.0, }, }, }, TokenParsingTest{ Name: "Hex with uppercase", Input: "0xABCDEF", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 11259375.0, }, }, }, TokenParsingTest{ Name: "Single string", Input: "'foo'", Expected: []ExpressionToken{ ExpressionToken{ Kind: STRING, Value: "foo", }, }, }, TokenParsingTest{ Name: "Single time, RFC3339, only date", Input: "'2014-01-02'", Expected: []ExpressionToken{ ExpressionToken{ Kind: TIME, Value: time.Date(2014, time.January, 2, 0, 0, 0, 0, time.Local), }, }, }, TokenParsingTest{ Name: "Single time, RFC3339, with hh:mm", Input: "'2014-01-02 14:12'", Expected: []ExpressionToken{ ExpressionToken{ Kind: TIME, Value: time.Date(2014, time.January, 2, 14, 12, 0, 0, time.Local), }, }, }, TokenParsingTest{ Name: "Single time, RFC3339, with hh:mm:ss", Input: "'2014-01-02 14:12:22'", Expected: []ExpressionToken{ ExpressionToken{ Kind: TIME, Value: time.Date(2014, time.January, 2, 14, 12, 22, 0, time.Local), }, }, }, TokenParsingTest{ Name: "Single boolean", Input: "true", Expected: []ExpressionToken{ ExpressionToken{ Kind: BOOLEAN, Value: true, }, }, }, TokenParsingTest{ Name: "Single large numeric", Input: "1234567890", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 1234567890.0, }, }, }, TokenParsingTest{ Name: "Single floating-point", Input: "0.5", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 0.5, }, }, }, TokenParsingTest{ Name: "Single large floating point", Input: "3.14567471", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 3.14567471, }, }, }, TokenParsingTest{ Name: "Single false boolean", Input: "false", Expected: []ExpressionToken{ ExpressionToken{ Kind: BOOLEAN, Value: false, }, }, }, TokenParsingTest{ Name: "Single internationalized string", Input: "'ÆŦǽഈᚥஇคٸ'", Expected: []ExpressionToken{ ExpressionToken{ Kind: STRING, Value: "ÆŦǽഈᚥஇคٸ", }, }, }, TokenParsingTest{ Name: "Single internationalized parameter", Input: "ÆŦǽഈᚥஇคٸ", Expected: []ExpressionToken{ ExpressionToken{ Kind: VARIABLE, Value: "ÆŦǽഈᚥஇคٸ", }, }, }, TokenParsingTest{ Name: "Parameterless function", Input: "foo()", Functions: map[string]ExpressionFunction{"foo": noop}, Expected: []ExpressionToken{ ExpressionToken{ Kind: FUNCTION, Value: noop, }, ExpressionToken{ Kind: CLAUSE, }, ExpressionToken{ Kind: CLAUSE_CLOSE, }, }, }, TokenParsingTest{ Name: "Single parameter function", Input: "foo('bar')", Functions: map[string]ExpressionFunction{"foo": noop}, Expected: []ExpressionToken{ ExpressionToken{ Kind: FUNCTION, Value: noop, }, ExpressionToken{ Kind: CLAUSE, }, ExpressionToken{ Kind: STRING, Value: "bar", }, ExpressionToken{ Kind: CLAUSE_CLOSE, }, }, }, TokenParsingTest{ Name: "Multiple parameter function", Input: "foo('bar', 1.0)", Functions: map[string]ExpressionFunction{"foo": noop}, Expected: []ExpressionToken{ ExpressionToken{ Kind: FUNCTION, Value: noop, }, ExpressionToken{ Kind: CLAUSE, }, ExpressionToken{ Kind: STRING, Value: "bar", }, ExpressionToken{ Kind: SEPARATOR, }, ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, ExpressionToken{ Kind: CLAUSE_CLOSE, }, }, }, TokenParsingTest{ Name: "Nested function", Input: "foo(foo('bar'), 1.0, foo(2.0))", Functions: map[string]ExpressionFunction{"foo": noop}, Expected: []ExpressionToken{ ExpressionToken{ Kind: FUNCTION, Value: noop, }, ExpressionToken{ Kind: CLAUSE, }, ExpressionToken{ Kind: FUNCTION, Value: noop, }, ExpressionToken{ Kind: CLAUSE, }, ExpressionToken{ Kind: STRING, Value: "bar", }, ExpressionToken{ Kind: CLAUSE_CLOSE, }, ExpressionToken{ Kind: SEPARATOR, }, ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, ExpressionToken{ Kind: SEPARATOR, }, ExpressionToken{ Kind: FUNCTION, Value: noop, }, ExpressionToken{ Kind: CLAUSE, }, ExpressionToken{ Kind: NUMERIC, Value: 2.0, }, ExpressionToken{ Kind: CLAUSE_CLOSE, }, ExpressionToken{ Kind: CLAUSE_CLOSE, }, }, }, TokenParsingTest{ Name: "Function with modifier afterwards (#28)", Input: "foo() + 1", Functions: map[string]ExpressionFunction{"foo": noop}, Expected: []ExpressionToken{ ExpressionToken{ Kind: FUNCTION, Value: noop, }, ExpressionToken{ Kind: CLAUSE, }, ExpressionToken{ Kind: CLAUSE_CLOSE, }, ExpressionToken{ Kind: MODIFIER, Value: "+", }, ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, }, }, TokenParsingTest{ Name: "Function with modifier afterwards and comparator", Input: "(foo()-1) > 3", Functions: map[string]ExpressionFunction{"foo": noop}, Expected: []ExpressionToken{ ExpressionToken{ Kind: CLAUSE, }, ExpressionToken{ Kind: FUNCTION, Value: noop, }, ExpressionToken{ Kind: CLAUSE, }, ExpressionToken{ Kind: CLAUSE_CLOSE, }, ExpressionToken{ Kind: MODIFIER, Value: "-", }, ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, ExpressionToken{ Kind: CLAUSE_CLOSE, }, ExpressionToken{ Kind: COMPARATOR, Value: ">", }, ExpressionToken{ Kind: NUMERIC, Value: 3.0, }, }, }, TokenParsingTest{ Name: "Double-quoted string added to square-brackted param (#59)", Input: "\"a\" + [foo]", Expected: []ExpressionToken{ ExpressionToken{ Kind: STRING, Value: "a", }, ExpressionToken{ Kind: MODIFIER, Value: "+", }, ExpressionToken{ Kind: VARIABLE, Value: "foo", }, }, }, TokenParsingTest{ Name: "Accessor variable", Input: "foo.Var", Expected: []ExpressionToken{ ExpressionToken{ Kind: ACCESSOR, Value: []string{"foo", "Var"}, }, }, }, TokenParsingTest{ Name: "Accessor function", Input: "foo.Operation()", Expected: []ExpressionToken{ ExpressionToken{ Kind: ACCESSOR, Value: []string{"foo", "Operation"}, }, ExpressionToken{ Kind: CLAUSE, }, ExpressionToken{ Kind: CLAUSE_CLOSE, }, }, }, } tokenParsingTests = combineWhitespaceExpressions(tokenParsingTests) runTokenParsingTest(tokenParsingTests, test) } func TestLogicalOperatorParsing(test *testing.T) { tokenParsingTests := []TokenParsingTest{ TokenParsingTest{ Name: "Boolean AND", Input: "true && false", Expected: []ExpressionToken{ ExpressionToken{ Kind: BOOLEAN, Value: true, }, ExpressionToken{ Kind: LOGICALOP, Value: "&&", }, ExpressionToken{ Kind: BOOLEAN, Value: false, }, }, }, TokenParsingTest{ Name: "Boolean OR", Input: "true || false", Expected: []ExpressionToken{ ExpressionToken{ Kind: BOOLEAN, Value: true, }, ExpressionToken{ Kind: LOGICALOP, Value: "||", }, ExpressionToken{ Kind: BOOLEAN, Value: false, }, }, }, TokenParsingTest{ Name: "Multiple logical operators", Input: "true || false && true", Expected: []ExpressionToken{ ExpressionToken{ Kind: BOOLEAN, Value: true, }, ExpressionToken{ Kind: LOGICALOP, Value: "||", }, ExpressionToken{ Kind: BOOLEAN, Value: false, }, ExpressionToken{ Kind: LOGICALOP, Value: "&&", }, ExpressionToken{ Kind: BOOLEAN, Value: true, }, }, }, } tokenParsingTests = combineWhitespaceExpressions(tokenParsingTests) runTokenParsingTest(tokenParsingTests, test) } func TestComparatorParsing(test *testing.T) { tokenParsingTests := []TokenParsingTest{ TokenParsingTest{ Name: "Numeric EQ", Input: "1 == 2", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, ExpressionToken{ Kind: COMPARATOR, Value: "==", }, ExpressionToken{ Kind: NUMERIC, Value: 2.0, }, }, }, TokenParsingTest{ Name: "Numeric NEQ", Input: "1 != 2", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, ExpressionToken{ Kind: COMPARATOR, Value: "!=", }, ExpressionToken{ Kind: NUMERIC, Value: 2.0, }, }, }, TokenParsingTest{ Name: "Numeric GT", Input: "1 > 0", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, ExpressionToken{ Kind: COMPARATOR, Value: ">", }, ExpressionToken{ Kind: NUMERIC, Value: 0.0, }, }, }, TokenParsingTest{ Name: "Numeric LT", Input: "1 < 2", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, ExpressionToken{ Kind: COMPARATOR, Value: "<", }, ExpressionToken{ Kind: NUMERIC, Value: 2.0, }, }, }, TokenParsingTest{ Name: "Numeric GTE", Input: "1 >= 2", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, ExpressionToken{ Kind: COMPARATOR, Value: ">=", }, ExpressionToken{ Kind: NUMERIC, Value: 2.0, }, }, }, TokenParsingTest{ Name: "Numeric LTE", Input: "1 <= 2", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, ExpressionToken{ Kind: COMPARATOR, Value: "<=", }, ExpressionToken{ Kind: NUMERIC, Value: 2.0, }, }, }, TokenParsingTest{ Name: "String LT", Input: "'ab.cd' < 'abc.def'", Expected: []ExpressionToken{ ExpressionToken{ Kind: STRING, Value: "ab.cd", }, ExpressionToken{ Kind: COMPARATOR, Value: "<", }, ExpressionToken{ Kind: STRING, Value: "abc.def", }, }, }, TokenParsingTest{ Name: "String LTE", Input: "'ab.cd' <= 'abc.def'", Expected: []ExpressionToken{ ExpressionToken{ Kind: STRING, Value: "ab.cd", }, ExpressionToken{ Kind: COMPARATOR, Value: "<=", }, ExpressionToken{ Kind: STRING, Value: "abc.def", }, }, }, TokenParsingTest{ Name: "String GT", Input: "'ab.cd' > 'abc.def'", Expected: []ExpressionToken{ ExpressionToken{ Kind: STRING, Value: "ab.cd", }, ExpressionToken{ Kind: COMPARATOR, Value: ">", }, ExpressionToken{ Kind: STRING, Value: "abc.def", }, }, }, TokenParsingTest{ Name: "String GTE", Input: "'ab.cd' >= 'abc.def'", Expected: []ExpressionToken{ ExpressionToken{ Kind: STRING, Value: "ab.cd", }, ExpressionToken{ Kind: COMPARATOR, Value: ">=", }, ExpressionToken{ Kind: STRING, Value: "abc.def", }, }, }, TokenParsingTest{ Name: "String REQ", Input: "'foobar' =~ 'bar'", Expected: []ExpressionToken{ ExpressionToken{ Kind: STRING, Value: "foobar", }, ExpressionToken{ Kind: COMPARATOR, Value: "=~", }, // it's not particularly clean to test for the contents of a pattern, (since it means modifying the harness below) // so pattern contents are left untested. ExpressionToken{ Kind: PATTERN, }, }, }, TokenParsingTest{ Name: "String NREQ", Input: "'foobar' !~ 'bar'", Expected: []ExpressionToken{ ExpressionToken{ Kind: STRING, Value: "foobar", }, ExpressionToken{ Kind: COMPARATOR, Value: "!~", }, ExpressionToken{ Kind: PATTERN, }, }, }, TokenParsingTest{ Name: "Comparator against modifier string additive (#22)", Input: "'foo' == '+'", Expected: []ExpressionToken{ ExpressionToken{ Kind: STRING, Value: "foo", }, ExpressionToken{ Kind: COMPARATOR, Value: "==", }, ExpressionToken{ Kind: STRING, Value: "+", }, }, }, TokenParsingTest{ Name: "Comparator against modifier string multiplicative (#22)", Input: "'foo' == '/'", Expected: []ExpressionToken{ ExpressionToken{ Kind: STRING, Value: "foo", }, ExpressionToken{ Kind: COMPARATOR, Value: "==", }, ExpressionToken{ Kind: STRING, Value: "/", }, }, }, TokenParsingTest{ Name: "Comparator against modifier string exponential (#22)", Input: "'foo' == '**'", Expected: []ExpressionToken{ ExpressionToken{ Kind: STRING, Value: "foo", }, ExpressionToken{ Kind: COMPARATOR, Value: "==", }, ExpressionToken{ Kind: STRING, Value: "**", }, }, }, TokenParsingTest{ Name: "Comparator against modifier string bitwise (#22)", Input: "'foo' == '^'", Expected: []ExpressionToken{ ExpressionToken{ Kind: STRING, Value: "foo", }, ExpressionToken{ Kind: COMPARATOR, Value: "==", }, ExpressionToken{ Kind: STRING, Value: "^", }, }, }, TokenParsingTest{ Name: "Comparator against modifier string shift (#22)", Input: "'foo' == '>>'", Expected: []ExpressionToken{ ExpressionToken{ Kind: STRING, Value: "foo", }, ExpressionToken{ Kind: COMPARATOR, Value: "==", }, ExpressionToken{ Kind: STRING, Value: ">>", }, }, }, TokenParsingTest{ Name: "Comparator against modifier string ternary (#22)", Input: "'foo' == '?'", Expected: []ExpressionToken{ ExpressionToken{ Kind: STRING, Value: "foo", }, ExpressionToken{ Kind: COMPARATOR, Value: "==", }, ExpressionToken{ Kind: STRING, Value: "?", }, }, }, TokenParsingTest{ Name: "Array membership lowercase", Input: "'foo' in ('foo', 'bar')", Expected: []ExpressionToken{ ExpressionToken{ Kind: STRING, Value: "foo", }, ExpressionToken{ Kind: COMPARATOR, Value: "in", }, ExpressionToken{ Kind: CLAUSE, }, ExpressionToken{ Kind: STRING, Value: "foo", }, ExpressionToken{ Kind: SEPARATOR, }, ExpressionToken{ Kind: STRING, Value: "bar", }, ExpressionToken{ Kind: CLAUSE_CLOSE, }, }, }, TokenParsingTest{ Name: "Array membership uppercase", Input: "'foo' IN ('foo', 'bar')", Expected: []ExpressionToken{ ExpressionToken{ Kind: STRING, Value: "foo", }, ExpressionToken{ Kind: COMPARATOR, Value: "in", }, ExpressionToken{ Kind: CLAUSE, }, ExpressionToken{ Kind: STRING, Value: "foo", }, ExpressionToken{ Kind: SEPARATOR, }, ExpressionToken{ Kind: STRING, Value: "bar", }, ExpressionToken{ Kind: CLAUSE_CLOSE, }, }, }, } tokenParsingTests = combineWhitespaceExpressions(tokenParsingTests) runTokenParsingTest(tokenParsingTests, test) } func TestModifierParsing(test *testing.T) { tokenParsingTests := []TokenParsingTest{ TokenParsingTest{ Name: "Numeric PLUS", Input: "1 + 1", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, ExpressionToken{ Kind: MODIFIER, Value: "+", }, ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, }, }, TokenParsingTest{ Name: "Numeric MINUS", Input: "1 - 1", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, ExpressionToken{ Kind: MODIFIER, Value: "-", }, ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, }, }, TokenParsingTest{ Name: "Numeric MULTIPLY", Input: "1 * 1", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, ExpressionToken{ Kind: MODIFIER, Value: "*", }, ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, }, }, TokenParsingTest{ Name: "Numeric DIVIDE", Input: "1 / 1", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, ExpressionToken{ Kind: MODIFIER, Value: "/", }, ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, }, }, TokenParsingTest{ Name: "Numeric MODULUS", Input: "1 % 1", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, ExpressionToken{ Kind: MODIFIER, Value: "%", }, ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, }, }, TokenParsingTest{ Name: "Numeric BITWISE_AND", Input: "1 & 1", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, ExpressionToken{ Kind: MODIFIER, Value: "&", }, ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, }, }, TokenParsingTest{ Name: "Numeric BITWISE_OR", Input: "1 | 1", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, ExpressionToken{ Kind: MODIFIER, Value: "|", }, ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, }, }, TokenParsingTest{ Name: "Numeric BITWISE_XOR", Input: "1 ^ 1", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, ExpressionToken{ Kind: MODIFIER, Value: "^", }, ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, }, }, TokenParsingTest{ Name: "Numeric BITWISE_LSHIFT", Input: "1 << 1", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, ExpressionToken{ Kind: MODIFIER, Value: "<<", }, ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, }, }, TokenParsingTest{ Name: "Numeric BITWISE_RSHIFT", Input: "1 >> 1", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, ExpressionToken{ Kind: MODIFIER, Value: ">>", }, ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, }, }, } tokenParsingTests = combineWhitespaceExpressions(tokenParsingTests) runTokenParsingTest(tokenParsingTests, test) } func TestPrefixParsing(test *testing.T) { testCases := []TokenParsingTest{ TokenParsingTest{ Name: "Sign prefix", Input: "-1", Expected: []ExpressionToken{ ExpressionToken{ Kind: PREFIX, Value: "-", }, ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, }, }, TokenParsingTest{ Name: "Sign prefix on variable", Input: "-foo", Expected: []ExpressionToken{ ExpressionToken{ Kind: PREFIX, Value: "-", }, ExpressionToken{ Kind: VARIABLE, Value: "foo", }, }, }, TokenParsingTest{ Name: "Boolean prefix", Input: "!true", Expected: []ExpressionToken{ ExpressionToken{ Kind: PREFIX, Value: "!", }, ExpressionToken{ Kind: BOOLEAN, Value: true, }, }, }, TokenParsingTest{ Name: "Boolean prefix on variable", Input: "!foo", Expected: []ExpressionToken{ ExpressionToken{ Kind: PREFIX, Value: "!", }, ExpressionToken{ Kind: VARIABLE, Value: "foo", }, }, }, TokenParsingTest{ Name: "Bitwise not prefix", Input: "~1", Expected: []ExpressionToken{ ExpressionToken{ Kind: PREFIX, Value: "~", }, ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, }, }, TokenParsingTest{ Name: "Bitwise not prefix on variable", Input: "~foo", Expected: []ExpressionToken{ ExpressionToken{ Kind: PREFIX, Value: "~", }, ExpressionToken{ Kind: VARIABLE, Value: "foo", }, }, }, } testCases = combineWhitespaceExpressions(testCases) runTokenParsingTest(testCases, test) } func TestEscapedParameters(test *testing.T) { testCases := []TokenParsingTest{ TokenParsingTest{ Name: "Single escaped parameter", Input: "[foo]", Expected: []ExpressionToken{ ExpressionToken{ Kind: VARIABLE, Value: "foo", }, }, }, TokenParsingTest{ Name: "Single escaped parameter with whitespace", Input: "[foo bar]", Expected: []ExpressionToken{ ExpressionToken{ Kind: VARIABLE, Value: "foo bar", }, }, }, TokenParsingTest{ Name: "Single escaped parameter with escaped closing bracket", Input: "[foo[bar\\]]", Expected: []ExpressionToken{ ExpressionToken{ Kind: VARIABLE, Value: "foo[bar]", }, }, }, TokenParsingTest{ Name: "Escaped parameters and unescaped parameters", Input: "[foo] > bar", Expected: []ExpressionToken{ ExpressionToken{ Kind: VARIABLE, Value: "foo", }, ExpressionToken{ Kind: COMPARATOR, Value: ">", }, ExpressionToken{ Kind: VARIABLE, Value: "bar", }, }, }, TokenParsingTest{ Name: "Unescaped parameter with space", Input: "foo\\ bar > bar", Expected: []ExpressionToken{ ExpressionToken{ Kind: VARIABLE, Value: "foo bar", }, ExpressionToken{ Kind: COMPARATOR, Value: ">", }, ExpressionToken{ Kind: VARIABLE, Value: "bar", }, }, }, TokenParsingTest{ Name: "Unescaped parameter with space", Input: "response\\-time > bar", Expected: []ExpressionToken{ ExpressionToken{ Kind: VARIABLE, Value: "response-time", }, ExpressionToken{ Kind: COMPARATOR, Value: ">", }, ExpressionToken{ Kind: VARIABLE, Value: "bar", }, }, }, TokenParsingTest{ Name: "Parameters with snake_case", Input: "foo_bar > baz_quux", Expected: []ExpressionToken{ ExpressionToken{ Kind: VARIABLE, Value: "foo_bar", }, ExpressionToken{ Kind: COMPARATOR, Value: ">", }, ExpressionToken{ Kind: VARIABLE, Value: "baz_quux", }, }, }, TokenParsingTest{ Name: "String literal uses backslash to escape", Input: "\"foo\\'bar\"", Expected: []ExpressionToken{ ExpressionToken{ Kind: STRING, Value: "foo'bar", }, }, }, } runTokenParsingTest(testCases, test) } func TestTernaryParsing(test *testing.T) { tokenParsingTests := []TokenParsingTest{ TokenParsingTest{ Name: "Ternary after Boolean", Input: "true ? 1", Expected: []ExpressionToken{ ExpressionToken{ Kind: BOOLEAN, Value: true, }, ExpressionToken{ Kind: TERNARY, Value: "?", }, ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, }, }, TokenParsingTest{ Name: "Ternary after Comperator", Input: "1 == 0 ? true", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, ExpressionToken{ Kind: COMPARATOR, Value: "==", }, ExpressionToken{ Kind: NUMERIC, Value: 0.0, }, ExpressionToken{ Kind: TERNARY, Value: "?", }, ExpressionToken{ Kind: BOOLEAN, Value: true, }, }, }, TokenParsingTest{ Name: "Null coalesce left", Input: "1 ?? 2", Expected: []ExpressionToken{ ExpressionToken{ Kind: NUMERIC, Value: 1.0, }, ExpressionToken{ Kind: TERNARY, Value: "??", }, ExpressionToken{ Kind: NUMERIC, Value: 2.0, }, }, }, } runTokenParsingTest(tokenParsingTests, test) } /* Tests to make sure that the String() reprsentation of an expression exactly matches what is given to the parse function. */ func TestOriginalString(test *testing.T) { // include all the token types, to be sure there's no shenaniganery going on. expressionString := "2 > 1 &&" + "'something' != 'nothing' || " + "'2014-01-20' < 'Wed Jul 8 23:07:35 MDT 2015' && " + "[escapedVariable name with spaces] <= unescaped\\-variableName &&" + "modifierTest + 1000 / 2 > (80 * 100 % 2) && true ? true : false" expression, err := NewEvaluableExpression(expressionString) if err != nil { test.Logf("failed to parse original string test: %v", err) test.Fail() return } if expression.String() != expressionString { test.Logf("String() did not give the same expression as given to parse") test.Fail() } } /* Tests to make sure that the Vars() reprsentation of an expression identifies all variables contained within the expression. */ func TestOriginalVars(test *testing.T) { // include all the token types, to be sure there's no shenaniganery going on. expressionString := "2 > 1 &&" + "'something' != 'nothing' || " + "'2014-01-20' < 'Wed Jul 8 23:07:35 MDT 2015' && " + "[escapedVariable name with spaces] <= unescaped\\-variableName &&" + "modifierTest + 1000 / 2 > (80 * 100 % 2) && true ? true : false" expectedVars := [3]string{"escapedVariable name with spaces", "modifierTest", "unescaped-variableName"} expression, err := NewEvaluableExpression(expressionString) if err != nil { test.Logf("failed to parse original var test: %v", err) test.Fail() return } if len(expression.Vars()) == len(expectedVars) { variableMap := make(map[string]string) for _, v := range expression.Vars() { variableMap[v] = v } for _, v := range expectedVars { if _, ok := variableMap[v]; !ok { test.Logf("Vars() did not correctly identify all variables contained within the expression") test.Fail() } } } else { test.Logf("Vars() did not correctly identify all variables contained within the expression") test.Fail() } } func combineWhitespaceExpressions(testCases []TokenParsingTest) []TokenParsingTest { var currentCase, strippedCase TokenParsingTest var caseLength int caseLength = len(testCases) for i := 0; i < caseLength; i++ { currentCase = testCases[i] strippedCase = TokenParsingTest{ Name: (currentCase.Name + " (without whitespace)"), Input: stripUnquotedWhitespace(currentCase.Input), Expected: currentCase.Expected, Functions: currentCase.Functions, } testCases = append(testCases, strippedCase, currentCase) } return testCases } func stripUnquotedWhitespace(expression string) string { var expressionBuffer bytes.Buffer var quoted bool for _, character := range expression { if !quoted && unicode.IsSpace(character) { continue } if character == '\'' { quoted = !quoted } expressionBuffer.WriteString(string(character)) } return expressionBuffer.String() } func runTokenParsingTest(tokenParsingTests []TokenParsingTest, test *testing.T) { var parsingTest TokenParsingTest var expression *EvaluableExpression var actualTokens []ExpressionToken var actualToken ExpressionToken var expectedTokenKindString, actualTokenKindString string var expectedTokenLength, actualTokenLength int var err error fmt.Printf("Running %d parsing test cases...\n", len(tokenParsingTests)) // defer func() { // if r := recover(); r != nil { // test.Logf("Panic in test '%s': %v", parsingTest.Name, r) // test.Fail() // } // }() // Run the test cases. for _, parsingTest = range tokenParsingTests { if parsingTest.Functions != nil { expression, err = NewEvaluableExpressionWithFunctions(parsingTest.Input, parsingTest.Functions) } else { expression, err = NewEvaluableExpression(parsingTest.Input) } if err != nil { test.Logf("Test '%s' failed to parse: %s", parsingTest.Name, err) test.Logf("Expression: '%s'", parsingTest.Input) test.Fail() continue } actualTokens = expression.Tokens() expectedTokenLength = len(parsingTest.Expected) actualTokenLength = len(actualTokens) if actualTokenLength != expectedTokenLength { test.Logf("Test '%s' failed:", parsingTest.Name) test.Logf("Expected %d tokens, actually found %d", expectedTokenLength, actualTokenLength) test.Fail() continue } for i, expectedToken := range parsingTest.Expected { actualToken = actualTokens[i] if actualToken.Kind != expectedToken.Kind { actualTokenKindString = actualToken.Kind.String() expectedTokenKindString = expectedToken.Kind.String() test.Logf("Test '%s' failed:", parsingTest.Name) test.Logf("Expected token kind '%v' does not match '%v'", expectedTokenKindString, actualTokenKindString) test.Fail() continue } if expectedToken.Value == nil { continue } reflectedKind := reflect.TypeOf(expectedToken.Value).Kind() if reflectedKind == reflect.Func { continue } // gotta be an accessor if reflectedKind == reflect.Slice { if actualToken.Value == nil { test.Logf("Test '%s' failed:", parsingTest.Name) test.Logf("Expected token value '%v' does not match nil", expectedToken.Value) test.Fail() } for z, actual := range actualToken.Value.([]string) { if actual != expectedToken.Value.([]string)[z] { test.Logf("Test '%s' failed:", parsingTest.Name) test.Logf("Expected token value '%v' does not match '%v'", expectedToken.Value, actualToken.Value) test.Fail() } } continue } if actualToken.Value != expectedToken.Value { test.Logf("Test '%s' failed:", parsingTest.Name) test.Logf("Expected token value '%v' does not match '%v'", expectedToken.Value, actualToken.Value) test.Fail() continue } } } } func noop(arguments ...interface{}) (interface{}, error) { return nil, nil }
{'content_hash': '2f197242f4e79a647b8c0f4765e351d5', 'timestamp': '', 'source': 'github', 'line_count': 1670, 'max_line_length': 124, 'avg_line_length': 19.104191616766467, 'alnum_prop': 0.582246740220662, 'repo_name': 'Knetic/govaluate', 'id': 'd57b80967d3223c5feb5a32e4d61b88fe1ea23d8', 'size': '31952', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'parsing_test.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Go', 'bytes': '177418'}, {'name': 'Shell', 'bytes': '760'}]}
<?xml version="1.0" encoding="UTF-8"?> <!-- - Sample namespace-based configuration - --> <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oauth2="http://www.springframework.org/schema/security/oauth2" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-1.0.xsd"> <http pattern="/resource/**" create-session="never" entry-point-ref="oauth2AuthenticationEntryPoint" access-decision-manager-ref="oauth2AccessDecisionManager"> <anonymous enabled="false" /> <intercept-url pattern="/resource/**" access="ROLE_USER,SCOPE_READ" /> <custom-filter ref="picResourceServer" before="PRE_AUTH_FILTER" /> <access-denied-handler ref="oauthAccessDeniedHandler" /> </http> <oauth2:resource-server id="picResourceServer" resource-id="pic-resource" token-services-ref="tokenServices" /> <http pattern="/oauth/token" create-session="stateless" authentication-manager-ref="clientAuthenticationManager" entry-point-ref="oauth2AuthenticationEntryPoint"> <intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" /> <anonymous enabled="false" /> <http-basic entry-point-ref="oauth2AuthenticationEntryPoint" /> <custom-filter ref="clientCredentialsTokenEndpointFilter" before="BASIC_AUTH_FILTER" /> <access-denied-handler ref="oauthAccessDeniedHandler" /> </http> <http access-denied-page="/login.jsp?error=true" authentication-manager-ref="authenticationManager"> <intercept-url pattern="/oauth/**" access="ROLE_USER" /> <intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" /> <form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?error=true" default-target-url="/index.jsp" /> <anonymous /> </http> <authentication-manager alias="authenticationManager"> <authentication-provider> <user-service id="userService"> <user name="admin" password="admin" authorities="ROLE_USER" /> </user-service> </authentication-provider> </authentication-manager> <beans:bean id="clientCredentialsTokenEndpointFilter" class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter"> <beans:property name="authenticationManager" ref="clientAuthenticationManager" /> </beans:bean> <beans:bean id="oauth2AuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint" /> <beans:bean id="oauthAccessDeniedHandler" class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" /> <authentication-manager id="clientAuthenticationManager"> <authentication-provider user-service-ref="oauth2ClientDetailsUserService" /> </authentication-manager> <beans:bean id="oauth2ClientDetailsUserService" class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService"> <beans:constructor-arg ref="clientDetailsService" /> </beans:bean> <oauth2:client-details-service id="clientDetailsService"> <oauth2:client client-id="m1" authorized-grant-types="password,authorization_code,refresh_token,implicit" secret="s1" scope="read,write,trust" authorities="ROLE_CLIENT, ROLE_TRUSTED_CLIENT" resource-ids="pic-resource" /> </oauth2:client-details-service> <beans:bean id="tokenServices" class="org.springframework.security.oauth2.provider.token.DefaultTokenServices"> <beans:property name="tokenStore" ref="tokenStore" /> <beans:property name="supportRefreshToken" value="true" /> <beans:property name="clientDetailsService" ref="clientDetailsService" /> </beans:bean> <beans:bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore"> </beans:bean> <oauth2:authorization-server client-details-service-ref="clientDetailsService" token-services-ref="tokenServices" user-approval-handler-ref="oauthUserApprovalHandler" user-approval-page="oauth_approval" error-page="oauth_error"> <oauth2:authorization-code /> <oauth2:implicit /> <oauth2:refresh-token /> <oauth2:client-credentials /> <oauth2:password /> </oauth2:authorization-server> <beans:bean id="oauthUserApprovalHandler" class="org.springframework.security.oauth2.provider.approval.DefaultUserApprovalHandler" /> <beans:bean id="oauth2AccessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased"> <beans:constructor-arg> <beans:list> <beans:bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" /> <beans:bean class="org.springframework.security.access.vote.RoleVoter" /> <beans:bean class="org.springframework.security.access.vote.AuthenticatedVoter" /> </beans:list> </beans:constructor-arg> </beans:bean> </beans:beans>
{'content_hash': '84a595ed63f81e80daa1d2cf1e760b5c', 'timestamp': '', 'source': 'github', 'line_count': 121, 'max_line_length': 157, 'avg_line_length': 45.83471074380165, 'alnum_prop': 0.7601875225387666, 'repo_name': 'levioZ/springSecurityOauth2', 'id': '885eaeb627d6ca89f96e72a4ff6510ae8859fc00', 'size': '5546', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'appDemo/target/appDemo/WEB-INF/applicationContext-security.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '25367'}]}
FROM balenalib/solidrun-imx6-ubuntu:eoan-build ENV NODE_VERSION 14.15.4 ENV YARN_VERSION 1.22.4 RUN for key in \ 6A010C5166006599AA17F08146C2130DFD2497F5 \ ; do \ gpg --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \ done \ && curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \ && echo "ffce90b07675434491361dfc74eee230f9ffc65c6c08efb88a18781bcb931871 node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && mkdir -p /opt/yarn \ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && npm config set unsafe-perm true -g --unsafe-perm \ && rm -rf /tmp/* CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \ && echo "Running test-stack@node" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Ubuntu eoan \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v14.15.4, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{'content_hash': 'c8a01e4b75bd5de09af8b5745a3f2309', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 692, 'avg_line_length': 66.85365853658537, 'alnum_prop': 0.7099598686610726, 'repo_name': 'nghiant2710/base-images', 'id': 'ce2d4d127f7bb93b26d59fbf176b02e348c9ccd4', 'size': '2762', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'balena-base-images/node/solidrun-imx6/ubuntu/eoan/14.15.4/build/Dockerfile', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '144558581'}, {'name': 'JavaScript', 'bytes': '16316'}, {'name': 'Shell', 'bytes': '368690'}]}
var Sources = $CL.namespace('SqlConnect.View.Sources'); $CL.require('Cl.Backbone.BlockingView'); Sources.Options = function() {}; Sources.Options = $CL.extendClass(Sources.Options, Cl.Backbone.BlockingView, { render : function() { this.parent.prototype.render.apply(this); if (!$CL.isEmpty(this.data.options)) { this.$el.find('select[name=sqlconnect-source-count-column]').val(this.data.options.countColumn); if (this.data.options.customSql) { this.$el.find('textarea[name=sqlconnect-source-custom-sql]').val(this.data.options.customSql); } } } });
{'content_hash': 'ee72d599010347b3f988d5d873d71c76', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 110, 'avg_line_length': 34.21052631578947, 'alnum_prop': 0.6276923076923077, 'repo_name': 'codeliner/ginger-ims', 'id': '081d1dc6469d2b881b15d969899987621caacf57', 'size': '650', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'module/SqlConnect/src/SqlConnect/Javascript/View/Sources/Options.js', 'mode': '33261', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '84729'}, {'name': 'JavaScript', 'bytes': '265425'}, {'name': 'PHP', 'bytes': '523207'}, {'name': 'Shell', 'bytes': '809'}]}
include(FindPackageHandleStandardArgs) find_path(FFTW_INCLUDE_DIR NAMES fftw3.h PATH_SUFFIXES include include/fftw HINTS ENV MKLROOT HINTS ENV FFTWROOT HINTS ENV FFTW_INC ) find_library(FFTW_LIBRARIES NAMES fftw3 PATH_SUFFIXES lib HINTS ENV MKLROOT HINTS ENV FFTW_DIR HINTS ENV FFTWROOT ) set(FFTW_INCLUDE_DIRS ${FFTW_INCLUDE_DIR}) if(FFTW_LIBRARIES MATCHES "NOTFOUND") # ok, fftw libraries not found. # MKL contains fftw, lets assume we use MKL # TODO: handle this properly set(FFTW_LIBRARIES "") find_package_handle_standard_args(FFTW REQUIRED_VARS FFTW_INCLUDE_DIR ) mark_as_advanced(FFTW_FOUND FFTW_INCLUDE_DIR) else() find_package_handle_standard_args(FFTW REQUIRED_VARS FFTW_INCLUDE_DIR FFTW_LIBRARIES) mark_as_advanced(FFTW_FOUND FFTW_INCLUDE_DIR FFTW_LIBRARIES) endif()
{'content_hash': '48fa9a8857e7df31546b884bdba04a16', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 62, 'avg_line_length': 25.151515151515152, 'alnum_prop': 0.7506024096385542, 'repo_name': 'electronic-structure/sirius', 'id': 'd261546f9ec8feb2a9b4a3d4b1bfb6ff23712246', 'size': '830', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'cmake/modules/FindFFTW.cmake', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'C', 'bytes': '80256'}, {'name': 'C++', 'bytes': '2742135'}, {'name': 'CSS', 'bytes': '99478'}, {'name': 'Cuda', 'bytes': '85058'}, {'name': 'FORTRAN', 'bytes': '904229'}, {'name': 'Groff', 'bytes': '3046'}, {'name': 'HTML', 'bytes': '25527'}, {'name': 'JavaScript', 'bytes': '1451'}, {'name': 'Makefile', 'bytes': '17141'}, {'name': 'PHP', 'bytes': '2203'}, {'name': 'Python', 'bytes': '343602'}, {'name': 'Shell', 'bytes': '314'}]}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_122-ea) on Thu Mar 02 11:05:13 PST 2017 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Package com.fasterxml.jackson.datatype.jsr310.ser.key (Jackson datatype: JSR310 2.9.0.pr1 API)</title> <meta name="date" content="2017-03-02"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Package com.fasterxml.jackson.datatype.jsr310.ser.key (Jackson datatype: JSR310 2.9.0.pr1 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?com/fasterxml/jackson/datatype/jsr310/ser/key/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Uses of Package com.fasterxml.jackson.datatype.jsr310.ser.key" class="title">Uses of Package<br>com.fasterxml.jackson.datatype.jsr310.ser.key</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/key/package-summary.html">com.fasterxml.jackson.datatype.jsr310.ser.key</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#com.fasterxml.jackson.datatype.jsr310.ser.key">com.fasterxml.jackson.datatype.jsr310.ser.key</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="com.fasterxml.jackson.datatype.jsr310.ser.key"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/key/package-summary.html">com.fasterxml.jackson.datatype.jsr310.ser.key</a> used by <a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/key/package-summary.html">com.fasterxml.jackson.datatype.jsr310.ser.key</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/key/class-use/ZonedDateTimeKeySerializer.html#com.fasterxml.jackson.datatype.jsr310.ser.key">ZonedDateTimeKeySerializer</a>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?com/fasterxml/jackson/datatype/jsr310/ser/key/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2017 <a href="http://fasterxml.com/">FasterXML</a>. All rights reserved.</small></p> </body> </html>
{'content_hash': 'e92b46947571eda7b2ef917761e295fe', 'timestamp': '', 'source': 'github', 'line_count': 159, 'max_line_length': 380, 'avg_line_length': 39.0251572327044, 'alnum_prop': 0.6288477034649477, 'repo_name': 'kevinjom/jackson-modules-java8', 'id': '14578e2fabfd180c6f49236394292c4badeba137', 'size': '6205', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'docs/javadoc/datetime/2.9.pr1/com/fasterxml/jackson/datatype/jsr310/ser/key/package-use.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '699284'}]}
#ifndef _TEST_H_ #define _TEST_H_ /********************* Header Files ***********************/ /* C Headers */ //#include <stdio.h> //#include <string.h> //#include <stdlib.h> /* atof, rand, malloc... */ //#include <stddef.h> /* size_t, NULL */ //#include <stdarg.h> /* Variable argument functions */ //#include <ctype.h> /* Character check functions */ //#include <limits.h> //#include <assert.h> //$include <math.h> //$include <stdint.h> /* C11, standard u_int16 & such */ /* Project Headers */ /******************* Constants/Macros *********************/ /******************* Type Declarations ********************/ /* For enums: Try to namesapce the common elements. * typedef enum { * VAL_, * } name_e; */ /* For structs: * typedef struct name_s { * int index; * } name_t; */ /********************** Prototypes ************************/ #endif /* _TEST_H_ */
{'content_hash': '882e76a4f5e8c4327fceaa481c14f98f', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 60, 'avg_line_length': 23.18421052631579, 'alnum_prop': 0.49148694665153236, 'repo_name': 'starcraftman/.my_scripts', 'id': '476ec6e0fb6258f7ca90bf4d60991d40b24ca43c', 'size': '881', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'bin/templates/c_template.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '914'}, {'name': 'C++', 'bytes': '4884'}, {'name': 'Common Lisp', 'bytes': '3217'}, {'name': 'Makefile', 'bytes': '14820'}, {'name': 'Objective-C', 'bytes': '881'}, {'name': 'Perl', 'bytes': '14953'}, {'name': 'Python', 'bytes': '87094'}, {'name': 'Ruby', 'bytes': '11415'}, {'name': 'Shell', 'bytes': '15604'}]}
package org.owasp.webgoat.plugin.db_cross_site; import org.owasp.webgoat.plugin.GoatHillsFinancial.DefaultLessonAction; import org.owasp.webgoat.plugin.GoatHillsFinancial.Employee; import org.owasp.webgoat.plugin.GoatHillsFinancial.GoatHillsFinancial; import org.owasp.webgoat.plugin.GoatHillsFinancial.LessonAction; import org.owasp.webgoat.session.ParameterNotFoundException; import org.owasp.webgoat.session.UnauthenticatedException; import org.owasp.webgoat.session.UnauthorizedException; import org.owasp.webgoat.session.ValidationException; import org.owasp.webgoat.session.WebSession; import javax.servlet.http.HttpServletRequest; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class UpdateProfileDBCrossSiteScripting extends DefaultLessonAction { private LessonAction chainedAction; public UpdateProfileDBCrossSiteScripting(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction) { super(lesson, lessonName, actionName); this.chainedAction = chainedAction; } public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, UnauthorizedException, ValidationException { if (isAuthenticated(s)) { int userId = getIntSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID); HttpServletRequest request = s.getRequest(); int subjectId = Integer.parseInt(request.getParameter(DBCrossSiteScripting.EMPLOYEE_ID)); String firstName = request.getParameter(DBCrossSiteScripting.FIRST_NAME); String lastName = request.getParameter(DBCrossSiteScripting.LAST_NAME); String ssn = request.getParameter(DBCrossSiteScripting.SSN); String title = request.getParameter(DBCrossSiteScripting.TITLE); String phone = request.getParameter(DBCrossSiteScripting.PHONE_NUMBER); String address1 = request.getParameter(DBCrossSiteScripting.ADDRESS1); String address2 = request.getParameter(DBCrossSiteScripting.ADDRESS2); int manager = Integer.parseInt(request.getParameter(DBCrossSiteScripting.MANAGER)); String startDate = request.getParameter(DBCrossSiteScripting.START_DATE); int salary = Integer.parseInt(request.getParameter(DBCrossSiteScripting.SALARY)); String ccn = request.getParameter(DBCrossSiteScripting.CCN); int ccnLimit = Integer.parseInt(request.getParameter(DBCrossSiteScripting.CCN_LIMIT)); String disciplinaryActionDate = request.getParameter(DBCrossSiteScripting.DISCIPLINARY_DATE); String disciplinaryActionNotes = request.getParameter(DBCrossSiteScripting.DISCIPLINARY_NOTES); String personalDescription = request.getParameter(DBCrossSiteScripting.DESCRIPTION); Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2, manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes, personalDescription); try { if (subjectId > 0) { this.changeEmployeeProfile(s, userId, subjectId, employee); setRequestAttribute(s, getLessonName() + "." + DBCrossSiteScripting.EMPLOYEE_ID, Integer .toString(subjectId)); if (DBCrossSiteScripting.STAGE1.equals(getStage(s))) { address1 = address1.toLowerCase(); boolean pass = address1.contains("<script>"); pass &= address1.contains("alert"); pass &= address1.contains("</script>"); if (pass) { setStageComplete(s, DBCrossSiteScripting.STAGE1); } } } else this.createEmployeeProfile(s, userId, employee); } catch (SQLException e) { s.setMessage("Error updating employee profile"); e.printStackTrace(); if (DBCrossSiteScripting.STAGE2.equals(getStage(s)) && (e.getMessage().contains("ORA-06512") || e.getMessage().contains("Illegal characters")) && !employee.getAddress1().matches("^[a-zA-Z0-9,\\. ]{0,80}$")) { setStageComplete(s, DBCrossSiteScripting.STAGE2); } } try { chainedAction.handleRequest(s); } catch (UnauthenticatedException ue1) { // System.out.println("Internal server error"); ue1.printStackTrace(); } catch (UnauthorizedException ue2) { // System.out.println("Internal server error"); ue2.printStackTrace(); } } else throw new UnauthenticatedException(); } public String getNextPage(WebSession s) { return DBCrossSiteScripting.VIEWPROFILE_ACTION; } public void changeEmployeeProfile(WebSession s, int userId, int subjectId, Employee employee) throws SQLException { String update = " { CALL UPDATE_EMPLOYEE(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) }"; CallableStatement call = WebSession.getConnection(s).prepareCall(update); // Note: The password field is ONLY set by ChangePassword call.setInt(1, userId); call.setString(2, employee.getFirstName()); call.setString(3, employee.getLastName()); call.setString(4, employee.getSsn()); call.setString(5, employee.getTitle()); call.setString(6, employee.getPhoneNumber()); call.setString(7, employee.getAddress1()); call.setString(8, employee.getAddress2()); call.setInt(9, employee.getManager()); call.setString(10, employee.getStartDate()); call.setInt(11, employee.getSalary()); call.setString(12, employee.getCcn()); call.setInt(13, employee.getCcnLimit()); call.setString(14, employee.getDisciplinaryActionDate()); call.setString(15, employee.getDisciplinaryActionNotes()); call.setString(16, employee.getPersonalDescription()); call.executeUpdate(); } public void createEmployeeProfile(WebSession s, int userId, Employee employee) throws UnauthorizedException { try { int nextId = getNextUID(s); String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; try { PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query); ps.setString(1, employee.getFirstName().toLowerCase()); ps.setString(2, employee.getLastName()); ps.setString(3, employee.getSsn()); ps.setString(4, employee.getTitle()); ps.setString(5, employee.getPhoneNumber()); ps.setString(6, employee.getAddress1()); ps.setString(7, employee.getAddress2()); ps.setInt(8, employee.getManager()); ps.setString(9, employee.getStartDate()); ps.setString(10, employee.getCcn()); ps.setInt(11, employee.getCcnLimit()); ps.setString(12, employee.getDisciplinaryActionDate()); ps.setString(13, employee.getDisciplinaryActionNotes()); ps.setString(14, employee.getPersonalDescription()); ps.execute(); } catch (SQLException sqle) { s.setMessage("Error updating employee profile"); sqle.printStackTrace(); } } catch (Exception e) { s.setMessage("Error updating employee profile"); e.printStackTrace(); } } private int getNextUID(WebSession s) { int uid = -1; try { Statement statement = WebSession.getConnection(s).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet results = statement.executeQuery("select max(userid) as uid from employee"); results.first(); uid = results.getInt("uid"); } catch (SQLException sqle) { sqle.printStackTrace(); s.setMessage("Error updating employee profile"); } return uid + 1; } }
{'content_hash': 'eec0d297b3bc76e40f3130914ef500bb', 'timestamp': '', 'source': 'github', 'line_count': 199, 'max_line_length': 137, 'avg_line_length': 44.90954773869347, 'alnum_prop': 0.6055723397113125, 'repo_name': 'aseemsbapat/test', 'id': 'a14823155fce0d70c961109dda0149c9c3cafeba', 'size': '10166', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'UpdateProfileDBCrossSiteScripting.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '522'}, {'name': 'CSS', 'bytes': '32037'}, {'name': 'HTML', 'bytes': '1085343'}, {'name': 'Java', 'bytes': '1094660'}, {'name': 'JavaScript', 'bytes': '372790'}, {'name': 'PHP', 'bytes': '172910'}, {'name': 'Roff', 'bytes': '22608'}]}
<?php namespace app\models; use Yii; use yii\base\Model; use yii\data\ActiveDataProvider; use app\models\Clientes; /** * ClientesSearch represents the model behind the search form about `app\models\Clientes`. */ class ClientesSearch extends Clientes { /** * @inheritdoc */ public function rules() { return [ [['idClientes', 'prioridad', 'telefono'], 'integer'], [['ci_cliente', 'nombre', 'horario_atencion', 'email'], 'safe'], ]; } /** * @inheritdoc */ public function scenarios() { // bypass scenarios() implementation in the parent class return Model::scenarios(); } /** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = Clientes::find(); // add conditions that should always apply here $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails // $query->where('0=1'); return $dataProvider; } // grid filtering conditions $query->andFilterWhere([ 'idClientes' => $this->idClientes, 'prioridad' => $this->prioridad, 'telefono' => $this->telefono, ]); $query->andFilterWhere(['like', 'ci_cliente', $this->ci_cliente]) ->andFilterWhere(['like', 'nombre', $this->nombre]) ->andFilterWhere(['like', 'horario_atencion', $this->horario_atencion]) ->andFilterWhere(['like', 'email', $this->email]); return $dataProvider; } }
{'content_hash': 'b37fd0dd039133410e0d765b85b31774', 'timestamp': '', 'source': 'github', 'line_count': 74, 'max_line_length': 106, 'avg_line_length': 25.18918918918919, 'alnum_prop': 0.5574034334763949, 'repo_name': 'Nacho2126/php20162', 'id': 'c1cd90f235b749d1d52827dc04a0d6b9754115d1', 'size': '1864', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'backend/models/ClientesSearch.php', 'mode': '33261', 'license': 'bsd-3-clause', 'language': [{'name': 'ApacheConf', 'bytes': '342'}, {'name': 'Batchfile', 'bytes': '1546'}, {'name': 'CSS', 'bytes': '161818'}, {'name': 'HTML', 'bytes': '25298'}, {'name': 'JavaScript', 'bytes': '364350'}, {'name': 'PHP', 'bytes': '240791'}, {'name': 'Shell', 'bytes': '3256'}]}
package pivkey import ( "github.com/go-piv/piv-go/piv" ) func SlotForName(slotName string) *piv.Slot { switch slotName { case "": return &piv.SlotSignature case "authentication": return &piv.SlotAuthentication case "signature": return &piv.SlotSignature case "card-authentication": return &piv.SlotCardAuthentication case "key-management": return &piv.SlotKeyManagement default: return nil } } func PINPolicyForName(policyName string, slot piv.Slot) piv.PINPolicy { switch policyName { case "": return defaultPINPolicyForSlot(slot) case "never": return piv.PINPolicyNever case "once": return piv.PINPolicyOnce case "always": return piv.PINPolicyAlways default: return -1 } } func TouchPolicyForName(policyName string, slot piv.Slot) piv.TouchPolicy { switch policyName { case "": return defaultTouchPolicyForSlot(slot) case "never": return piv.TouchPolicyNever case "cached": return piv.TouchPolicyCached case "always": return piv.TouchPolicyAlways default: return -1 } } func defaultPINPolicyForSlot(slot piv.Slot) piv.PINPolicy { // // Defaults from https://developers.yubico.com/PIV/Introduction/Certificate_slots.html // switch slot { case piv.SlotAuthentication: return piv.PINPolicyOnce case piv.SlotSignature: return piv.PINPolicyAlways case piv.SlotKeyManagement: return piv.PINPolicyOnce case piv.SlotCardAuthentication: return piv.PINPolicyNever default: // This should never happen panic("invalid value for slot") } } func defaultTouchPolicyForSlot(slot piv.Slot) piv.TouchPolicy { // // Defaults from https://developers.yubico.com/PIV/Introduction/Certificate_slots.html // switch slot { case piv.SlotAuthentication: return piv.TouchPolicyCached case piv.SlotSignature: return piv.TouchPolicyAlways case piv.SlotKeyManagement: return piv.TouchPolicyCached case piv.SlotCardAuthentication: return piv.TouchPolicyNever default: // This should never happen panic("invalid value for slot") } }
{'content_hash': '776ea3c863945fe997a86eb7014ae009', 'timestamp': '', 'source': 'github', 'line_count': 92, 'max_line_length': 87, 'avg_line_length': 21.83695652173913, 'alnum_prop': 0.7610751617720258, 'repo_name': 'tektoncd/operator', 'id': 'a323716e6b4d31588890f94ad9ab34da28b70d05', 'size': '2655', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'vendor/github.com/sigstore/cosign/pkg/cosign/pivkey/util.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '1972'}, {'name': 'Go', 'bytes': '1049401'}, {'name': 'Makefile', 'bytes': '7852'}, {'name': 'Python', 'bytes': '14477'}, {'name': 'Shell', 'bytes': '42938'}, {'name': 'Smarty', 'bytes': '4243'}]}
<macros> <token name="@TOOL_VERSION@">3.4</token> <token name="@GALAXY_TOOL_VERSION@">galaxy1</token> <xml name="edam_ontology"> <edam_topics> <edam_topic>topic_0632</edam_topic> </edam_topics> <edam_operations> <edam_operation>operation_0231</edam_operation> </edam_operations> </xml> <xml name="requirements"> <requirements> <requirement type="package" version="@TOOL_VERSION@">cutadapt</requirement> </requirements> </xml> <xml name="citations"> <citations> <citation type="doi">10.14806/ej.17.1.200</citation> </citations> </xml> <xml name="xrefs"> <xrefs> <xref type='bio.tools'>cutadapt</xref> </xrefs> </xml> <token name="@read1_options@"><![CDATA[ ## Read1 trimming #for $a in $library.r1.adapters #if $a.adapter_source.adapter_source_list == 'builtin': -a '${a.adapter_source.adapter.fields.name}'='${a.adapter_source.adapter}${adapter_options.internal}' #else if $a.adapter_source.adapter_source_list == 'file': -a file:'${a.adapter_source.adapter_file}${adapter_options.internal}' #else if str($a.adapter_source.adapter_name) != "": -a '${a.adapter_source.adapter_name}'='${a.adapter_source.adapter}${adapter_options.internal}' #else -a '${a.adapter_source.adapter}${adapter_options.internal}' #end if #end for #for $aa in $library.r1.anywhere_adapters #if $aa.anywhere_adapter_source.anywhere_adapter_source_list == 'builtin': -b '${aa.anywhere_adapter_source.anywhere_adapter.fields.name}'='${aa.anywhere_adapter_source.anywhere_adapter}' #else if $aa.anywhere_adapter_source.anywhere_adapter_source_list == 'file': -b file:'${aa.anywhere_adapter_source.anywhere_adapter_file}' #else if str($aa.anywhere_adapter_source.anywhere_adapter_name) != "": -b '${aa.anywhere_adapter_source.anywhere_adapter_name}'='${aa.anywhere_adapter_source.anywhere_adapter}' #else -b '${aa.anywhere_adapter_source.anywhere_adapter}' #end if #end for #for $fa in $library.r1.front_adapters #if $fa.front_adapter_source.front_adapter_source_list == 'builtin': -g '${fa.front_adapter_source.front_adapter.fields.name}'='${adapter_options.internal}${fa.front_adapter_source.front_adapter}' #else if $fa.front_adapter_source.front_adapter_source_list == 'file': -g file:'${adapter_options.internal}${fa.front_adapter_source.front_adapter_file}' #else if str($fa.front_adapter_source.front_adapter_name) != "": -g '${fa.front_adapter_source.front_adapter_name}'='${adapter_options.internal}${fa.front_adapter_source.front_adapter}' #else -g '${adapter_options.internal}${fa.front_adapter_source.front_adapter}' #end if #end for #if str($library.r1.cut) != '0': -u $library.r1.cut #end if ## Additional Outputs #if 'info_file' in $output_selector: --info-file=$info_file #end if #if 'rest_file' in $output_selector: --rest-file='${rest_output}' #end if #if 'wildcard_file' in $output_selector: --wildcard-file='${wild_output}' #end if #if 'too_short_file' in $output_selector: --too-short-output='${too_short_output}' #end if #if 'too_long_file' in $output_selector: --too-long-output='${too_long_output}' #end if #if 'untrimmed_file' in $output_selector: --untrimmed-output='${untrimmed_output}' #end if ]]></token> <token name="@read2_options@"><![CDATA[ ## Read2 trimming #for $a in $library.r2.adapters2 #if $a.adapter_source2.adapter_source_list2 == 'builtin': -A '${a.adapter_source2.adapter2.fields.name}'='${a.adapter_source2.adapter2}${adapter_options.internal}' #else if $a.adapter_source2.adapter_source_list2 == 'file': -A file:'${a.adapter_source2.adapter_file2}${adapter_options.internal}' #else if str($a.adapter_source2.adapter_name2) != "": -A '${a.adapter_source2.adapter_name2}'='${a.adapter_source2.adapter2}${adapter_options.internal}' #else -A '${a.adapter_source2.adapter2}${adapter_options.internal}' #end if #end for #for $aa in $library.r2.anywhere_adapters2 #if $aa.anywhere_adapter_source2.anywhere_adapter_source_list2 == 'builtin': -B '${aa.anywhere_adapter_source2.anywhere_adapter2.fields.name}'='${aa.anywhere_adapter_source2.anywhere_adapter2}' #else if $aa.anywhere_adapter_source2.anywhere_adapter_source_list2 == 'file': -B file:'${aa.anywhere_adapter_source2.anywhere_adapter_file2}' #else if str($aa.anywhere_adapter_source2.anywhere_adapter_name2) != "": -B '${aa.anywhere_adapter_source2.anywhere_adapter_name2}'='${aa.anywhere_adapter_source2.anywhere_adapter2}' #else -B '${aa.anywhere_adapter_source2.anywhere_adapter2}' #end if #end for #for $fa in $library.r2.front_adapters2 #if $fa.front_adapter_source2.front_adapter_source_list2 == 'builtin': -G '${fa.front_adapter_source2.front_adapter2.fields.name}'='${adapter_options.internal}${fa.front_adapter_source2.front_adapter2}' #else if $fa.front_adapter_source2.front_adapter_source_list2 == 'file': -G file:'${adapter_options.internal}${fa.front_adapter_source2.front_adapter_file2}' #else if str($fa.front_adapter_source2.front_adapter_name2) != "": -G '${fa.front_adapter_source2.front_adapter_name2}'='${adapter_options.internal}${fa.front_adapter_source2.front_adapter2}' #else -G '${adapter_options.internal}${fa.front_adapter_source2.front_adapter2}' #end if #end for #if str($library.r2.cut2) != '0': -U $library.r2.cut2 #end if ## Additional Outputs - Read 2 #if 'too_short_file' in $output_selector: --too-short-paired-output='${too_short_paired_output}' #end if #if 'too_long_file' in $output_selector: --too-long-paired-output='${too_long_paired_output}' #end if #if 'untrimmed_file' in $output_selector: --untrimmed-paired-output='${untrimmed_paired_output}' #end if ]]></token> <xml name="adapter_sanitizer"> <sanitizer> <valid initial="string.digits"> <add value="A"/><!--standard nucleotides--> <add value="T"/> <add value="C"/> <add value="G"/> <add value="U"/><!--ambiguous nucleotides--> <add value="R"/> <add value="Y"/> <add value="S"/> <add value="W"/> <add value="K"/> <add value="M"/> <add value="B"/> <add value="D"/> <add value="H"/> <add value="V"/> <add value="N"/> <add value="X"/><!-- don't match any nucleotide--> <add value="{"/><!--specify repeats .. needs digits which are added as default--> <add value="}"/> <add value="^"/><!--anchoring--> <add value="$"/> <add value="."/> <add value="("/><!--specify what to keep--> <add value=")"/> </valid> </sanitizer> </xml> <xml name="adapter" token_name="" token_argument="" token_value="" token_label=""> <param name="@NAME@" argument="@ARGUMENT@" type="text" value="@VALUE@" label="@LABEL@"> <expand macro="adapter_sanitizer"/> </param> </xml> <xml name="adapter_select" token_name="" token_argument="" token_label=""> <param name="@NAME@" argument="@ARGUMENT@" type="select" label="@LABEL@"> <options from_data_table="adapters"> <filter type="sort_by" column="1" /> </options> <expand macro="adapter_sanitizer"/> </param> </xml> <xml name="single_end_options" > <section name="r1" title="Read 1 Options" expanded="True"> <repeat name="adapters" title="3' (End) Adapters" help="Sequence of an adapter ligated to the 3' end (paired data: of the first read). The adapter and subsequent bases are trimmed. If a '$' character is appended ('anchoring'), the adapter is only found if it is a suffix of the read. To search for a linked adapter, separate the 2 sequences with 3 dots (ADAPTER1...ADAPTER2), see Help below."> <conditional name="adapter_source"> <param name="adapter_source_list" type="select" label="Source" > <option value="builtin" selected="True">Standard (select from the list below)</option> <option value="user">Enter custom sequence</option> <option value="file">File from history</option> </param> <when value="user"> <param name="adapter_name" type="text" value="" optional="True" label="Enter custom 3' adapter name (Optional if Multiple output is 'No')" /> <expand macro="adapter" name="adapter" argument="-a" type="text" value="AATTGGCC" label="Enter custom 3' adapter sequence" /> </when> <when value="builtin"> <expand macro="adapter_select" name="adapter" argument="-a" label="Choose 3' adapter"/> </when> <when value="file"> <param name="adapter_file" argument="-a" format="fasta" type="data" help="Should be of datatype FASTA" label="Choose file containing 3' adapters" /> </when> </conditional> </repeat> <repeat name="front_adapters" title="5' (Front) Adapters" help="Sequence of an adapter ligated to the 5' end (paired data: of the first read). The adapter and any preceding bases are trimmed. Partial matches at the 5' end are allowed. If a '^' character is prepended ('anchoring'), the adapter is only found if it is a prefix of the read. To search for a linked adapter, separate the 2 sequences with 3 dots (ADAPTER1...ADAPTER2), see Help below."> <conditional name="front_adapter_source"> <param name="front_adapter_source_list" type="select" label="Source"> <option value="builtin" selected="True">Standard (select from the list below)</option> <option value="user">Enter custom sequence</option> <option value="file">File from history</option> </param> <when value="user"> <param name="front_adapter_name" type="text" value="" optional="True" label="Enter custom 5' adapter name (Optional if Multiple output is 'No')" /> <expand macro="adapter" name="front_adapter" argument="-g" value="AATTGGCC" label="Enter custom 5' adapter sequence" /> </when> <when value="builtin"> <expand macro="adapter_select" name="front_adapter" argument="-g" label="Choose 5' adapter"/> </when> <when value="file"> <param name="front_adapter_file" argument="-g" format="fasta" type="data" help="Should be of datatype &quot;FASTA&quot;" label="Choose file containing 5' adapters" /> </when> </conditional> </repeat> <repeat name="anywhere_adapters" title="5' or 3' (Anywhere) Adapters" help="Sequence of an adapter that may be ligated to the 5' or 3' end (paired data: of the first read). Both types of matches as described under 3' und 5' Adapters are allowed. If the first base of the read is part of the match, the behavior is as with 5' Adapters, otherwise as with 3' Adapters. This option is mostly for rescuing failed library preparations - do not use if you know which end your adapter was ligated to!"> <conditional name="anywhere_adapter_source"> <param name="anywhere_adapter_source_list" type="select" label="Source"> <option value="builtin" selected="True">Standard (select from the list below)</option> <option value="user">Enter custom sequence</option> <option value="file">File from history</option> </param> <when value="user"> <param name="anywhere_adapter_name" type="text" value="" optional="True" label="Enter custom 5' or 3' adapter name (Optional if Multiple output is 'No')" /> <expand macro="adapter" name="anywhere_adapter" argument="-b" value="AATTGGCC" label="Enter custom 5' or 3' adapter sequence" /> </when> <when value="builtin"> <expand macro="adapter_select" name="anywhere_adapter" argument="-b" label="Choose 5' or 3' adapter"/> </when> <when value="file"> <param name="anywhere_adapter_file" argument="-b" format="fasta" type="data" help="Should be of datatype &quot;FASTA&quot;" label="Choose file containing 3' or 5' adapters" /> </when> </conditional> </repeat> <param name="cut" argument="--cut" type="integer" value="0" optional="True" label="Cut bases from reads before adapter trimming" help="Remove bases from each read (first read only if paired). If positive, remove bases from the beginning. If negative, remove bases from the end. This is applied *before* adapter trimming." /> </section> </xml> <xml name="paired_end_options" > <!-- Read 1 Options --> <expand macro="single_end_options" /> <!-- Read 2 Options --> <section name="r2" title="Read 2 Options" expanded="True"> <repeat name="adapters2" title="3' (End) Adapters" help="Sequence of an adapter ligated to the 3' end of the second read in each pair. The adapter and subsequent bases are trimmed. If a '$' character is appended ('anchoring'), the adapter is only found if it is a suffix of the read. To search for a linked adapter, separate the 2 sequences with 3 dots (ADAPTER1...ADAPTER2), see Help below."> <conditional name="adapter_source2"> <param name="adapter_source_list2" type="select" label="Source" > <option value="builtin" selected="True">Standard (select from the list below)</option> <option value="user">Enter custom sequence</option> <option value="file">File from history</option> </param> <when value="user"> <param name="adapter_name2" type="text" value="" optional="True" label="Enter custom 3' adapter name (Optional)" /> <expand macro="adapter" name="adapter2" argument="-A" label="Enter custom 3' adapter sequence" value="AATTGGCC" /> </when> <when value="builtin"> <expand macro="adapter_select" name="adapter2" argument="-A" label="Choose 3' adapter"/> </when> <when value="file"> <param name="adapter_file2" argument="-a" format="fasta" type="data" help="Should be of datatype &quot;FASTA&quot;" label="Choose file containing 3' adapters" /> </when> </conditional> </repeat> <repeat name="front_adapters2" title="5' (Front) Adapters" help="Sequence of an adapter ligated to the 5' end of the second read in each pair. The adapter and any preceding bases are trimmed. Partial matches at the 5' end are allowed. If a '^' character is prepended ('anchoring'), the adapter is only found if it is a prefix of the read. To search for a linked adapter, separate the 2 sequences with 3 dots (ADAPTER1...ADAPTER2), see Help below."> <conditional name="front_adapter_source2"> <param name="front_adapter_source_list2" type="select" label="Source"> <option value="builtin" selected="True">Standard (select from the list below)</option> <option value="user">Enter custom sequence</option> <option value="file">File from history</option> </param> <when value="user"> <param name="front_adapter_name2" type="text" value="" label="Enter custom 5' adapter name (Optional)" /> <expand macro="adapter" name="front_adapter2" argument="-G" value="AATTGGCC" label="Enter custom 5' adapter sequence" /> </when> <when value="builtin"> <expand macro="adapter_select" name="front_adapter2" argument="-G" label="Choose 5' adapter"/> </when> <when value="file"> <param name="front_adapter_file2" argument="-g" format="fasta" type="data" help="Should be of datatype &quot;FASTA&quot;" label="Choose file containing 5' adapters" /> </when> </conditional> </repeat> <repeat name="anywhere_adapters2" title="5' or 3' (Anywhere) Adapters" help="Sequence of an adapter that may be ligated to the 5' or 3' end of the second read in each pair. Both types of matches as described under under 3' und 5' Adapters are allowed. If the first base of the read is part of the match, the behavior is as with 5' Adapters, otherwise as with 3' Adapters. This option is mostly for rescuing failed library preparations - do not use if you know which end your adapter was ligated to!"> <conditional name="anywhere_adapter_source2"> <param name="anywhere_adapter_source_list2" type="select" label="Source"> <option value="builtin" selected="True">Standard (select from the list below)</option> <option value="user">Enter custom sequence</option> <option value="file">File from history</option> </param> <when value="user"> <param name="anywhere_adapter_name2" type="text" value="" optional="True" label="Enter custom 5' or 3' adapter name (Optional)" /> <expand macro="adapter" name="anywhere_adapter2" argument="-B" label="Enter custom 5' or 3' adapter sequence" value="AATTGGCC" /> </when> <when value="builtin"> <expand macro="adapter_select" name="anywhere_adapter2" argument="-B" type="select" label="Choose 5' or 3' adapter"/> </when> <when value="file"> <param name="anywhere_adapter_file2" argument="-b" format="fasta" type="data" help="Should be of datatype &quot;FASTA&quot;" label="Choose file containing 3' or 5' adapters" /> </when> </conditional> </repeat> <param name="cut2" argument="-U" type="integer" value="0" optional="True" label="Cut bases from the second read in each pair." help="Remove bases from the beginning or end of each read before trimming adapters. If positive, the bases are removed from the beginning of each read. If negative, the bases are removed from the end of each read." /> </section> </xml> <xml name="inherit_format_1"> <actions> <conditional name="library.type"> <when value="single"> <action type="format"> <option type="from_param" name="library.input_1" param_attribute="ext" /> </action> </when> <when value="paired"> <action type="format"> <option type="from_param" name="library.input_1" param_attribute="ext" /> </action> </when> </conditional> </actions> </xml> <xml name="inherit_format_2"> <actions> <conditional name="library.type"> <when value="paired"> <action type="format"> <option type="from_param" name="library.input_2" param_attribute="ext" /> </action> </when> </conditional> </actions> </xml> </macros>
{'content_hash': '7273be33487bd7118b51d835119d7da2', 'timestamp': '', 'source': 'github', 'line_count': 381, 'max_line_length': 516, 'avg_line_length': 58.55380577427822, 'alnum_prop': 0.5371374781478327, 'repo_name': 'pjbriggs/tools-iuc', 'id': 'ba2b0fa5f8f53a75a531ba72d37f85cc9aaac6df', 'size': '22309', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tools/cutadapt/macros.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '4220'}, {'name': 'HTML', 'bytes': '11558401'}, {'name': 'Mako', 'bytes': '2116'}, {'name': 'Max', 'bytes': '140358'}, {'name': 'OpenEdge ABL', 'bytes': '1960016'}, {'name': 'Pep8', 'bytes': '87474'}, {'name': 'Perl', 'bytes': '58627'}, {'name': 'Python', 'bytes': '741604'}, {'name': 'R', 'bytes': '268177'}, {'name': 'Rebol', 'bytes': '1225'}, {'name': 'Roff', 'bytes': '3011'}, {'name': 'Shell', 'bytes': '84319'}, {'name': 'UnrealScript', 'bytes': '660637'}, {'name': 'eC', 'bytes': '24'}]}
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var React = require('react'); var tooltip = require('primereact/tooltip'); var utils = require('primereact/utils'); function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); } n["default"] = e; return Object.freeze(n); } var React__namespace = /*#__PURE__*/_interopNamespace(React); function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } var InputSwitch = /*#__PURE__*/React__namespace.memo( /*#__PURE__*/React__namespace.forwardRef(function (props, ref) { var _React$useState = React__namespace.useState(false), _React$useState2 = _slicedToArray(_React$useState, 2), focusedState = _React$useState2[0], setFocusedState = _React$useState2[1]; var elementRef = React__namespace.useRef(null); var inputRef = React__namespace.useRef(props.inputRef); var checked = props.checked === props.trueValue; var onClick = function onClick(event) { if (props.disabled) { return; } toggle(event); utils.DomHandler.focus(inputRef.current); event.preventDefault(); }; var toggle = function toggle(event) { if (props.onChange) { var value = checked ? props.falseValue : props.trueValue; props.onChange({ originalEvent: event, value: value, stopPropagation: function stopPropagation() {}, preventDefault: function preventDefault() {}, target: { name: props.name, id: props.id, value: value } }); } }; var onFocus = function onFocus(event) { setFocusedState(true); props.onFocus && props.onFocus(event); }; var onBlur = function onBlur(event) { setFocusedState(false); props.onBlur && props.onBlur(event); }; React__namespace.useImperativeHandle(ref, function () { return _objectSpread({ getElement: function getElement() { return elementRef.current; }, getInput: function getInput() { return elementRef.current; } }, props); }); React__namespace.useEffect(function () { utils.ObjectUtils.combinedRefs(inputRef, props.inputRef); }, [inputRef, props.inputRef]); var hasTooltip = utils.ObjectUtils.isNotEmpty(props.tooltip); var otherProps = utils.ObjectUtils.findDiffKeys(props, InputSwitch.defaultProps); var className = utils.classNames('p-inputswitch p-component', { 'p-inputswitch-checked': checked, 'p-disabled': props.disabled, 'p-focus': focusedState }, props.className); return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/React__namespace.createElement("div", _extends({ ref: elementRef, id: props.id, className: className, style: props.style }, otherProps, { onClick: onClick, role: "checkbox", "aria-checked": checked }), /*#__PURE__*/React__namespace.createElement("div", { className: "p-hidden-accessible" }, /*#__PURE__*/React__namespace.createElement("input", { ref: inputRef, type: "checkbox", id: props.inputId, name: props.name, checked: checked, onChange: toggle, onFocus: onFocus, onBlur: onBlur, disabled: props.disabled, role: "switch", tabIndex: props.tabIndex, "aria-checked": checked, "aria-labelledby": props['aria-labelledby'], "aria-label": props['aria-label'] })), /*#__PURE__*/React__namespace.createElement("span", { className: "p-inputswitch-slider" })), hasTooltip && /*#__PURE__*/React__namespace.createElement(tooltip.Tooltip, _extends({ target: elementRef, content: props.tooltip }, props.tooltipOptions))); })); InputSwitch.displayName = 'InputSwitch'; InputSwitch.defaultProps = { __TYPE: 'InputSwitch', id: null, inputRef: null, style: null, className: null, inputId: null, name: null, tabIndex: null, checked: false, trueValue: true, falseValue: false, disabled: false, tooltip: null, tooltipOptions: null, 'aria-label': null, 'aria-labelledby': null, onChange: null, onFocus: null, onBlur: null }; exports.InputSwitch = InputSwitch;
{'content_hash': '094e587a17c4ee77902e347534369fb8', 'timestamp': '', 'source': 'github', 'line_count': 249, 'max_line_length': 506, 'avg_line_length': 30.248995983935743, 'alnum_prop': 0.6319702602230484, 'repo_name': 'cdnjs/cdnjs', 'id': 'b263e1fd46e8ff5512b9d5b112066e325aa0c9ac', 'size': '7532', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ajax/libs/primereact/8.3.0/inputswitch/inputswitch.cjs.js', 'mode': '33188', 'license': 'mit', 'language': []}
var Event = function Event(Title, WorldWar, SocialStability, TechnologicalProgress, Message, Event_Variable) { this.Title = Title; this.WorldWar = WorldWar; this.SocialStability = SocialStability; this.TechnologicalProgress = TechnologicalProgress; this.Message = Message; this.Event_Variable = Event_Variable; } //Protoype allows us to implement pseudoclasses into Javascript. //It is necessary to define the 'call' method on the Event Constructor so that we can trigger the //event's effects. Event.prototype = { call: function() { Metrics.WorldWar += this.WorldWar; Metrics.SocialStability += this.SocialStability; Metrics.TechnologicalProgress += this.TechnologicalProgress; if (this.Event_Variable == "CityFive") { CityFive = true; } return (this.Message + "<button class='deleteEvent' id='"+this.Title+"'>Delete</button>") } }; //An EmptyEvent exist if you delete an event from the Timeline. It is created //so that I don't have to worry about calling "undefined" events. var EmptyEvent = function () { } //At the beginning of the game, the following four events are inserted into the Timeline and are triggered. //new Event(WorldWar, SocialStability, TechnologicalProgress, Message, optional Event_Varaible) var CityFiveBuilt = new Event("CityFiveBuilt",-20,0,20, CITY_FIVE_BUILT,"CityFive") var TheOrder = new Event("TheOrder",0,20,-20, THE_ORDER); //In the original version of Zybourne Clock, Dr. Zybourne developed his time-travelling Clock after the World War. But I do not want to implement events being dependent on each other until AFTER the MVP. var ClockInvented = new Event("ClockInvented", -20,0,20, CLOCK_INVENTED); var Zepplins = new Event("Zepplins",-20,20,0, ZEPPLINS); //These events are in the Player's hand at the start of Zybourne Clock Redux. This is just a MVP, so I only have two events here for now. var ChildSpybots = new Event("ChildSpybots",20,-20,0, CHILD_SPYBOTS) var Vaundermause = new Event("Vaundermause",20,0,-20, VAUNDERMAUSE) var SocialPlanningRevolution = new Event("SocialPlanningRevolution",-40,20,20, SOCIAL_PLANNING) var Nanotech = new Event("Nanotech",20,-40,20, NANOTECH) var LuddistCrusade = new Event("LuddistCrusade",0,40,-40, LUDDIST_CRUSADE) var Timeline = [] var PlayerHand = [ChildSpybots, Vaundermause, SocialPlanningRevolution, Nanotech, LuddistCrusade]
{'content_hash': '14b4e1f5ba710e7c0cdf6fef5a72fcd1', 'timestamp': '', 'source': 'github', 'line_count': 55, 'max_line_length': 203, 'avg_line_length': 43.163636363636364, 'alnum_prop': 0.7502106149957877, 'repo_name': 'tra38/Zybourne-Clock-Redux', 'id': '37a1a89af37f147eccff2172bb4682b95be13b1b', 'size': '2533', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/assets/javascripts/timeline_events.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '928'}, {'name': 'CoffeeScript', 'bytes': '211'}, {'name': 'HTML', 'bytes': '7737'}, {'name': 'JavaScript', 'bytes': '22687'}, {'name': 'Ruby', 'bytes': '21100'}]}
using System; using System.Collections.Generic; using System.Linq; using MonoTouch.Foundation; using MonoTouch.UIKit; namespace Linq2TwitterSample { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { get; set; } // This method is invoked when the application is about to move from active to inactive state. // OpenGL applications should use this method to pause. public override void OnResignActivation (UIApplication application) { } // This method should be used to release shared resources and it should store the application state. // If your application supports background exection this method is called instead of WillTerminate // when the user quits. public override void DidEnterBackground (UIApplication application) { } // This method is called as part of the transiton from background to active state. public override void WillEnterForeground (UIApplication application) { } // This method is called when the application is about to terminate. Save data, if needed. public override void WillTerminate (UIApplication application) { } } }
{'content_hash': 'dcc28da19aa0881a6b9bc1aa83aad202', 'timestamp': '', 'source': 'github', 'line_count': 47, 'max_line_length': 102, 'avg_line_length': 30.595744680851062, 'alnum_prop': 0.7600834492350487, 'repo_name': 'SotoiGhost/Linq2TwitterSample', 'id': '4197deb07c8adc0a020d77dec7abc30d27d93584', 'size': '1440', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Linq2TwitterSample/AppDelegate.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '6431'}]}
package nl.soccar.library.test; import java.time.LocalTime; import java.util.Optional; import nl.soccar.library.Event; import nl.soccar.library.Game; import nl.soccar.library.Player; import nl.soccar.library.enumeration.CarType; import nl.soccar.library.enumeration.Duration; import nl.soccar.library.enumeration.EventType; import nl.soccar.library.enumeration.GameStatus; import nl.soccar.library.enumeration.Privilege; import nl.soccar.ui.DisplayConstants; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * JUnit test that tests the nl.soccar.library.Game class. * * @author PTS34A */ public class GameTest { // Declaration of test objects. private Player player; private Event event; private Game game; /** * Instantiation of test objects. */ @Before public void setUp() { player = new Player("username", Privilege.NORMAL, CarType.CASUAL); event = new Event(EventType.GOAL_RED, LocalTime.of(13, 55, 03), player); game = new Game(); } /** * Tests the start method. */ @Test public void startTest() { game.start(); assertEquals(GameStatus.RUNNING, game.getStatus()); } /** * Tests the stop method. */ @Test public void stopTest() { game.stop(); assertEquals(GameStatus.STOPPED, game.getStatus()); } /** * Tests the addEvent and getEvents methods. */ @Test public void addEventAndGetEventsTest() { game.addEvent(event); assertEquals(event, game.getEvents().get(0)); } /** * Tests the getStarttime method. */ @Test public void getStartTimeTest() { assertEquals(Optional.empty(), game.getStartTime()); } /** * Tests the getStatus and setStatus methods. */ @Test public void getStatusAndSetStatusTest() { assertEquals(GameStatus.STOPPED, game.getStatus()); game.setStatus(GameStatus.SCORED); assertEquals(GameStatus.SCORED, game.getStatus()); } /** * Tests the getDuration and setDuration methods. */ @Test public void getDurationAndSetDurationTest() { game.setDuration(Duration.MINUTES_3); assertEquals(Duration.MINUTES_3, game.getDuration()); } /** * Tests the getMap method. */ @Test public void getMapTest() { assertEquals(0, Math.round(game.getMap().getSize().getX())); assertEquals(0, Math.round(game.getMap().getSize().getY())); assertEquals(Math.round(DisplayConstants.MAP_WIDTH), Math.round(game.getMap().getSize().getWidth())); assertEquals(Math.round(DisplayConstants.MAP_HEIGHT), Math.round(game.getMap().getSize().getHeight())); } /** * Tests the getLastBallTouched andSetLastBallTouched methods. */ @Test public void getLastBallTouchedAndSetLastBallTouchedTest() { game.setLastBallTouched(player); assertEquals(player, game.getLastBallTouched()); } }
{'content_hash': 'efcaef1e7ed640ec248955d49738e987', 'timestamp': '', 'source': 'github', 'line_count': 114, 'max_line_length': 111, 'avg_line_length': 27.69298245614035, 'alnum_prop': 0.6262274311054798, 'repo_name': 'PTS3-S34A/Soccar', 'id': 'c2bb3a3834ae9819ea3957941f620832347a8138', 'size': '3157', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Soccar [Client]/test/nl/soccar/library/test/GameTest.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1119'}, {'name': 'Java', 'bytes': '191451'}]}
// tjh Headers #include "../src/Publisher.h" // System Headers #include <functional> #include <memory> #include <iostream> #include <string> namespace tjh { namespace example { //! A listener class which subscribes to an exterior publication. class Client { public: //! @note: There is no constraint requiring an IPublisher to be passed into the //! constructor of a listener, this pattern was simply used to demonstrate the //! mechanism of subscription. The shared_ptr callback and the IPublisher object //! just, at some point, need to exist in the same scope. Client(IPublisher<int, const std::string&>& publisher) { // If the Client is going to subsribe to publications, it needs to create // a callback object. This callback object is a shared_ptr owned by the // Client; the callback will have the same life-span as the naked // "this" created within the bound function. This ensures that the // bound function is either valid, or its parent shared_ptr has // already been destructed because the object itself no longer exists. _callback = tjh::make_callback(&Client::handler, this); // The shared_ptr is provided to the IPublisher interface, and the IPublisher // interface holds a weak_ptr that is checked for validity before the callback is // fired. publisher.subscribe(_callback); } private: void handler(int a, const std::string& b) { // Published arguments! std::cout << __FUNCTION__ << ": a=" << a << ", b=" << b << std::endl; // Upon receiving a publication from the subscriber, the listener has determined // it no longer needs to exist, so it deletes itself. This deletion nulls the // weak_ptr held in the IPublisher object which will be cleaned up during the // next publication. // @note: The below line ONLY works if the object was heap allocated; if the // object was allocated on the stack, a double deletion will occur. delete this; } // The callback object enforces the requirement that this instance's lifetime is the // same as the contained function's lifetime. std::shared_ptr<std::function<void(int, const std::string&)>> _callback; }; class Primary : public IPublisher<int, const std::string&> { public: virtual void subscribe(std::weak_ptr<std::function<void(int, const std::string&)> > callback) { // This is a simple pass through to the composed publisher. _publisher.subscribe(callback); } void doSomething(int a, const std::string& b) { // Publish the contents of a and b to any listeners. _publisher.publish(a, b); } private: tjh::Publisher<Primary, int, const std::string&> _publisher; }; } // end example } // end tjh #endif // EXAMPLE_H
{'content_hash': '38729259009835b30d73bdffd602ffb1', 'timestamp': '', 'source': 'github', 'line_count': 83, 'max_line_length': 97, 'avg_line_length': 35.734939759036145, 'alnum_prop': 0.6429534726904923, 'repo_name': 'tjhalva/Publisher', 'id': 'e5f194b73824ab8ce47569e6a7eb58272522308b', 'size': '3004', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/Example.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '13338'}]}
module RspecWiki class Markdown attr_reader :context def initialize context @context = context end def anchor_link { anchor_group => "* [#{title_with_status}](#{RspecWiki.configuration.wiki_page_url}##{title_anchor})"} end def anchor_group return "#{h3}#{context.metadata[:group]}" if context.metadata[:group].present? described_class = context.described_class.split("::").last described_class.gsub!('Controller', '') described_class.underscore.humanize.prepend(h3) end def print <<-EOC #{header} #{body} #{footer} EOC end def header "#{h3}#{title}" end def body <<-EOC #{description} #{url} | #{request_method} #{parameters} Response #{status} #{javascript(context.response_body)} EOC end def footer <<-EOC #{ back_to_table_of_content } #{ '='*100 } EOC end def description <<-EOC `#{context.content}` EOC end def status "Status: \`#{context.response_status}\`" end def parameters "Parameters: #{format_params}" end def url "URL: __#{context.request_path}__" end def request_method "Method: \`#{context.request_method}\`" end private def title (context.metadata[:title] || context.content).humanize end def title_with_status status = context.response_success? ? "(SUCCESS)" : "(ERROR)" "#{title} #{status}" end def title_anchor title.downcase.gsub(/\s+/, '-') end def format_params context.params.collect do |key, value| "\`#{key}\` => #{value}" end.join("\n\n") end def h3 '###' end def javascript content <<-EOC ```javascript #{content} ``` EOC end def back_to_table_of_content "[Back to table of contents](#{RspecWiki.configuration.wiki_page_url}#table-of-contents)" end end end
{'content_hash': '8be93f2c1b0eacfea0fd5da8a1eefd47', 'timestamp': '', 'source': 'github', 'line_count': 114, 'max_line_length': 109, 'avg_line_length': 17.13157894736842, 'alnum_prop': 0.5734767025089605, 'repo_name': 'nlds90/rspec_wiki', 'id': '91ac239716d4a828d05ed2680bc618fa37860b8b', 'size': '1953', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/rspec_wiki/formatter/markdown.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '683'}, {'name': 'HTML', 'bytes': '4883'}, {'name': 'JavaScript', 'bytes': '599'}, {'name': 'Ruby', 'bytes': '26134'}]}
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Graphina chloroleuca Müll. Arg. ### Remarks null
{'content_hash': 'b6d01ef3643e7f4bb4be5fd89fb77ee0', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 10.461538461538462, 'alnum_prop': 0.7058823529411765, 'repo_name': 'mdoering/backbone', 'id': '808b6cdb5c3858b5bb710b66ea453efb4233e682', 'size': '193', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Fungi/Ascomycota/Lecanoromycetes/Ostropales/Graphidaceae/Graphina/Graphina chloroleuca/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
//===----------------------------------------------------------------------===// // // Peloton // // abstract_scan_executor.h // // Identification: src/include/executor/abstract_scan_executor.h // // Copyright (c) 2015-17, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #pragma once #include "executor/abstract_executor.h" #include "planner/abstract_scan_plan.h" #include "type/types.h" namespace peloton { namespace executor { /** * Super class for different kinds of scan executor. * It provides common codes for all kinds of scan: * evaluate generic predicates and simple projections. */ class AbstractScanExecutor : public AbstractExecutor { public: AbstractScanExecutor(const AbstractScanExecutor &) = delete; AbstractScanExecutor &operator=(const AbstractScanExecutor &) = delete; AbstractScanExecutor(AbstractScanExecutor &&) = delete; AbstractScanExecutor &operator=(AbstractScanExecutor &&) = delete; explicit AbstractScanExecutor(const planner::AbstractPlan *node, ExecutorContext *executor_context); virtual void UpdatePredicate(const std::vector<oid_t> &column_ids UNUSED_ATTRIBUTE, const std::vector<type::Value> &values UNUSED_ATTRIBUTE) {} virtual void ResetState() {} protected: bool DInit(); virtual bool DExecute() = 0; protected: //===--------------------------------------------------------------------===// // Plan Info //===--------------------------------------------------------------------===// /** @brief Selection predicate. */ const expression::AbstractExpression *predicate_ = nullptr; /** @brief Columns from tile group to be added to logical tile output. */ std::vector<oid_t> column_ids_; }; } // namespace executor } // namespace peloton
{'content_hash': '2960e75f46996173b93b6cc917f7d2b6', 'timestamp': '', 'source': 'github', 'line_count': 62, 'max_line_length': 80, 'avg_line_length': 31.629032258064516, 'alnum_prop': 0.5599184089750128, 'repo_name': 'prashasthip/peloton', 'id': '44269c196dcea5898cbb03956693af6e9aef5d43', 'size': '1961', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/include/executor/abstract_scan_executor.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '44625'}, {'name': 'C++', 'bytes': '5767040'}, {'name': 'CMake', 'bytes': '109338'}, {'name': 'Java', 'bytes': '44640'}, {'name': 'Objective-C', 'bytes': '4030'}, {'name': 'PLpgSQL', 'bytes': '5855'}, {'name': 'Python', 'bytes': '63317'}, {'name': 'Ruby', 'bytes': '1310'}, {'name': 'Shell', 'bytes': '14149'}]}
""" Test for controlnet.py """ import unittest from mininet.util import pexpect from sys import stdout class testControlNet( unittest.TestCase ): prompt = 'mininet>' def testPingall( self ): "Simple pingall test that verifies 0% packet drop in data network" p = pexpect.spawn( 'python -m mininet.examples.controlnet', logfile=stdout) p.expect( self.prompt ) p.sendline( 'pingall' ) p.expect ( '(\d+)% dropped' ) percent = int( p.match.group( 1 ) ) if p.match else -1 self.assertEqual( percent, 0 ) p.expect( self.prompt ) p.sendline( 'exit' ) p.wait() def testFailover( self ): "Kill controllers and verify that switch, s1, fails over properly" count = 1 p = pexpect.spawn( 'python -m mininet.examples.controlnet', logfile=stdout ) p.expect( self.prompt ) lp = pexpect.spawn( 'tail -f /tmp/s1-ofp.log', logfile=stdout ) lp.expect( 'tcp:\d+\.\d+\.\d+\.(\d+):\d+: connected' ) ip = int( lp.match.group( 1 ) ) self.assertEqual( count, ip ) count += 1 for c in [ 'c0', 'c1' ]: p.sendline( '%s ifconfig %s-eth0 down' % ( c, c) ) p.expect( self.prompt ) lp.expect( 'tcp:\d+\.\d+\.\d+\.(\d+):\d+: connected' ) ip = int( lp.match.group( 1 ) ) self.assertEqual( count, ip ) count += 1 p.sendline( 'exit' ) p.wait() if __name__ == '__main__': unittest.main()
{'content_hash': 'dcd1b25ea0159b021904f1dcfe18f9f6', 'timestamp': '', 'source': 'github', 'line_count': 47, 'max_line_length': 84, 'avg_line_length': 32.340425531914896, 'alnum_prop': 0.5473684210526316, 'repo_name': 'mininet/mininet', 'id': '7e7ce9a6ba6f8fc8254b1ac5348350c7707a9ff2', 'size': '1543', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'examples/test/test_controlnet.py', 'mode': '33261', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '49941'}, {'name': 'Makefile', 'bytes': '2620'}, {'name': 'Python', 'bytes': '305497'}, {'name': 'Shell', 'bytes': '42436'}]}
package org.apache.activemq.plugin.util; import java.util.Set; import org.apache.activemq.broker.region.Destination; import org.apache.activemq.broker.region.DestinationFilter; import org.apache.activemq.broker.region.Queue; import org.apache.activemq.broker.region.RegionBroker; import org.apache.activemq.broker.region.Topic; import org.apache.activemq.broker.region.policy.PolicyEntry; import org.apache.activemq.broker.region.policy.PolicyMap; import org.apache.activemq.plugin.AbstractRuntimeConfigurationBroker; public class PolicyEntryUtil { /** * Find a matching PolicyEntry by looking up the Set of entries from the map and * then comparing the destination to find the exact match. This lets us be able to * find the correct policy entry to update even though there might be multiple that * are returned from the get method of the PolicyMap. * * @param runtimeBroker * @param entry * @return */ public static PolicyEntry findEntryByDestination(AbstractRuntimeConfigurationBroker runtimeBroker, PolicyEntry entry) { PolicyMap existingMap = runtimeBroker.getBrokerService().getDestinationPolicy(); @SuppressWarnings("unchecked") Set<PolicyEntry> existingEntries = existingMap.get(entry.getDestination()); //First just look up by the destination type to see if anything matches PolicyEntry existingEntry = null; for (PolicyEntry ee: existingEntries) { if (ee.getDestination().equals(entry.getDestination())) { existingEntry = ee; break; } } return existingEntry; } /** * Utility to properly apply an updated policy entry to all existing destinations that * match this entry. The destination will only be updated if the policy is the exact * policy (most specific) that matches the destination. * * @param runtimeBroker * @param updatedEntry */ public static void applyRetrospectively(AbstractRuntimeConfigurationBroker runtimeBroker, PolicyEntry updatedEntry) { PolicyEntryUtil.applyRetrospectively(runtimeBroker, updatedEntry, null); } /** * * Utility to properly apply an updated policy entry to all existing destinations that * match this entry. The destination will only be updated if the policy is the exact * policy (most specific) that matches the destination. * * The includedProperties List is optional and is used to specify a list of properties * to apply retrospectively to the matching destinations. This allows only certain properties * to be reapplied. If the list is null then all properties will be applied. * * @param runtimeBroker * @param updatedEntry * @param includedProperties */ public static void applyRetrospectively(AbstractRuntimeConfigurationBroker runtimeBroker, PolicyEntry updatedEntry, Set<String> includedProperties) { RegionBroker regionBroker = (RegionBroker) runtimeBroker.getBrokerService().getRegionBroker(); for (Destination destination : regionBroker.getDestinations(updatedEntry.getDestination())) { //Look up the policy that applies to the destination PolicyEntry specificyPolicy = regionBroker.getDestinationPolicy().getEntryFor( destination.getActiveMQDestination()); //only update the destination if it matches the specific policy being updated //currently just an identity check which is what we want if (updatedEntry.equals(specificyPolicy)){ Destination target = destination; while (target instanceof DestinationFilter) { target = ((DestinationFilter)target).getNext(); } //If we are providing a list of properties to set then use them //to set eligible properties that are in the includedProperties list if (target.getActiveMQDestination().isQueue()) { updatedEntry.update((Queue) target, includedProperties); } else if (target.getActiveMQDestination().isTopic()) { updatedEntry.update((Topic) target, includedProperties); } runtimeBroker.debug("applied update to:" + target); } } } }
{'content_hash': 'e5788ae49aded600bd76b08b5bfa8db1', 'timestamp': '', 'source': 'github', 'line_count': 100, 'max_line_length': 102, 'avg_line_length': 44.22, 'alnum_prop': 0.6840796019900498, 'repo_name': 'chirino/activemq', 'id': '64d752810dda8af64641ce340e80c1bc5389316c', 'size': '5225', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'activemq-runtime-config/src/main/java/org/apache/activemq/plugin/util/PolicyEntryUtil.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '17712'}, {'name': 'C#', 'bytes': '27536'}, {'name': 'C++', 'bytes': '17404'}, {'name': 'CSS', 'bytes': '34997'}, {'name': 'HTML', 'bytes': '158883'}, {'name': 'Java', 'bytes': '25304453'}, {'name': 'JavaScript', 'bytes': '438641'}, {'name': 'PHP', 'bytes': '3665'}, {'name': 'Perl', 'bytes': '4128'}, {'name': 'Protocol Buffer', 'bytes': '13867'}, {'name': 'Python', 'bytes': '14547'}, {'name': 'Ruby', 'bytes': '6594'}, {'name': 'Scala', 'bytes': '302023'}, {'name': 'Shell', 'bytes': '87001'}]}
module Syntax where data Type = TyBool | TyNat deriving (Show, Eq) data Term = TmTrue | TmFalse | TmIf Term Term Term | TmZero | TmSucc Term | TmPred Term | TmIsZero Term deriving Show type Error = String
{'content_hash': '9fb7a16903e2a0e71f1533024c613e85', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 29, 'avg_line_length': 13.88888888888889, 'alnum_prop': 0.608, 'repo_name': 'kellino/TypeSystems', 'id': '030956f76a40bfff9cad12cb7446bef6451120a3', 'size': '250', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'typedArith/Syntax.hs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Agda', 'bytes': '27249'}, {'name': 'Haskell', 'bytes': '103038'}]}
<?php namespace App\ApiModule\Presenters; use Nette\Application\UI\Presenter; use Nette\Http; abstract class BasePresenter extends Presenter { public function error($message = NULL, $code = Http\IResponse::S404_NOT_FOUND) { $this->getHttpResponse()->setCode($code); $this->sendJson([ 'success' => false, 'error' => $code, 'message' => $message ]); } }
{'content_hash': '4d242af7c0728bb13a675e53ae740a3e', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 82, 'avg_line_length': 19.5, 'alnum_prop': 0.5920745920745921, 'repo_name': 'vitush93/rocnikac', 'id': '8f9b7b86302ee26da7fec9f36ac31e32c5a0f5de', 'size': '429', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'app/ApiModule/presenters/BasePresenter.php', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ApacheConf', 'bytes': '884'}, {'name': 'CSS', 'bytes': '533582'}, {'name': 'HTML', 'bytes': '149898'}, {'name': 'JavaScript', 'bytes': '1152173'}, {'name': 'PHP', 'bytes': '202353'}, {'name': 'Shell', 'bytes': '165'}]}
<?php if (!defined('CC_CRON')) { echo "NO DICE"; exit; } include_once(dirname(__FILE__).DIRECTORY_SEPARATOR."config.php"); if ((!empty($_REQUEST['cron']['type']) && $_REQUEST['cron']['type'] == "all") || !empty($_REQUEST['cron']['modules'])) { chatrooms(); chatroommessages(); chatroomsusers(); } else { if(isset($_REQUEST['cron']['inactiverooms'])){chatrooms();} if(isset($_REQUEST['cron']['chatroommessages'])){chatroommessages();} if(isset($_REQUEST['cron']['inactiveusers'])){chatroomsusers();} } function chatrooms() { global $chatroomTimeout; $sql = ("delete from cometchat_chatrooms where createdby <> 0 and lastactivity < (".getTimeStamp()."- ".$chatroomTimeout." )"); $query = mysqli_query($GLOBALS['dbh'],$sql); if (defined('DEV_MODE') && DEV_MODE == '1') { echo mysqli_error($GLOBALS['dbh']); } } function chatroommessages() { $sql = ("delete from cometchat_chatroommessages where sent < (".getTimeStamp()."-10800)"); $query = mysqli_query($GLOBALS['dbh'],$sql); if (defined('DEV_MODE') && DEV_MODE == '1') { echo mysqli_error($GLOBALS['dbh']); } } function chatroomsusers() { $sql = ("delete from cometchat_chatrooms_users where lastactivity < (".getTimeStamp()."-3600)"); $query = mysqli_query($GLOBALS['dbh'],$sql); if (defined('DEV_MODE') && DEV_MODE == '1') { echo mysqli_error($GLOBALS['dbh']); } }
{'content_hash': '8e0b23f3352032d87953dc785769ea1b', 'timestamp': '', 'source': 'github', 'line_count': 34, 'max_line_length': 128, 'avg_line_length': 39.35294117647059, 'alnum_prop': 0.6434977578475336, 'repo_name': 'networksoft/erp.wellnet', 'id': '3c6df67a6c6cd7a1f410f8f7f952e99499aa8f3b', 'size': '1338', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'cometchat/modules/chatrooms/cron.php', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'ApacheConf', 'bytes': '383'}, {'name': 'Batchfile', 'bytes': '310'}, {'name': 'C', 'bytes': '479526'}, {'name': 'CSS', 'bytes': '916036'}, {'name': 'Groff', 'bytes': '60910'}, {'name': 'HTML', 'bytes': '7195685'}, {'name': 'JavaScript', 'bytes': '1616267'}, {'name': 'Makefile', 'bytes': '16519'}, {'name': 'PHP', 'bytes': '12824429'}, {'name': 'Perl', 'bytes': '50950'}, {'name': 'Shell', 'bytes': '27957'}]}
package io.advantageous.qbit.service.dispatchers; import io.advantageous.qbit.service.ServiceBuilder; import io.advantageous.qbit.service.ServiceQueue; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; public class ShardedServiceWorkerBuilder { /** * Shard rule, if you don't set a shard rule, you get shard of first argument. * Shard rule by default. */ private ShardRule shardRule; private ServiceBuilder serviceBuilder; private ServiceWorkers serviceDispatcher; private int workerCount = -1; private int flushInterval = -1; private TimeUnit timeUnit = TimeUnit.MILLISECONDS; private Supplier<Object> serviceObjectSupplier; public static ShardedServiceWorkerBuilder shardedServiceWorkerBuilder() { return new ShardedServiceWorkerBuilder(); } public Supplier<Object> getServiceObjectSupplier() { return serviceObjectSupplier; } public ShardedServiceWorkerBuilder setServiceObjectSupplier(Supplier<Object> serviceObjectSupplier) { this.serviceObjectSupplier = serviceObjectSupplier; return this; } public int getWorkerCount() { if (workerCount == -1) { workerCount = Runtime.getRuntime().availableProcessors(); } return workerCount; } public ShardedServiceWorkerBuilder setWorkerCount(int workerCount) { this.workerCount = workerCount; return this; } public ShardRule getShardRule() { if (shardRule == null) { final int workerCount = this.getWorkerCount(); shardRule = (methodName, methodArgs, numWorkers) -> methodArgs[0].hashCode() % workerCount; } return shardRule; } public ShardedServiceWorkerBuilder setShardRule(ShardRule shardRule) { this.shardRule = shardRule; return this; } public ServiceBuilder getServiceBuilder() { if (serviceBuilder == null) { serviceBuilder = ServiceBuilder.serviceBuilder(); return serviceBuilder; } return serviceBuilder.copy(); } public ShardedServiceWorkerBuilder setServiceBuilder(ServiceBuilder serviceBuilder) { this.serviceBuilder = serviceBuilder; return this; } public ServiceWorkers getServiceDispatcher() { if (serviceDispatcher == null) { if (this.flushInterval == -1) { serviceDispatcher = ServiceWorkers.shardedWorkers(getShardRule()); } else { serviceDispatcher = ServiceWorkers.shardedWorkers(getFlushInterval(), getTimeUnit(), getShardRule()); } } return serviceDispatcher; } public ShardedServiceWorkerBuilder setServiceDispatcher(ServiceWorkers serviceDispatcher) { this.serviceDispatcher = serviceDispatcher; return this; } public int getFlushInterval() { return flushInterval; } public ShardedServiceWorkerBuilder setFlushInterval(int flushInterval) { this.flushInterval = flushInterval; return this; } public TimeUnit getTimeUnit() { return timeUnit; } public ShardedServiceWorkerBuilder setTimeUnit(TimeUnit timeUnit) { this.timeUnit = timeUnit; return this; } public ServiceMethodDispatcher build() { if (getServiceObjectSupplier() == null) { throw new IllegalStateException("serviceObjectSupplier must be set"); } final ServiceBuilder serviceBuilder = getServiceBuilder(); for (int index = 0; index < getWorkerCount(); index++) { final ServiceQueue serviceQueue = serviceBuilder .setServiceObject(getServiceObjectSupplier().get()).build(); getServiceDispatcher().addServices(serviceQueue); } return getServiceDispatcher(); } }
{'content_hash': 'd4cab8ca09c8232b1e52995429ac3ec7', 'timestamp': '', 'source': 'github', 'line_count': 128, 'max_line_length': 105, 'avg_line_length': 30.53125, 'alnum_prop': 0.6665813715455476, 'repo_name': 'advantageous/qbit', 'id': '39f38897bffec165bc1dd1b51ed008adfbaecca0', 'size': '3908', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'qbit/core/src/main/java/io/advantageous/qbit/service/dispatchers/ShardedServiceWorkerBuilder.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '1064'}, {'name': 'Java', 'bytes': '2713914'}, {'name': 'JavaScript', 'bytes': '1141'}, {'name': 'Lua', 'bytes': '110'}, {'name': 'Shell', 'bytes': '181'}]}
<?php namespace Opulence\Routing\Routes\Compilers; use Opulence\Http\Requests\Request; use Opulence\Routing\Routes\CompiledRoute; use Opulence\Routing\Routes\Compilers\Matchers\HostMatcher; use Opulence\Routing\Routes\Compilers\Matchers\IRouteMatcher; use Opulence\Routing\Routes\Compilers\Matchers\PathMatcher; use Opulence\Routing\Routes\ParsedRoute; /** * Defines a route compiler */ class Compiler implements ICompiler { /** @var IRouteMatcher[] The list of route matchers used by the compiler */ private $routeMatchers = []; /** * @param IRouteMatcher[] $routeMatchers The list of route matchers to use */ public function __construct(array $routeMatchers) { $this->routeMatchers = $routeMatchers; } /** * @inheritdoc */ public function compile(ParsedRoute $route, Request $request) : CompiledRoute { $hostMatches = []; $pathMatches = []; foreach ($this->routeMatchers as $routeMatcher) { if ($routeMatcher instanceof HostMatcher && !$routeMatcher->isMatch($route, $request, $hostMatches)) { return new CompiledRoute($route, false); } elseif ($routeMatcher instanceof PathMatcher && !$routeMatcher->isMatch($route, $request, $pathMatches)) { return new CompiledRoute($route, false); } elseif (!$routeMatcher->isMatch($route, $request)) { return new CompiledRoute($route, false); } } // If we've gotten here, then all the matchers matched $pathVars = array_merge($hostMatches, $pathMatches); return new CompiledRoute($route, true, $pathVars); } }
{'content_hash': '432d9d45e55b086ec1390ece1a209d21', 'timestamp': '', 'source': 'github', 'line_count': 53, 'max_line_length': 120, 'avg_line_length': 31.735849056603772, 'alnum_prop': 0.6563614744351962, 'repo_name': 'opulencephp/Opulence', 'id': '83a3bfc80eb3d3b7b2c2823a137d52215e81641e', 'size': '1864', 'binary': False, 'copies': '1', 'ref': 'refs/heads/1.2', 'path': 'src/Opulence/Routing/Routes/Compilers/Compiler.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '2098'}, {'name': 'Hack', 'bytes': '979'}, {'name': 'PHP', 'bytes': '2407691'}, {'name': 'Shell', 'bytes': '1733'}]}
/** * Generate HTTP headers from auth credentials * @param {AuthCredentials} props * @return {Promise} - promise that resolves with the headers */ export function getAuthenticationHeaders(props) { if (!props) { throw new Error('Must provide authentication information.'); } // JWT always have priority over a simple app token if (props.jwt) { return { 'Authorization': 'Bearer ' + props.jwt }; } else if (props.appToken) { return { 'app-token': props.appToken }; } throw new Error('Must provide a JWT or a app token'); }
{'content_hash': '83384ec27e3f4ced2c1873f6906535fe', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 68, 'avg_line_length': 27.17391304347826, 'alnum_prop': 0.6016, 'repo_name': 'bobhami/payrollbot', 'id': '4c4eef679c0c2d72a65a89d8df74bb2fc21691d6', 'size': '625', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'node_modules/smooch-bot/node_modules/smooch-core/src/utils/auth.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '213'}, {'name': 'JavaScript', 'bytes': '7625'}]}
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.apache</groupId> <artifactId>rocketmq-hbase</artifactId> <packaging>pom</packaging> <version>1.0-SNAPSHOT</version> <modules> <module>rocketmq-hbase-sink</module> <module>rocketmq-hbase-source</module> </modules> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <maven.test.skip>false</maven.test.skip> <maven.javadoc.skip>true</maven.javadoc.skip> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <rocketmq.version>4.2.0</rocketmq.version> <hbase.version>1.4.4</hbase.version> </properties> <dependencies> <dependency> <groupId>org.apache.rocketmq</groupId> <artifactId>rocketmq-client</artifactId> <version>${rocketmq.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.5</version> </dependency> <dependency> <groupId>org.apache.hbase</groupId> <artifactId>hbase-server</artifactId> <version>${hbase.version}</version> </dependency> <!-- test --> <dependency> <groupId>org.apache.hbase</groupId> <artifactId>hbase-testing-util</artifactId> <version>${hbase.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.rocketmq</groupId> <artifactId>rocketmq-namesrv</artifactId> <version>${rocketmq.version}</version> <scope>test</scope> <exclusions> <exclusion> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.rocketmq</groupId> <artifactId>rocketmq-broker</artifactId> <version>${rocketmq.version}</version> <scope>test</scope> <exclusions> <exclusion> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> </exclusion> <exclusion> <groupId>io.netty</groupId> <artifactId>netty-tcnative</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>3.1.1</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> </configuration> </execution> </executions> </plugin> <plugin> <artifactId>maven-checkstyle-plugin</artifactId> <version>2.17</version> <executions> <execution> <id>verify</id> <phase>verify</phase> <configuration> <configLocation>style/rmq_checkstyle.xml</configLocation> <encoding>UTF-8</encoding> <consoleOutput>true</consoleOutput> <failsOnError>true</failsOnError> <includeTestSourceDirectory>false</includeTestSourceDirectory> <includeTestResources>false</includeTestResources> </configuration> <goals> <goal>check</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
{'content_hash': '2db8e8db004b0f67e2ed7c5523164a2a', 'timestamp': '', 'source': 'github', 'line_count': 123, 'max_line_length': 108, 'avg_line_length': 37.6260162601626, 'alnum_prop': 0.5084269662921348, 'repo_name': 'StyleTang/incubator-rocketmq-externals', 'id': 'b2ba196528df2805f6e6a3071aaffdff782fbbad', 'size': '4628', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'rocketmq-hbase/pom.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '768'}, {'name': 'C', 'bytes': '1804'}, {'name': 'C++', 'bytes': '1075014'}, {'name': 'CSS', 'bytes': '60479'}, {'name': 'Go', 'bytes': '276304'}, {'name': 'HTML', 'bytes': '86942'}, {'name': 'Java', 'bytes': '554421'}, {'name': 'JavaScript', 'bytes': '76515'}, {'name': 'Makefile', 'bytes': '2349'}, {'name': 'PHP', 'bytes': '29834'}, {'name': 'Python', 'bytes': '17496'}, {'name': 'Scala', 'bytes': '60754'}, {'name': 'Shell', 'bytes': '2982'}]}
class CertDbInitializer; // Factory that manages creation of CertDbInitializer. The initialization is // handled differently depending on the environment: // * On real ChromeOS devices with TPMs: // ** if the user is affiliated: CertDbInitializer is automatically // created right after its profile is created. It receives a path to software // cert database and slot IDs for Chaps from Ash and uses them. // ** if the user is not affiliated: TODO(b/197082753): not officially supported // yet, handled as if there's no TPM. // * In emulated environments (e.g. when running ChromeOS on Linux) and in the // future on ChromeOS without TPMs: Same as real ChromeOS, but Ash only sends // the software database path. // * In browsertests: CertDbInitializer is not created by default because it // requires crosapi mojo interface. It is configured through the // `SetCreateWithBrowserContextForTesting()` method. This can be overridden by // individual tests or they can create their own instances of the service. // * In unittests: CertDbInitializer is not created by default (see // `ServiceIsNULLWhileTesting()`). class CertDbInitializerFactory : public BrowserContextKeyedServiceFactory { public: static CertDbInitializerFactory* GetInstance(); static CertDbInitializer* GetForBrowserContext( content::BrowserContext* context); // Configures whether CertDbInitializer should be automatically created on // profile creation in browser tests. // Currently it is configured that in browser tests the service is not created // by default. Individual tests can override it when needed. void SetCreateWithBrowserContextForTesting(bool should_create); private: friend class base::NoDestructor<CertDbInitializerFactory>; CertDbInitializerFactory(); ~CertDbInitializerFactory() override = default; // BrowserStateKeyedServiceFactory bool ServiceIsCreatedWithBrowserContext() const override; KeyedService* BuildServiceInstanceFor( content::BrowserContext* context) const override; bool ServiceIsNULLWhileTesting() const override; content::BrowserContext* GetBrowserContextToUse( content::BrowserContext* context) const override; bool should_create_with_browser_context_ = true; }; #endif // CHROME_BROWSER_LACROS_CERT_DB_INITIALIZER_FACTORY_H_
{'content_hash': '61ceabbd404882a9f131dabf6d3a6508', 'timestamp': '', 'source': 'github', 'line_count': 49, 'max_line_length': 80, 'avg_line_length': 46.795918367346935, 'alnum_prop': 0.7836894897514174, 'repo_name': 'ric2b/Vivaldi-browser', 'id': 'f0bc2dfa2893f0641a44664dca58ae0733ea7e0e', 'size': '2699', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'chromium/chrome/browser/lacros/cert_db_initializer_factory.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
module Azure::ARM::ServiceBus module Models # # Parameters supplied to the Create Or Update Subscription operation. # class SubscriptionCreateOrUpdateParameters include MsRestAzure # @return [String] Subscription data center location. attr_accessor :location # @return [String] Resource manager type of the resource. attr_accessor :type # @return [DateTime] Last time there was a receive request to this # subscription. attr_accessor :accessed_at # @return [String] TimeSpan idle interval after which the topic is # automatically deleted. The minimum duration is 5 minutes. attr_accessor :auto_delete_on_idle # @return [MessageCountDetails] attr_accessor :count_details # @return [DateTime] Exact time the message was created. attr_accessor :created_at # @return [String] Default message time to live value. This is the # duration after which the message expires, starting from when the # message is sent to Service Bus. This is the default value used when # TimeToLive is not set on a message itself. attr_accessor :default_message_time_to_live # @return [Boolean] Value that indicates whether a subscription has dead # letter support on filter evaluation exceptions. attr_accessor :dead_lettering_on_filter_evaluation_exceptions # @return [Boolean] Value that indicates whether a subscription has dead # letter support when a message expires. attr_accessor :dead_lettering_on_message_expiration # @return [Boolean] Value that indicates whether server-side batched # operations are enabled. attr_accessor :enable_batched_operations # @return [EntityAvailabilityStatus] Entity availability status for the # topic. Possible values include: 'Available', 'Limited', 'Renaming', # 'Restoring', 'Unknown' attr_accessor :entity_availability_status # @return [Boolean] Value that indicates whether the entity description # is read-only. attr_accessor :is_read_only # @return [String] The lock duration time span for the subscription. attr_accessor :lock_duration # @return [Integer] Number of maximum deliveries. attr_accessor :max_delivery_count # @return [Integer] Number of messages. attr_accessor :message_count # @return [Boolean] Value indicating if a subscription supports the # concept of sessions. attr_accessor :requires_session # @return [EntityStatus] Enumerates the possible values for the status of # a messaging entity. Possible values include: 'Active', 'Creating', # 'Deleting', 'Disabled', 'ReceiveDisabled', 'Renaming', 'Restoring', # 'SendDisabled', 'Unknown' attr_accessor :status # @return [DateTime] The exact time the message was updated. attr_accessor :updated_at # # Mapper for SubscriptionCreateOrUpdateParameters class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { required: false, serialized_name: 'SubscriptionCreateOrUpdateParameters', type: { name: 'Composite', class_name: 'SubscriptionCreateOrUpdateParameters', model_properties: { location: { required: true, serialized_name: 'location', type: { name: 'String' } }, type: { required: false, serialized_name: 'type', type: { name: 'String' } }, accessed_at: { required: false, serialized_name: 'properties.accessedAt', type: { name: 'DateTime' } }, auto_delete_on_idle: { required: false, serialized_name: 'properties.autoDeleteOnIdle', type: { name: 'String' } }, count_details: { required: false, serialized_name: 'properties.countDetails', type: { name: 'Composite', class_name: 'MessageCountDetails' } }, created_at: { required: false, serialized_name: 'properties.createdAt', type: { name: 'DateTime' } }, default_message_time_to_live: { required: false, serialized_name: 'properties.defaultMessageTimeToLive', type: { name: 'String' } }, dead_lettering_on_filter_evaluation_exceptions: { required: false, serialized_name: 'properties.deadLetteringOnFilterEvaluationExceptions', type: { name: 'Boolean' } }, dead_lettering_on_message_expiration: { required: false, serialized_name: 'properties.deadLetteringOnMessageExpiration', type: { name: 'Boolean' } }, enable_batched_operations: { required: false, serialized_name: 'properties.enableBatchedOperations', type: { name: 'Boolean' } }, entity_availability_status: { required: false, serialized_name: 'properties.entityAvailabilityStatus', type: { name: 'Enum', module: 'EntityAvailabilityStatus' } }, is_read_only: { required: false, serialized_name: 'properties.isReadOnly', type: { name: 'Boolean' } }, lock_duration: { required: false, serialized_name: 'properties.lockDuration', type: { name: 'String' } }, max_delivery_count: { required: false, serialized_name: 'properties.maxDeliveryCount', type: { name: 'Number' } }, message_count: { required: false, serialized_name: 'properties.messageCount', type: { name: 'Number' } }, requires_session: { required: false, serialized_name: 'properties.requiresSession', type: { name: 'Boolean' } }, status: { required: false, serialized_name: 'properties.status', type: { name: 'Enum', module: 'EntityStatus' } }, updated_at: { required: false, serialized_name: 'properties.updatedAt', type: { name: 'DateTime' } } } } } end end end end
{'content_hash': '463cf306d2ba57e2d7af248322101698', 'timestamp': '', 'source': 'github', 'line_count': 227, 'max_line_length': 88, 'avg_line_length': 33.44933920704846, 'alnum_prop': 0.5073093638877914, 'repo_name': 'devigned/azure-sdk-for-ruby', 'id': 'bbdaacd695508b209e59bb962749182086822315', 'size': '7764', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'management/azure_mgmt_service_bus/lib/generated/azure_mgmt_service_bus/models/subscription_create_or_update_parameters.rb', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Ruby', 'bytes': '11168894'}, {'name': 'Shell', 'bytes': '157'}]}
'use strict'; /* jshint maxlen: false */ /** * @ngdoc overview * @name ngAnimate * @description * * # ngAnimate * * The `ngAnimate` module provides support for JavaScript, CSS3 transition and CSS3 keyframe animation hooks within existing core and custom directives. * * {@installModule animate} * * <div doc-module-components="ngAnimate"></div> * * # Usage * * To see animations in action, all that is required is to define the appropriate CSS classes * or to register a JavaScript animation via the myModule.animation() function. The directives that support animation automatically are: * `ngRepeat`, `ngInclude`, `ngIf`, `ngSwitch`, `ngShow`, `ngHide`, `ngView` and `ngClass`. Custom directives can take advantage of animation * by using the `$animate` service. * * Below is a more detailed breakdown of the supported animation events provided by pre-existing ng directives: * * | Directive | Supported Animations | * |---------------------------------------------------------- |----------------------------------------------------| * | {@link ng.directive:ngRepeat#usage_animations ngRepeat} | enter, leave and move | * | {@link ngRoute.directive:ngView#usage_animations ngView} | enter and leave | * | {@link ng.directive:ngInclude#usage_animations ngInclude} | enter and leave | * | {@link ng.directive:ngSwitch#usage_animations ngSwitch} | enter and leave | * | {@link ng.directive:ngIf#usage_animations ngIf} | enter and leave | * | {@link ng.directive:ngClass#usage_animations ngClass} | add and remove | * | {@link ng.directive:ngShow#usage_animations ngShow & ngHide} | add and remove (the ng-hide class value) | * * You can find out more information about animations upon visiting each directive page. * * Below is an example of how to apply animations to a directive that supports animation hooks: * * <pre> * <style type="text/css"> * .slide.ng-enter, .slide.ng-leave { * -webkit-transition:0.5s linear all; * transition:0.5s linear all; * } * * .slide.ng-enter { } /&#42; starting animations for enter &#42;/ * .slide.ng-enter-active { } /&#42; terminal animations for enter &#42;/ * .slide.ng-leave { } /&#42; starting animations for leave &#42;/ * .slide.ng-leave-active { } /&#42; terminal animations for leave &#42;/ * </style> * * <!-- * the animate service will automatically add .ng-enter and .ng-leave to the element * to trigger the CSS transition/animations * --> * <ANY class="slide" ng-include="..."></ANY> * </pre> * * Keep in mind that if an animation is running, any child elements cannot be animated until the parent element's * animation has completed. * * <h2>CSS-defined Animations</h2> * The animate service will automatically apply two CSS classes to the animated element and these two CSS classes * are designed to contain the start and end CSS styling. Both CSS transitions and keyframe animations are supported * and can be used to play along with this naming structure. * * The following code below demonstrates how to perform animations using **CSS transitions** with Angular: * * <pre> * <style type="text/css"> * /&#42; * The animate class is apart of the element and the ng-enter class * is attached to the element once the enter animation event is triggered * &#42;/ * .reveal-animation.ng-enter { * -webkit-transition: 1s linear all; /&#42; Safari/Chrome &#42;/ * transition: 1s linear all; /&#42; All other modern browsers and IE10+ &#42;/ * * /&#42; The animation preparation code &#42;/ * opacity: 0; * } * * /&#42; * Keep in mind that you want to combine both CSS * classes together to avoid any CSS-specificity * conflicts * &#42;/ * .reveal-animation.ng-enter.ng-enter-active { * /&#42; The animation code itself &#42;/ * opacity: 1; * } * </style> * * <div class="view-container"> * <div ng-view class="reveal-animation"></div> * </div> * </pre> * * The following code below demonstrates how to perform animations using **CSS animations** with Angular: * * <pre> * <style type="text/css"> * .reveal-animation.ng-enter { * -webkit-animation: enter_sequence 1s linear; /&#42; Safari/Chrome &#42;/ * animation: enter_sequence 1s linear; /&#42; IE10+ and Future Browsers &#42;/ * } * &#64-webkit-keyframes enter_sequence { * from { opacity:0; } * to { opacity:1; } * } * &#64keyframes enter_sequence { * from { opacity:0; } * to { opacity:1; } * } * </style> * * <div class="view-container"> * <div ng-view class="reveal-animation"></div> * </div> * </pre> * * Both CSS3 animations and transitions can be used together and the animate service will figure out the correct duration and delay timing. * * Upon DOM mutation, the event class is added first (something like `ng-enter`), then the browser prepares itself to add * the active class (in this case `ng-enter-active`) which then triggers the animation. The animation module will automatically * detect the CSS code to determine when the animation ends. Once the animation is over then both CSS classes will be * removed from the DOM. If a browser does not support CSS transitions or CSS animations then the animation will start and end * immediately resulting in a DOM element that is at its final state. This final state is when the DOM element * has no CSS transition/animation classes applied to it. * * <h3>CSS Staggering Animations</h3> * A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a * curtain-like effect. The ngAnimate module, as of 1.2.0, supports staggering animations and the stagger effect can be * performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for * the animation. The style property expected within the stagger class can either be a **transition-delay** or an * **animation-delay** property (or both if your animation contains both transitions and keyframe animations). * * <pre> * .my-animation.ng-enter { * /&#42; standard transition code &#42;/ * -webkit-transition: 1s linear all; * transition: 1s linear all; * opacity:0; * } * .my-animation.ng-enter-stagger { * /&#42; this will have a 100ms delay between each successive leave animation &#42;/ * -webkit-transition-delay: 0.1s; * transition-delay: 0.1s; * * /&#42; in case the stagger doesn't work then these two values * must be set to 0 to avoid an accidental CSS inheritance &#42;/ * -webkit-transition-duration: 0s; * transition-duration: 0s; * } * .my-animation.ng-enter.ng-enter-active { * /&#42; standard transition styles &#42;/ * opacity:1; * } * </pre> * * Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations * on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this * are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation * will also be reset if more than 10ms has passed after the last animation has been fired. * * The following code will issue the **ng-leave-stagger** event on the element provided: * * <pre> * var kids = parent.children(); * * $animate.leave(kids[0]); //stagger index=0 * $animate.leave(kids[1]); //stagger index=1 * $animate.leave(kids[2]); //stagger index=2 * $animate.leave(kids[3]); //stagger index=3 * $animate.leave(kids[4]); //stagger index=4 * * $timeout(function() { * //stagger has reset itself * $animate.leave(kids[5]); //stagger index=0 * $animate.leave(kids[6]); //stagger index=1 * }, 100, false); * </pre> * * Stagger animations are currently only supported within CSS-defined animations. * * <h2>JavaScript-defined Animations</h2> * In the event that you do not want to use CSS3 transitions or CSS3 animations or if you wish to offer animations on browsers that do not * yet support CSS transitions/animations, then you can make use of JavaScript animations defined inside of your AngularJS module. * * <pre> * //!annotate="YourApp" Your AngularJS Module|Replace this or ngModule with the module that you used to define your application. * var ngModule = angular.module('YourApp', []); * ngModule.animation('.my-crazy-animation', function() { * return { * enter: function(element, done) { * //run the animation here and call done when the animation is complete * return function(cancelled) { * //this (optional) function will be called when the animation * //completes or when the animation is cancelled (the cancelled * //flag will be set to true if cancelled). * } * } * leave: function(element, done) { }, * move: function(element, done) { }, * * //animation that can be triggered before the class is added * beforeAddClass: function(element, className, done) { }, * * //animation that can be triggered after the class is added * addClass: function(element, className, done) { }, * * //animation that can be triggered before the class is removed * beforeRemoveClass: function(element, className, done) { }, * * //animation that can be triggered after the class is removed * removeClass: function(element, className, done) { } * } * }); * </pre> * * JavaScript-defined animations are created with a CSS-like class selector and a collection of events which are set to run * a javascript callback function. When an animation is triggered, $animate will look for a matching animation which fits * the element's CSS class attribute value and then run the matching animation event function (if found). * In other words, if the CSS classes present on the animated element match any of the JavaScript animations then the callback function will * be executed. It should be also noted that only simple, single class selectors are allowed (compound class selectors are not supported). * * Within a JavaScript animation, an object containing various event callback animation functions is expected to be returned. * As explained above, these callbacks are triggered based on the animation event. Therefore if an enter animation is run, * and the JavaScript animation is found, then the enter callback will handle that animation (in addition to the CSS keyframe animation * or transition code that is defined via a stylesheet). * */ angular.module('ngAnimate', ['ng']) /** * @ngdoc object * @name ngAnimate.$animateProvider * @description * * The `$animateProvider` allows developers to register JavaScript animation event handlers directly inside of a module. * When an animation is triggered, the $animate service will query the $animate service to find any animations that match * the provided name value. * * Requires the {@link ngAnimate `ngAnimate`} module to be installed. * * Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application. * */ .config(['$provide', '$animateProvider', function($provide, $animateProvider) { var noop = angular.noop; var forEach = angular.forEach; var selectors = $animateProvider.$$selectors; var ELEMENT_NODE = 1; var NG_ANIMATE_STATE = '$$ngAnimateState'; var NG_ANIMATE_CLASS_NAME = 'ng-animate'; var rootAnimateState = {running: true}; $provide.decorator('$animate', ['$delegate', '$injector', '$sniffer', '$rootElement', '$timeout', '$rootScope', '$document', function($delegate, $injector, $sniffer, $rootElement, $timeout, $rootScope, $document) { $rootElement.data(NG_ANIMATE_STATE, rootAnimateState); // disable animations during bootstrap, but once we bootstrapped, enable animations $rootScope.$$postDigest(function() { rootAnimateState.running = false; }); function lookup(name) { if (name) { var matches = [], flagMap = {}, classes = name.substr(1).split('.'); //the empty string value is the default animation //operation which performs CSS transition and keyframe //animations sniffing. This is always included for each //element animation procedure if the browser supports //transitions and/or keyframe animations if ($sniffer.transitions || $sniffer.animations) { classes.push(''); } for(var i=0; i < classes.length; i++) { var klass = classes[i], selectorFactoryName = selectors[klass]; if(selectorFactoryName && !flagMap[klass]) { matches.push($injector.get(selectorFactoryName)); flagMap[klass] = true; } } return matches; } } /** * @ngdoc object * @name ngAnimate.$animate * @function * * @description * The `$animate` service provides animation detection support while performing DOM operations (enter, leave and move) as well as during addClass and removeClass operations. * When any of these operations are run, the $animate service * will examine any JavaScript-defined animations (which are defined by using the $animateProvider provider object) * as well as any CSS-defined animations against the CSS classes present on the element once the DOM operation is run. * * The `$animate` service is used behind the scenes with pre-existing directives and animation with these directives * will work out of the box without any extra configuration. * * Requires the {@link ngAnimate `ngAnimate`} module to be installed. * * Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application. * */ return { /** * @ngdoc function * @name ngAnimate.$animate#enter * @methodOf ngAnimate.$animate * @function * * @description * Appends the element to the parentElement element that resides in the document and then runs the enter animation. Once * the animation is started, the following CSS classes will be present on the element for the duration of the animation: * * Below is a breakdown of each step that occurs during enter animation: * * | Animation Step | What the element class attribute looks like | * |----------------------------------------------------------------------------------------------|---------------------------------------------| * | 1. $animate.enter(...) is called | class="my-animation" | * | 2. element is inserted into the parentElement element or beside the afterElement element | class="my-animation" | * | 3. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" | * | 4. the .ng-enter class is added to the element | class="my-animation ng-animate ng-enter" | * | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-enter" | * | 6. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate ng-enter" | * | 7. the .ng-enter-active and .ng-animate-active classes are added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active ng-enter ng-enter-active" | * | 8. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active ng-enter ng-enter-active" | * | 9. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | * | 10. The doneCallback() callback is fired (if provided) | class="my-animation" | * * @param {jQuery/jqLite element} element the element that will be the focus of the enter animation * @param {jQuery/jqLite element} parentElement the parent element of the element that will be the focus of the enter animation * @param {jQuery/jqLite element} afterElement the sibling element (which is the previous element) of the element that will be the focus of the enter animation * @param {function()=} doneCallback the callback function that will be called once the animation is complete */ enter : function(element, parentElement, afterElement, doneCallback) { this.enabled(false, element); $delegate.enter(element, parentElement, afterElement); $rootScope.$$postDigest(function() { performAnimation('enter', 'ng-enter', element, parentElement, afterElement, noop, doneCallback); }); }, /** * @ngdoc function * @name ngAnimate.$animate#leave * @methodOf ngAnimate.$animate * @function * * @description * Runs the leave animation operation and, upon completion, removes the element from the DOM. Once * the animation is started, the following CSS classes will be added for the duration of the animation: * * Below is a breakdown of each step that occurs during enter animation: * * | Animation Step | What the element class attribute looks like | * |----------------------------------------------------------------------------------------------|---------------------------------------------| * | 1. $animate.leave(...) is called | class="my-animation" | * | 2. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" | * | 3. the .ng-leave class is added to the element | class="my-animation ng-animate ng-leave" | * | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-leave" | * | 5. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate ng-leave" | * | 6. the .ng-leave-active and .ng-animate-active classes is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active ng-leave ng-leave-active" | * | 7. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active ng-leave ng-leave-active" | * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | * | 9. The element is removed from the DOM | ... | * | 10. The doneCallback() callback is fired (if provided) | ... | * * @param {jQuery/jqLite element} element the element that will be the focus of the leave animation * @param {function()=} doneCallback the callback function that will be called once the animation is complete */ leave : function(element, doneCallback) { cancelChildAnimations(element); this.enabled(false, element); $rootScope.$$postDigest(function() { performAnimation('leave', 'ng-leave', element, null, null, function() { $delegate.leave(element); }, doneCallback); }); }, /** * @ngdoc function * @name ngAnimate.$animate#move * @methodOf ngAnimate.$animate * @function * * @description * Fires the move DOM operation. Just before the animation starts, the animate service will either append it into the parentElement container or * add the element directly after the afterElement element if present. Then the move animation will be run. Once * the animation is started, the following CSS classes will be added for the duration of the animation: * * Below is a breakdown of each step that occurs during move animation: * * | Animation Step | What the element class attribute looks like | * |----------------------------------------------------------------------------------------------|---------------------------------------------| * | 1. $animate.move(...) is called | class="my-animation" | * | 2. element is moved into the parentElement element or beside the afterElement element | class="my-animation" | * | 3. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" | * | 4. the .ng-move class is added to the element | class="my-animation ng-animate ng-move" | * | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-move" | * | 6. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate ng-move" | * | 7. the .ng-move-active and .ng-animate-active classes is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active ng-move ng-move-active" | * | 8. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active ng-move ng-move-active" | * | 9. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | * | 10. The doneCallback() callback is fired (if provided) | class="my-animation" | * * @param {jQuery/jqLite element} element the element that will be the focus of the move animation * @param {jQuery/jqLite element} parentElement the parentElement element of the element that will be the focus of the move animation * @param {jQuery/jqLite element} afterElement the sibling element (which is the previous element) of the element that will be the focus of the move animation * @param {function()=} doneCallback the callback function that will be called once the animation is complete */ move : function(element, parentElement, afterElement, doneCallback) { cancelChildAnimations(element); this.enabled(false, element); $delegate.move(element, parentElement, afterElement); $rootScope.$$postDigest(function() { performAnimation('move', 'ng-move', element, parentElement, afterElement, noop, doneCallback); }); }, /** * @ngdoc function * @name ngAnimate.$animate#addClass * @methodOf ngAnimate.$animate * * @description * Triggers a custom animation event based off the className variable and then attaches the className value to the element as a CSS class. * Unlike the other animation methods, the animate service will suffix the className value with {@type -add} in order to provide * the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if no CSS transitions * or keyframes are defined on the -add or base CSS class). * * Below is a breakdown of each step that occurs during addClass animation: * * | Animation Step | What the element class attribute looks like | * |------------------------------------------------------------------------------------------------|---------------------------------------------| * | 1. $animate.addClass(element, 'super') is called | class="my-animation" | * | 2. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" | * | 3. the .super-add class are added to the element | class="my-animation ng-animate super-add" | * | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate super-add" | * | 5. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate super-add" | * | 6. the .super, .super-add-active and .ng-animate-active classes are added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active super super-add super-add-active" | * | 7. $animate waits for X milliseconds for the animation to complete | class="my-animation super-add super-add-active" | * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation super" | * | 9. The super class is kept on the element | class="my-animation super" | * | 10. The doneCallback() callback is fired (if provided) | class="my-animation super" | * * @param {jQuery/jqLite element} element the element that will be animated * @param {string} className the CSS class that will be added to the element and then animated * @param {function()=} doneCallback the callback function that will be called once the animation is complete */ addClass : function(element, className, doneCallback) { performAnimation('addClass', className, element, null, null, function() { $delegate.addClass(element, className); }, doneCallback); }, /** * @ngdoc function * @name ngAnimate.$animate#removeClass * @methodOf ngAnimate.$animate * * @description * Triggers a custom animation event based off the className variable and then removes the CSS class provided by the className value * from the element. Unlike the other animation methods, the animate service will suffix the className value with {@type -remove} in * order to provide the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if * no CSS transitions or keyframes are defined on the -remove or base CSS classes). * * Below is a breakdown of each step that occurs during removeClass animation: * * | Animation Step | What the element class attribute looks like | * |-----------------------------------------------------------------------------------------------|---------------------------------------------| * | 1. $animate.removeClass(element, 'super') is called | class="my-animation super" | * | 2. $animate runs any JavaScript-defined animations on the element | class="my-animation super ng-animate" | * | 3. the .super-remove class are added to the element | class="my-animation super ng-animate super-remove"| * | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation super ng-animate super-remove" | * | 5. $animate waits for 10ms (this performs a reflow) | class="my-animation super ng-animate super-remove" | * | 6. the .super-remove-active and .ng-animate-active classes are added and .super is removed (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active super-remove super-remove-active" | * | 7. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active super-remove super-remove-active" | * | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation" | * | 9. The doneCallback() callback is fired (if provided) | class="my-animation" | * * * @param {jQuery/jqLite element} element the element that will be animated * @param {string} className the CSS class that will be animated and then removed from the element * @param {function()=} doneCallback the callback function that will be called once the animation is complete */ removeClass : function(element, className, doneCallback) { performAnimation('removeClass', className, element, null, null, function() { $delegate.removeClass(element, className); }, doneCallback); }, /** * @ngdoc function * @name ngAnimate.$animate#enabled * @methodOf ngAnimate.$animate * @function * * @param {boolean=} value If provided then set the animation on or off. * @param {jQuery/jqLite element=} element If provided then the element will be used to represent the enable/disable operation * @return {boolean} Current animation state. * * @description * Globally enables/disables animations. * */ enabled : function(value, element) { switch(arguments.length) { case 2: if(value) { cleanup(element); } else { var data = element.data(NG_ANIMATE_STATE) || {}; data.disabled = true; element.data(NG_ANIMATE_STATE, data); } break; case 1: rootAnimateState.disabled = !value; break; default: value = !rootAnimateState.disabled; break; } return !!value; } }; /* all animations call this shared animation triggering function internally. The animationEvent variable refers to the JavaScript animation event that will be triggered and the className value is the name of the animation that will be applied within the CSS code. Element, parentElement and afterElement are provided DOM elements for the animation and the onComplete callback will be fired once the animation is fully complete. */ function performAnimation(animationEvent, className, element, parentElement, afterElement, domOperation, doneCallback) { var currentClassName = element.attr('class') || ''; var classes = currentClassName + ' ' + className; var animationLookup = (' ' + classes).replace(/\s+/g,'.'); if (!parentElement) { parentElement = afterElement ? afterElement.parent() : element.parent(); } var matches = lookup(animationLookup); var isClassBased = animationEvent == 'addClass' || animationEvent == 'removeClass'; var ngAnimateState = element.data(NG_ANIMATE_STATE) || {}; //skip the animation if animations are disabled, a parent is already being animated, //the element is not currently attached to the document body or then completely close //the animation if any matching animations are not found at all. //NOTE: IE8 + IE9 should close properly (run closeAnimation()) in case a NO animation is not found. if (animationsDisabled(element, parentElement) || matches.length === 0) { fireDOMOperation(); closeAnimation(); return; } var animations = []; //only add animations if the currently running animation is not structural //or if there is no animation running at all if(!ngAnimateState.running || !(isClassBased && ngAnimateState.structural)) { forEach(matches, function(animation) { //add the animation to the queue to if it is allowed to be cancelled if(!animation.allowCancel || animation.allowCancel(element, animationEvent, className)) { var beforeFn, afterFn = animation[animationEvent]; //Special case for a leave animation since there is no point in performing an //animation on a element node that has already been removed from the DOM if(animationEvent == 'leave') { beforeFn = afterFn; afterFn = null; //this must be falsy so that the animation is skipped for leave } else { beforeFn = animation['before' + animationEvent.charAt(0).toUpperCase() + animationEvent.substr(1)]; } animations.push({ before : beforeFn, after : afterFn }); } }); } //this would mean that an animation was not allowed so let the existing //animation do it's thing and close this one early if(animations.length === 0) { fireDOMOperation(); fireDoneCallbackAsync(); return; } //this value will be searched for class-based CSS className lookup. Therefore, //we prefix and suffix the current className value with spaces to avoid substring //lookups of className tokens var futureClassName = ' ' + currentClassName + ' '; if(ngAnimateState.running) { //if an animation is currently running on the element then lets take the steps //to cancel that animation and fire any required callbacks $timeout.cancel(ngAnimateState.closeAnimationTimeout); cleanup(element); cancelAnimations(ngAnimateState.animations); //if the class is removed during the reflow then it will revert the styles temporarily //back to the base class CSS styling causing a jump-like effect to occur. This check //here ensures that the domOperation is only performed after the reflow has commenced if(ngAnimateState.beforeComplete) { (ngAnimateState.done || noop)(true); } else if(isClassBased && !ngAnimateState.structural) { //class-based animations will compare element className values after cancelling the //previous animation to see if the element properties already contain the final CSS //class and if so then the animation will be skipped. Since the domOperation will //be performed only after the reflow is complete then our element's className value //will be invalid. Therefore the same string manipulation that would occur within the //DOM operation will be performed below so that the class comparison is valid... futureClassName = ngAnimateState.event == 'removeClass' ? futureClassName.replace(ngAnimateState.className, '') : futureClassName + ngAnimateState.className + ' '; } } //There is no point in perform a class-based animation if the element already contains //(on addClass) or doesn't contain (on removeClass) the className being animated. //The reason why this is being called after the previous animations are cancelled //is so that the CSS classes present on the element can be properly examined. var classNameToken = ' ' + className + ' '; if((animationEvent == 'addClass' && futureClassName.indexOf(classNameToken) >= 0) || (animationEvent == 'removeClass' && futureClassName.indexOf(classNameToken) == -1)) { fireDOMOperation(); fireDoneCallbackAsync(); return; } //the ng-animate class does nothing, but it's here to allow for //parent animations to find and cancel child animations when needed element.addClass(NG_ANIMATE_CLASS_NAME); element.data(NG_ANIMATE_STATE, { running:true, event:animationEvent, className:className, structural:!isClassBased, animations:animations, done:onBeforeAnimationsComplete }); //first we run the before animations and when all of those are complete //then we perform the DOM operation and run the next set of animations invokeRegisteredAnimationFns(animations, 'before', onBeforeAnimationsComplete); function onBeforeAnimationsComplete(cancelled) { fireDOMOperation(); if(cancelled === true) { closeAnimation(); return; } //set the done function to the final done function //so that the DOM event won't be executed twice by accident //if the after animation is cancelled as well var data = element.data(NG_ANIMATE_STATE); if(data) { data.done = closeAnimation; element.data(NG_ANIMATE_STATE, data); } invokeRegisteredAnimationFns(animations, 'after', closeAnimation); } function invokeRegisteredAnimationFns(animations, phase, allAnimationFnsComplete) { var endFnName = phase + 'End'; forEach(animations, function(animation, index) { var animationPhaseCompleted = function() { progress(index, phase); }; //there are no before functions for enter + move since the DOM //operations happen before the performAnimation method fires if(phase == 'before' && (animationEvent == 'enter' || animationEvent == 'move')) { animationPhaseCompleted(); return; } if(animation[phase]) { animation[endFnName] = isClassBased ? animation[phase](element, className, animationPhaseCompleted) : animation[phase](element, animationPhaseCompleted); } else { animationPhaseCompleted(); } }); function progress(index, phase) { var phaseCompletionFlag = phase + 'Complete'; var currentAnimation = animations[index]; currentAnimation[phaseCompletionFlag] = true; (currentAnimation[endFnName] || noop)(); for(var i=0;i<animations.length;i++) { if(!animations[i][phaseCompletionFlag]) return; } allAnimationFnsComplete(); } } function fireDoneCallbackAsync() { doneCallback && $timeout(doneCallback, 0, false); } //it is less complicated to use a flag than managing and cancelling //timeouts containing multiple callbacks. function fireDOMOperation() { if(!fireDOMOperation.hasBeenRun) { fireDOMOperation.hasBeenRun = true; domOperation(); } } function closeAnimation() { if(!closeAnimation.hasBeenRun) { closeAnimation.hasBeenRun = true; var data = element.data(NG_ANIMATE_STATE); if(data) { /* only structural animations wait for reflow before removing an animation, but class-based animations don't. An example of this failing would be when a parent HTML tag has a ng-class attribute causing ALL directives below to skip animations during the digest */ if(isClassBased) { cleanup(element); } else { data.closeAnimationTimeout = $timeout(function() { cleanup(element); }, 0, false); element.data(NG_ANIMATE_STATE, data); } } fireDoneCallbackAsync(); } } } function cancelChildAnimations(element) { var node = element[0]; if(node.nodeType != ELEMENT_NODE) { return; } forEach(node.querySelectorAll('.' + NG_ANIMATE_CLASS_NAME), function(element) { element = angular.element(element); var data = element.data(NG_ANIMATE_STATE); if(data) { cancelAnimations(data.animations); cleanup(element); } }); } function cancelAnimations(animations) { var isCancelledFlag = true; forEach(animations, function(animation) { if(!animations.beforeComplete) { (animation.beforeEnd || noop)(isCancelledFlag); } if(!animations.afterComplete) { (animation.afterEnd || noop)(isCancelledFlag); } }); } function cleanup(element) { if(element[0] == $rootElement[0]) { if(!rootAnimateState.disabled) { rootAnimateState.running = false; rootAnimateState.structural = false; } } else { element.removeClass(NG_ANIMATE_CLASS_NAME); element.removeData(NG_ANIMATE_STATE); } } function animationsDisabled(element, parentElement) { if (rootAnimateState.disabled) return true; if(element[0] == $rootElement[0]) { return rootAnimateState.disabled || rootAnimateState.running; } do { //the element did not reach the root element which means that it //is not apart of the DOM. Therefore there is no reason to do //any animations on it if(parentElement.length === 0) break; var isRoot = parentElement[0] == $rootElement[0]; var state = isRoot ? rootAnimateState : parentElement.data(NG_ANIMATE_STATE); var result = state && (!!state.disabled || !!state.running); if(isRoot || result) { return result; } if(isRoot) return true; } while(parentElement = parentElement.parent()); return true; } }]); $animateProvider.register('', ['$window', '$sniffer', '$timeout', function($window, $sniffer, $timeout) { // Detect proper transitionend/animationend event names. var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT; // If unprefixed events are not supported but webkit-prefixed are, use the latter. // Otherwise, just use W3C names, browsers not supporting them at all will just ignore them. // Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend` // but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`. // Register both events in case `window.onanimationend` is not supported because of that, // do the same for `transitionend` as Safari is likely to exhibit similar behavior. // Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit // therefore there is no reason to test anymore for other vendor prefixes: http://caniuse.com/#search=transition if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined) { CSS_PREFIX = '-webkit-'; TRANSITION_PROP = 'WebkitTransition'; TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend'; } else { TRANSITION_PROP = 'transition'; TRANSITIONEND_EVENT = 'transitionend'; } if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined) { CSS_PREFIX = '-webkit-'; ANIMATION_PROP = 'WebkitAnimation'; ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend'; } else { ANIMATION_PROP = 'animation'; ANIMATIONEND_EVENT = 'animationend'; } var DURATION_KEY = 'Duration'; var PROPERTY_KEY = 'Property'; var DELAY_KEY = 'Delay'; var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount'; var NG_ANIMATE_PARENT_KEY = '$$ngAnimateKey'; var NG_ANIMATE_CSS_DATA_KEY = '$$ngAnimateCSS3Data'; var NG_ANIMATE_FALLBACK_CLASS_NAME = 'ng-animate-start'; var NG_ANIMATE_FALLBACK_ACTIVE_CLASS_NAME = 'ng-animate-active'; var lookupCache = {}; var parentCounter = 0; var animationReflowQueue = [], animationTimer, timeOut = false; function afterReflow(callback) { animationReflowQueue.push(callback); $timeout.cancel(animationTimer); animationTimer = $timeout(function() { forEach(animationReflowQueue, function(fn) { fn(); }); animationReflowQueue = []; animationTimer = null; lookupCache = {}; }, 10, false); } function applyStyle(node, style) { var oldStyle = node.getAttribute('style') || ''; var newStyle = (oldStyle.length > 0 ? '; ' : '') + style; node.setAttribute('style', newStyle); return oldStyle; } function getElementAnimationDetails(element, cacheKey) { var data = cacheKey ? lookupCache[cacheKey] : null; if(!data) { var transitionDuration = 0; var transitionDelay = 0; var animationDuration = 0; var animationDelay = 0; var transitionDelayStyle; var animationDelayStyle; var transitionDurationStyle; var transitionPropertyStyle; //we want all the styles defined before and after forEach(element, function(element) { if (element.nodeType == ELEMENT_NODE) { var elementStyles = $window.getComputedStyle(element) || {}; transitionDurationStyle = elementStyles[TRANSITION_PROP + DURATION_KEY]; transitionDuration = Math.max(parseMaxTime(transitionDurationStyle), transitionDuration); transitionPropertyStyle = elementStyles[TRANSITION_PROP + PROPERTY_KEY]; transitionDelayStyle = elementStyles[TRANSITION_PROP + DELAY_KEY]; transitionDelay = Math.max(parseMaxTime(transitionDelayStyle), transitionDelay); animationDelayStyle = elementStyles[ANIMATION_PROP + DELAY_KEY]; animationDelay = Math.max(parseMaxTime(animationDelayStyle), animationDelay); var aDuration = parseMaxTime(elementStyles[ANIMATION_PROP + DURATION_KEY]); if(aDuration > 0) { aDuration *= parseInt(elementStyles[ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY], 10) || 1; } animationDuration = Math.max(aDuration, animationDuration); } }); data = { total : 0, transitionPropertyStyle: transitionPropertyStyle, transitionDurationStyle: transitionDurationStyle, transitionDelayStyle: transitionDelayStyle, transitionDelay: transitionDelay, transitionDuration: transitionDuration, animationDelayStyle: animationDelayStyle, animationDelay: animationDelay, animationDuration: animationDuration }; if(cacheKey) { lookupCache[cacheKey] = data; } } return data; } function parseMaxTime(str) { var maxValue = 0; var values = angular.isString(str) ? str.split(/\s*,\s*/) : []; forEach(values, function(value) { maxValue = Math.max(parseFloat(value) || 0, maxValue); }); return maxValue; } function getCacheKey(element) { var parentElement = element.parent(); var parentID = parentElement.data(NG_ANIMATE_PARENT_KEY); if(!parentID) { parentElement.data(NG_ANIMATE_PARENT_KEY, ++parentCounter); parentID = parentCounter; } return parentID + '-' + element[0].className; } function animateSetup(element, className) { var cacheKey = getCacheKey(element); var eventCacheKey = cacheKey + ' ' + className; var stagger = {}; var ii = lookupCache[eventCacheKey] ? ++lookupCache[eventCacheKey].total : 0; if(ii > 0) { var staggerClassName = className + '-stagger'; var staggerCacheKey = cacheKey + ' ' + staggerClassName; var applyClasses = !lookupCache[staggerCacheKey]; applyClasses && element.addClass(staggerClassName); stagger = getElementAnimationDetails(element, staggerCacheKey); applyClasses && element.removeClass(staggerClassName); } element.addClass(className); var timings = getElementAnimationDetails(element, eventCacheKey); /* there is no point in performing a reflow if the animation timeout is empty (this would cause a flicker bug normally in the page. There is also no point in performing an animation that only has a delay and no duration */ var maxDuration = Math.max(timings.transitionDuration, timings.animationDuration); if(maxDuration === 0) { element.removeClass(className); return false; } var node = element[0]; //temporarily disable the transition so that the enter styles //don't animate twice (this is here to avoid a bug in Chrome/FF). var activeClassName = ''; if(timings.transitionDuration > 0) { element.addClass(NG_ANIMATE_FALLBACK_CLASS_NAME); activeClassName += NG_ANIMATE_FALLBACK_ACTIVE_CLASS_NAME + ' '; blockTransitions(element); } else { blockKeyframeAnimations(element); } forEach(className.split(' '), function(klass, i) { activeClassName += (i > 0 ? ' ' : '') + klass + '-active'; }); element.data(NG_ANIMATE_CSS_DATA_KEY, { className : className, activeClassName : activeClassName, maxDuration : maxDuration, classes : className + ' ' + activeClassName, timings : timings, stagger : stagger, ii : ii }); return true; } function blockTransitions(element) { element[0].style[TRANSITION_PROP + PROPERTY_KEY] = 'none'; } function blockKeyframeAnimations(element) { element[0].style[ANIMATION_PROP] = 'none 0s'; } function unblockTransitions(element) { var node = element[0], prop = TRANSITION_PROP + PROPERTY_KEY; if(node.style[prop] && node.style[prop].length > 0) { node.style[prop] = ''; } } function unblockKeyframeAnimations(element) { element[0].style[ANIMATION_PROP] = ''; } function animateRun(element, className, activeAnimationComplete) { var data = element.data(NG_ANIMATE_CSS_DATA_KEY); if(!element.hasClass(className) || !data) { activeAnimationComplete(); return; } var node = element[0]; var timings = data.timings; var stagger = data.stagger; var maxDuration = data.maxDuration; var activeClassName = data.activeClassName; var maxDelayTime = Math.max(timings.transitionDelay, timings.animationDelay) * 1000; var startTime = Date.now(); var css3AnimationEvents = ANIMATIONEND_EVENT + ' ' + TRANSITIONEND_EVENT; var formerStyle; var ii = data.ii; var applyFallbackStyle, style = ''; if(timings.transitionDuration > 0) { var propertyStyle = timings.transitionPropertyStyle; if(propertyStyle.indexOf('all') == -1) { applyFallbackStyle = true; var fallbackProperty = $sniffer.msie ? '-ms-zoom' : 'border-spacing'; style += CSS_PREFIX + 'transition-property: ' + propertyStyle + ', ' + fallbackProperty + '; '; style += CSS_PREFIX + 'transition-duration: ' + timings.transitionDurationStyle + ', ' + timings.transitionDuration + 's; '; } } else { unblockKeyframeAnimations(element); } if(ii > 0) { if(stagger.transitionDelay > 0 && stagger.transitionDuration === 0) { var delayStyle = timings.transitionDelayStyle; if(applyFallbackStyle) { delayStyle += ', ' + timings.transitionDelay + 's'; } style += CSS_PREFIX + 'transition-delay: ' + prepareStaggerDelay(delayStyle, stagger.transitionDelay, ii) + '; '; } if(stagger.animationDelay > 0 && stagger.animationDuration === 0) { style += CSS_PREFIX + 'animation-delay: ' + prepareStaggerDelay(timings.animationDelayStyle, stagger.animationDelay, ii) + '; '; } } if(style.length > 0) { formerStyle = applyStyle(node, style); } element.on(css3AnimationEvents, onAnimationProgress); element.addClass(activeClassName); // This will automatically be called by $animate so // there is no need to attach this internally to the // timeout done method. return function onEnd(cancelled) { element.off(css3AnimationEvents, onAnimationProgress); element.removeClass(activeClassName); animateClose(element, className); if(formerStyle != null) { formerStyle.length > 0 ? node.setAttribute('style', formerStyle) : node.removeAttribute('style'); } }; function onAnimationProgress(event) { event.stopPropagation(); var ev = event.originalEvent || event; var timeStamp = ev.$manualTimeStamp || ev.timeStamp || Date.now(); /* $manualTimeStamp is a mocked timeStamp value which is set * within browserTrigger(). This is only here so that tests can * mock animations properly. Real events fallback to event.timeStamp, * or, if they don't, then a timeStamp is automatically created for them. * We're checking to see if the timeStamp surpasses the expected delay, * but we're using elapsedTime instead of the timeStamp on the 2nd * pre-condition since animations sometimes close off early */ if(Math.max(timeStamp - startTime, 0) >= maxDelayTime && ev.elapsedTime >= maxDuration) { activeAnimationComplete(); } } } function prepareStaggerDelay(delayStyle, staggerDelay, index) { var style = ''; forEach(delayStyle.split(','), function(val, i) { style += (i > 0 ? ',' : '') + (index * staggerDelay + parseInt(val, 10)) + 's'; }); return style; } function animateBefore(element, className) { if(animateSetup(element, className)) { return function(cancelled) { cancelled && animateClose(element, className); }; } } function animateAfter(element, className, afterAnimationComplete) { if(element.data(NG_ANIMATE_CSS_DATA_KEY)) { return animateRun(element, className, afterAnimationComplete); } else { animateClose(element, className); afterAnimationComplete(); } } function animate(element, className, animationComplete) { //If the animateSetup function doesn't bother returning a //cancellation function then it means that there is no animation //to perform at all var preReflowCancellation = animateBefore(element, className); if(!preReflowCancellation) { animationComplete(); return; } //There are two cancellation functions: one is before the first //reflow animation and the second is during the active state //animation. The first function will take care of removing the //data from the element which will not make the 2nd animation //happen in the first place var cancel = preReflowCancellation; afterReflow(function() { unblockTransitions(element); //once the reflow is complete then we point cancel to //the new cancellation function which will remove all of the //animation properties from the active animation cancel = animateAfter(element, className, animationComplete); }); return function(cancelled) { (cancel || noop)(cancelled); }; } function animateClose(element, className) { element.removeClass(className); element.removeClass(NG_ANIMATE_FALLBACK_CLASS_NAME); element.removeData(NG_ANIMATE_CSS_DATA_KEY); } return { allowCancel : function(element, animationEvent, className) { //always cancel the current animation if it is a //structural animation var oldClasses = (element.data(NG_ANIMATE_CSS_DATA_KEY) || {}).classes; if(!oldClasses || ['enter','leave','move'].indexOf(animationEvent) >= 0) { return true; } var parentElement = element.parent(); var clone = angular.element(element[0].cloneNode()); //make the element super hidden and override any CSS style values clone.attr('style','position:absolute; top:-9999px; left:-9999px'); clone.removeAttr('id'); clone.html(''); forEach(oldClasses.split(' '), function(klass) { clone.removeClass(klass); }); var suffix = animationEvent == 'addClass' ? '-add' : '-remove'; clone.addClass(suffixClasses(className, suffix)); parentElement.append(clone); var timings = getElementAnimationDetails(clone); clone.remove(); return Math.max(timings.transitionDuration, timings.animationDuration) > 0; }, enter : function(element, animationCompleted) { return animate(element, 'ng-enter', animationCompleted); }, leave : function(element, animationCompleted) { return animate(element, 'ng-leave', animationCompleted); }, move : function(element, animationCompleted) { return animate(element, 'ng-move', animationCompleted); }, beforeAddClass : function(element, className, animationCompleted) { var cancellationMethod = animateBefore(element, suffixClasses(className, '-add')); if(cancellationMethod) { afterReflow(function() { unblockTransitions(element); animationCompleted(); }); return cancellationMethod; } animationCompleted(); }, addClass : function(element, className, animationCompleted) { return animateAfter(element, suffixClasses(className, '-add'), animationCompleted); }, beforeRemoveClass : function(element, className, animationCompleted) { var cancellationMethod = animateBefore(element, suffixClasses(className, '-remove')); if(cancellationMethod) { afterReflow(function() { unblockTransitions(element); animationCompleted(); }); return cancellationMethod; } animationCompleted(); }, removeClass : function(element, className, animationCompleted) { return animateAfter(element, suffixClasses(className, '-remove'), animationCompleted); } }; function suffixClasses(classes, suffix) { var className = ''; classes = angular.isArray(classes) ? classes : classes.split(/\s+/); forEach(classes, function(klass, i) { if(klass && klass.length > 0) { className += (i > 0 ? ' ' : '') + klass + suffix; } }); return className; } }]); }]);
{'content_hash': 'ed82e7ac286038fb9ede14c272a09167', 'timestamp': '', 'source': 'github', 'line_count': 1279, 'max_line_length': 244, 'avg_line_length': 48.320562939796716, 'alnum_prop': 0.5992362706708521, 'repo_name': 'songlinjava/angular.js', 'id': '81d200431b5933cfd15f8d8accec62cc63e5388d', 'size': '61802', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/ngAnimate/animate.js', 'mode': '33188', 'license': 'mit', 'language': []}
namespace base { class Thread; } namespace sandbox { class SANDBOX_EXPORT ThreadHelpers { public: // Check whether the current process is single threaded. |proc_fd| // must be a file descriptor to /proc/ and remains owned by the // caller. static bool IsSingleThreaded(int proc_fd); static bool IsSingleThreaded(); // Crash if the current process is not single threaded. This will wait // on /proc to be updated. In the case where this doesn't crash, this will // return promptly. In the case where this does crash, this will first wait // for a few ms in Debug mode, a few seconds in Release mode. static void AssertSingleThreaded(int proc_fd); static void AssertSingleThreaded(); // Stop |thread| and ensure that it does not have an entry in // /proc/self/task/ from the point of view of the current thread. This is // the way to stop threads before calling IsSingleThreaded(). static bool StopThreadAndWatchProcFS(int proc_fd, base::Thread* thread); static const char* GetAssertSingleThreadedErrorMessageForTests(); private: DISALLOW_IMPLICIT_CONSTRUCTORS(ThreadHelpers); }; } // namespace sandbox #endif // SANDBOX_LINUX_SERVICES_THREAD_HELPERS_H_
{'content_hash': '7284ed8fa925d757aa39452492f6c8fe', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 77, 'avg_line_length': 36.303030303030305, 'alnum_prop': 0.7420701168614358, 'repo_name': 'Fireblend/chromium-crosswalk', 'id': 'f4abdffd03b418b15b07f08a6b32b3b08d499db9', 'size': '1525', 'binary': False, 'copies': '13', 'ref': 'refs/heads/master', 'path': 'sandbox/linux/services/thread_helpers.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'AppleScript', 'bytes': '6973'}, {'name': 'Arduino', 'bytes': '464'}, {'name': 'Assembly', 'bytes': '34367'}, {'name': 'Batchfile', 'bytes': '8451'}, {'name': 'C', 'bytes': '9397825'}, {'name': 'C++', 'bytes': '235052525'}, {'name': 'CSS', 'bytes': '951745'}, {'name': 'DM', 'bytes': '60'}, {'name': 'Emacs Lisp', 'bytes': '988'}, {'name': 'Groff', 'bytes': '2494'}, {'name': 'HTML', 'bytes': '29070071'}, {'name': 'Java', 'bytes': '10089056'}, {'name': 'JavaScript', 'bytes': '20170506'}, {'name': 'Makefile', 'bytes': '68234'}, {'name': 'Objective-C', 'bytes': '1639405'}, {'name': 'Objective-C++', 'bytes': '9478782'}, {'name': 'PHP', 'bytes': '97817'}, {'name': 'PLpgSQL', 'bytes': '178732'}, {'name': 'Perl', 'bytes': '63937'}, {'name': 'Protocol Buffer', 'bytes': '465313'}, {'name': 'Python', 'bytes': '8146950'}, {'name': 'Shell', 'bytes': '473684'}, {'name': 'Standard ML', 'bytes': '5034'}, {'name': 'XSLT', 'bytes': '418'}, {'name': 'nesC', 'bytes': '18347'}]}
package io.leangen.graphql.generator.mapping; import io.leangen.graphql.util.ClassUtils; import java.lang.reflect.AnnotatedType; public abstract class AbstractSimpleTypeAdapter<T, S> extends AbstractTypeAdapter<T, S> { @SuppressWarnings("WeakerAccess") protected final Class<?> rawSourceType; protected AbstractSimpleTypeAdapter() { this.rawSourceType = ClassUtils.getRawType(sourceType.getType()); } @Override public boolean supports(AnnotatedType type) { return ClassUtils.isSuperClass(rawSourceType, type); } }
{'content_hash': 'f88b0e383bb1f5c93b8afee69ad8b315', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 89, 'avg_line_length': 28.2, 'alnum_prop': 0.74822695035461, 'repo_name': 'leangen/GraphQL-SPQR', 'id': '5dc471494ab5746d371c3c433df2d3e081b89162', 'size': '564', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/io/leangen/graphql/generator/mapping/AbstractSimpleTypeAdapter.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '1016834'}]}
<?php /** * Adds methods for limited kinds of faceting using the silverstripe ORM. * This is used by the default ShopSearchSimple adapter but also can * be added to other contexts (such as ProductCategory). * * TODO: Facet class + subclasses * * @author Mark Guinn <[email protected]> * @date 10.21.2013 * @package shop_search * @subpackage helpers */ class FacetHelper extends Object { /** @var bool - if this is turned on it will use an algorithm that doesn't require traversing the data set if possible */ private static $faster_faceting = false; /** @var bool - should the facets (link and checkbox only) be sorted - this can mess with things like category lists */ private static $sort_facet_values = true; /** @var string - I don't know why you'd want to override this, but you could if you wanted */ private static $attribute_facet_regex = '/^ATT(\d+)$/'; /** @var bool - For checkbox facets, is the initial state all checked or all unchecked? */ private static $default_checkbox_state = true; /** * @return FacetHelper */ public static function inst() { return Injector::inst()->get('FacetHelper'); } /** * Performs some quick pre-processing on filters from any source * * @param array $filters * @return array */ public function scrubFilters($filters) { if (!is_array($filters)) { $filters = array(); } foreach ($filters as $k => $v) { if (empty($v)) { unset($filters[$k]); } // this allows you to send an array as a comma-separated list, which is easier on the query string length if (is_string($v) && strpos($v, 'LIST~') === 0) { $filters[$k] = explode(',', substr($v, 5)); } } return $filters; } /** * @param DataList $list * @param array $filters * @param DataObject|string $sing - just a singleton object we can get information off of * @return DataList */ public function addFiltersToDataList($list, array $filters, $sing=null) { if (!$sing) { $sing = singleton($list->dataClass()); } if (is_string($sing)) { $sing = singleton($sing); } if (!empty($filters)) { foreach ($filters as $filterField => $filterVal) { if ($sing->hasExtension('HasStaticAttributes') && preg_match(self::config()->attribute_facet_regex, $filterField, $matches)) { // $sav = $sing->StaticAttributeValues(); // Debug::log("sav = {$sav->getJoinTable()}, {$sav->getLocalKey()}, {$sav->getForeignKey()}"); // $list = $list // ->innerJoin($sav->getJoinTable(), "\"{$sing->baseTable()}\".\"ID\" = \"{$sav->getJoinTable()}\".\"{$sav->getLocalKey()}\"") // ->filter("\"{$sav->getJoinTable()}\".\"{$sav->getForeignKey()}\"", $filterVal) // ; // TODO: This logic should be something like the above, but I don't know // how to get the join table from a singleton (which returns an UnsavedRelationList // instead of a ManyManyList). I've got a deadline to meet, though, so this // will catch the majority of cases as long as the extension is applied to the // Product class instead of a subclass. $list = $list ->innerJoin('Product_StaticAttributeTypes', "\"SiteTree\".\"ID\" = \"Product_StaticAttributeTypes\".\"ProductID\"") ->innerJoin('ProductAttributeValue', "\"Product_StaticAttributeTypes\".\"ProductAttributeTypeID\" = \"ProductAttributeValue\".\"TypeID\"") ->innerJoin('Product_StaticAttributeValues', "\"SiteTree\".\"ID\" = \"Product_StaticAttributeValues\".\"ProductID\" AND \"ProductAttributeValue\".\"ID\" = \"Product_StaticAttributeValues\".\"ProductAttributeValueID\"") ->filter("Product_StaticAttributeValues.ProductAttributeValueID", $filterVal); } else { $list = $list->filter($this->processFilterField($sing, $filterField, $filterVal)); } } } return $list; } /** * @param DataObject $rec This would normally just be a singleton but we don't want to have to create it over and over * @param string $filterField * @param mixed $filterVal * @return array - returns the new filter added */ public function processFilterField($rec, $filterField, $filterVal) { // First check for VFI fields if ($rec->hasExtension('VirtualFieldIndex') && ($spec = $rec->getVFISpec($filterField))) { if ($spec['Type'] == VirtualFieldIndex::TYPE_LIST) { // Lists have to be handled a little differently $f = $rec->getVFIFieldName($filterField) . ':PartialMatch'; if (is_array($filterVal)) { foreach ($filterVal as &$val) { $val = '|' . $val . '|'; } return array($f => $filterVal); } else { return array($f => '|' . $filterVal . '|'); } } else { // Simples are simple $filterField = $rec->getVFIFieldName($filterField); } } // Next check for regular db fields if ($rec->dbObject($filterField)) { // Is it a range value? if (is_string($filterVal) && preg_match('/^RANGE\~(.+)\~(.+)$/', $filterVal, $m)) { $filterField .= ':Between'; $filterVal = array_slice($m, 1, 2); } return array($filterField => $filterVal); } return array(); } /** * Processes the facet spec and removes any shorthand (field => label). * @param array $facetSpec * @return array */ public function expandFacetSpec(array $facetSpec) { if (is_null($facetSpec)) { return array(); } $facets = array(); foreach ($facetSpec as $field => $label) { if (is_array($label)) { $facets[$field] = $label; } else { $facets[$field] = array('Label' => $label); } if (empty($facets[$field]['Source'])) { $facets[$field]['Source'] = $field; } if (empty($facets[$field]['Type'])) { $facets[$field]['Type'] = ShopSearch::FACET_TYPE_LINK; } if (empty($facets[$field]['Values'])) { $facets[$field]['Values'] = array(); } else { $vals = $facets[$field]['Values']; if (is_string($vals)) { $vals = eval('return ' . $vals . ';'); } $facets[$field]['Values'] = array(); foreach ($vals as $val => $lbl) { $facets[$field]['Values'][$val] = new ArrayData(array( 'Label' => $lbl, 'Value' => $val, 'Count' => 0, )); } } } return $facets; } /** * This is super-slow. I'm assuming if you're using facets you * probably also ought to be using Solr or something else. Or * maybe you have unlimited time and can refactor this feature * and submit a pull request... * * TODO: If this is going to be used for categories we're going * to have to really clean it up and speed it up. * Suggestion: * - option to turn off counts * - switch order of nested array so we don't go through results unless needed * - if not doing counts, min/max and link facets can be handled w/ queries * - separate that bit out into a new function * NOTE: This is partially done with the "faster_faceting" config * option but more could be done, particularly by covering link facets as well. * * Output - list of ArrayData in the format: * Label - name of the facet * Source - field name of the facet * Type - one of the ShopSearch::FACET_TYPE_XXXX constants * Values - SS_List of possible values for this facet * * @param SS_List $matches * @param array $facetSpec * @param bool $autoFacetAttributes [optional] * @return ArrayList */ public function buildFacets(SS_List $matches, array $facetSpec, $autoFacetAttributes=false) { $facets = $this->expandFacetSpec($facetSpec); if (!$autoFacetAttributes && (empty($facets) || !$matches || !$matches->count())) { return new ArrayList(); } $fasterMethod = (bool)$this->config()->faster_faceting; // fill them in foreach ($facets as $field => &$facet) { if (preg_match(self::config()->attribute_facet_regex, $field, $m)) { $this->buildAttributeFacet($matches, $facet, $m[1]); continue; } // NOTE: using this method range and checkbox facets don't get counts if ($fasterMethod && $facet['Type'] != ShopSearch::FACET_TYPE_LINK) { if ($facet['Type'] == ShopSearch::FACET_TYPE_RANGE) { if (isset($facet['RangeMin'])) { $facet['MinValue'] = $facet['RangeMin']; } if (isset($facet['RangeMax'])) { $facet['MaxValue'] = $facet['RangeMax']; } } continue; } foreach ($matches as $rec) { // If it's a range facet, set up the min/max if ($facet['Type'] == ShopSearch::FACET_TYPE_RANGE) { if (isset($facet['RangeMin'])) { $facet['MinValue'] = $facet['RangeMin']; } if (isset($facet['RangeMax'])) { $facet['MaxValue'] = $facet['RangeMax']; } } // If the field is accessible via normal methods, including // a user-defined getter, prefer that $fieldValue = $rec->relObject($field); if (is_null($fieldValue) && $rec->hasMethod($meth = "get{$field}")) { $fieldValue = $rec->$meth(); } // If not, look for a VFI field if (!$fieldValue && $rec->hasExtension('VirtualFieldIndex')) { $fieldValue = $rec->getVFI($field); } // If we found something, process it if (!empty($fieldValue)) { // normalize so that it's iterable if (!is_array($fieldValue) && !$fieldValue instanceof SS_List) { $fieldValue = array($fieldValue); } foreach ($fieldValue as $obj) { if (empty($obj)) { continue; } // figure out the right label if (is_object($obj) && $obj->hasMethod('Nice')) { $lbl = $obj->Nice(); } elseif (is_object($obj) && !empty($obj->Title)) { $lbl = $obj->Title; } elseif ( is_numeric($obj) && !empty($facet['LabelFormat']) && $facet['LabelFormat'] === 'Currency' && $facet['Type'] !== ShopSearch::FACET_TYPE_RANGE // this one handles it via javascript ) { $tmp = Currency::create($field); $tmp->setValue($obj); $lbl = $tmp->Nice(); } else { $lbl = (string)$obj; } // figure out the value for sorting if (is_object($obj) && $obj->hasMethod('getAmount')) { $val = $obj->getAmount(); } elseif (is_object($obj) && !empty($obj->ID)) { $val = $obj->ID; } else { $val = (string)$obj; } // if it's a range facet, calculate the min and max if ($facet['Type'] == ShopSearch::FACET_TYPE_RANGE) { if (!isset($facet['MinValue']) || $val < $facet['MinValue']) { $facet['MinValue'] = $val; $facet['MinLabel'] = $lbl; } if (!isset($facet['RangeMin']) || $val < $facet['RangeMin']) { $facet['RangeMin'] = $val; } if (!isset($facet['MaxValue']) || $val > $facet['MaxValue']) { $facet['MaxValue'] = $val; $facet['MaxLabel'] = $lbl; } if (!isset($facet['RangeMax']) || $val > $facet['RangeMax']) { $facet['RangeMax'] = $val; } } // Tally the value in the facets if (!isset($facet['Values'][$val])) { $facet['Values'][$val] = new ArrayData(array( 'Label' => $lbl, 'Value' => $val, 'Count' => 1, )); } elseif ($facet['Values'][$val]) { $facet['Values'][$val]->Count++; } } } } } // if we're auto-building the facets based on attributes, if ($autoFacetAttributes) { $facets = array_merge($this->buildAllAttributeFacets($matches), $facets); } // convert values to arraylist $out = new ArrayList(); $sortValues = self::config()->sort_facet_values; foreach ($facets as $f) { if ($sortValues) { ksort($f['Values']); } $f['Values'] = new ArrayList($f['Values']); $out->push(new ArrayData($f)); } return $out; } /** * NOTE: this will break if applied to something that's not a SiteTree subclass. * @param DataList|PaginatedList $matches * @param array $facet * @param int $typeID */ protected function buildAttributeFacet($matches, array &$facet, $typeID) { $q = $matches instanceof PaginatedList ? $matches->getList()->dataQuery()->query() : $matches->dataQuery()->query(); if (empty($facet['Label'])) { $type = ProductAttributeType::get()->byID($typeID); $facet['Label'] = $type->Label; } $baseTable = $q->getFrom(); if (is_array($baseTable)) { $baseTable = reset($baseTable); } $q = $q->setSelect(array()) ->selectField('"ProductAttributeValue"."ID"', 'Value') ->selectField('"ProductAttributeValue"."Value"', 'Label') ->selectField('count(distinct '.$baseTable.'."ID")', 'Count') ->selectField('"ProductAttributeValue"."Sort"') ->addInnerJoin('Product_StaticAttributeValues', $baseTable.'."ID" = "Product_StaticAttributeValues"."ProductID"') ->addInnerJoin('ProductAttributeValue', '"Product_StaticAttributeValues"."ProductAttributeValueID" = "ProductAttributeValue"."ID"') ->addWhere(sprintf("\"ProductAttributeValue\".\"TypeID\" = '%d'", $typeID)) ->setOrderBy('"ProductAttributeValue"."Sort"', 'ASC') ->setGroupBy('"ProductAttributeValue"."ID"') ->execute() ; $facet['Values'] = array(); foreach ($q as $row) { $facet['Values'][ $row['Value'] ] = new ArrayData($row); } } /** * Builds facets from all attributes present in the data set. * @param DataList|PaginatedList $matches * @return array */ protected function buildAllAttributeFacets($matches) { $q = $matches instanceof PaginatedList ? $matches->getList()->dataQuery()->query() : $matches->dataQuery()->query(); // this is the easiest way to get SiteTree vs SiteTree_Live $baseTable = $q->getFrom(); if (is_array($baseTable)) { $baseTable = reset($baseTable); } $q = $q->setSelect(array()) ->selectField('"ProductAttributeType"."ID"', 'TypeID') ->selectField('"ProductAttributeType"."Label"', 'TypeLabel') ->selectField('"ProductAttributeValue"."ID"', 'Value') ->selectField('"ProductAttributeValue"."Value"', 'Label') ->selectField('count(distinct '.$baseTable.'."ID")', 'Count') ->selectField('"ProductAttributeValue"."Sort"') ->addInnerJoin('Product_StaticAttributeTypes', $baseTable.'."ID" = "Product_StaticAttributeTypes"."ProductID"') ->addInnerJoin('ProductAttributeType', '"Product_StaticAttributeTypes"."ProductAttributeTypeID" = "ProductAttributeType"."ID"') ->addInnerJoin('Product_StaticAttributeValues', $baseTable.'."ID" = "Product_StaticAttributeValues"."ProductID"') ->addInnerJoin('ProductAttributeValue', '"Product_StaticAttributeValues"."ProductAttributeValueID" = "ProductAttributeValue"."ID"' . ' AND "ProductAttributeValue"."TypeID" = "ProductAttributeType"."ID"') ->setOrderBy(array( '"ProductAttributeType"."Label"' => 'ASC', '"ProductAttributeValue"."Sort"' => 'ASC', )) ->setGroupBy(array('"ProductAttributeValue"."ID"', '"ProductAttributeType"."ID"')) ->execute() ; $curType = 0; $facets = array(); $curFacet = null; foreach ($q as $row) { if ($curType != $row['TypeID']) { if ($curType > 0) { $facets['ATT'.$curType] = $curFacet; } $curType = $row['TypeID']; $curFacet = array( 'Label' => $row['TypeLabel'], 'Source' => 'ATT'.$curType, 'Type' => ShopSearch::FACET_TYPE_LINK, 'Values' => array(), ); } unset($row['TypeID']); unset($row['TypeLabel']); $curFacet['Values'][ $row['Value'] ] = new ArrayData($row); } if ($curType > 0) { $facets['ATT'.$curType] = $curFacet; } return $facets; } /** * Inserts a "Link" field into the values for each facet which can be * used to get a filtered search based on that facets * * @param ArrayList $facets * @param array $baseParams * @param string $baseLink * @return ArrayList */ public function insertFacetLinks(ArrayList $facets, array $baseParams, $baseLink) { $qs_f = Config::inst()->get('ShopSearch', 'qs_filters'); $qs_t = Config::inst()->get('ShopSearch', 'qs_title'); foreach ($facets as $facet) { switch ($facet->Type) { case ShopSearch::FACET_TYPE_RANGE: $params = array_merge($baseParams, array()); if (!isset($params[$qs_f])) { $params[$qs_f] = array(); } $params[$qs_f][$facet->Source] = 'RANGEFACETVALUE'; $params[$qs_t] = $facet->Label . ': RANGEFACETLABEL'; $facet->Link = $baseLink . '?' . http_build_query($params); break; case ShopSearch::FACET_TYPE_CHECKBOX; $facet->LinkDetails = json_encode(array( 'filter' => $qs_f, 'source' => $facet->Source, 'leaves' => $facet->FilterOnlyLeaves, )); // fall through on purpose default: foreach ($facet->Values as $value) { // make a copy of the existing params $params = array_merge($baseParams, array()); // add the filter for this value if (!isset($params[$qs_f])) { $params[$qs_f] = array(); } if ($facet->Type == ShopSearch::FACET_TYPE_CHECKBOX) { unset($params[$qs_f][$facet->Source]); // this will be figured out via javascript $params[$qs_t] = ($value->Active ? 'Remove ' : '') . $facet->Label . ': ' . $value->Label; } else { $params[$qs_f][$facet->Source] = $value->Value; $params[$qs_t] = $facet->Label . ': ' . $value->Label; } // build a new link $value->Link = $baseLink . '?' . http_build_query($params); } } } return $facets; } /** * @param ArrayList $children * @return array */ protected function getRecursiveChildValues(ArrayList $children) { $out = array(); foreach ($children as $child) { $out[$child->Value] = $child->Value; if (!empty($child->Children)) { $out += $this->getRecursiveChildValues($child->Children); } } return $out; } /** * For checkbox and range facets, this updates the state (checked and min/max) * based on current filter values. * * @param ArrayList $facets * @param array $filters * @return ArrayList */ public function updateFacetState(ArrayList $facets, array $filters) { foreach ($facets as $facet) { if ($facet->Type == ShopSearch::FACET_TYPE_CHECKBOX) { if (empty($filters[$facet->Source])) { // If the filter is not being used at all, we count // all values as active. foreach ($facet->Values as $value) { $value->Active = (bool)FacetHelper::config()->default_checkbox_state; } } else { $filterVals = $filters[$facet->Source]; if (!is_array($filterVals)) { $filterVals = array($filterVals); } $this->updateCheckboxFacetState( !empty($facet->NestedValues) ? $facet->NestedValues : $facet->Values, $filterVals, !empty($facet->FilterOnlyLeaves)); } } elseif ($facet->Type == ShopSearch::FACET_TYPE_RANGE) { if (!empty($filters[$facet->Source]) && preg_match('/^RANGE\~(.+)\~(.+)$/', $filters[$facet->Source], $m)) { $facet->MinValue = $m[1]; $facet->MaxValue = $m[2]; } } } return $facets; } /** * For checkboxes, updates the state based on filters. Handles hierarchies and FilterOnlyLeaves * @param ArrayList $values * @param array $filterVals * @param bool $filterOnlyLeaves [optional] * @return bool - true if any of the children are true, false if all children are false */ protected function updateCheckboxFacetState(ArrayList $values, array $filterVals, $filterOnlyLeaves=false) { $out = false; foreach ($values as $value) { if ($filterOnlyLeaves && !empty($value->Children)) { if (in_array($value->Value, $filterVals)) { // This wouldn't be normal, but even if it's not a leaf, we want to handle // the case where a filter might be set for this node. It should still show up correctly. $value->Active = true; foreach ($value->Children as $c) { $c->Active = true; } // TODO: handle more than one level of recursion here } else { $value->Active = $this->updateCheckboxFacetState($value->Children, $filterVals, $filterOnlyLeaves); } } else { $value->Active = in_array($value->Value, $filterVals); } if ($value->Active) { $out = true; } } return $out; } /** * If there are any facets (link or checkbox) that have a HierarchyDivider field * in the spec, transform them into a hierarchy so they can be displayed as such. * * @param ArrayList $facets * @return ArrayList */ public function transformHierarchies(ArrayList $facets) { foreach ($facets as $facet) { if (!empty($facet->HierarchyDivider)) { $out = new ArrayList(); $parentStack = array(); foreach ($facet->Values as $value) { if (empty($value->Label)) { continue; } $value->FullLabel = $value->Label; // Look for the most recent parent that matches the beginning of this one while (count($parentStack) > 0) { $curParent = $parentStack[ count($parentStack)-1 ]; if (strpos($value->Label, $curParent->FullLabel) === 0) { if (!isset($curParent->Children)) { $curParent->Children = new ArrayList(); } // Modify the name so we only show the last component $value->FullLabel = $value->Label; $p = strrpos($value->Label, $facet->HierarchyDivider); if ($p > -1) { $value->Label = trim(substr($value->Label, $p + 1)); } $curParent->Children->push($value); break; } else { array_pop($parentStack); } } // If we went all the way back to the root without a match, this is // a new parent item if (count($parentStack) == 0) { $out->push($value); } // Each item could be a potential parent. If it's not it will get popped // immediately on the next iteration $parentStack[] = $value; } $facet->NestedValues = $out; } } return $facets; } }
{'content_hash': '6478753a7729571cecfad83c1a477ed7', 'timestamp': '', 'source': 'github', 'line_count': 691, 'max_line_length': 242, 'avg_line_length': 40.04920405209841, 'alnum_prop': 0.4753559297535593, 'repo_name': 'markguinn/silverstripe-shop-search', 'id': 'bfb09294dcb715bc4cacf98092967be2b163a30f', 'size': '27674', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'code/helpers/FacetHelper.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '3858'}, {'name': 'JavaScript', 'bytes': '16835'}, {'name': 'PHP', 'bytes': '152023'}, {'name': 'Scheme', 'bytes': '3171'}, {'name': 'Shell', 'bytes': '463'}]}
package org.jetbrains.plugins.hocon.misc import com.intellij.psi.PsiElement import com.intellij.xml.breadcrumbs.BreadcrumbsInfoProvider import org.jetbrains.plugins.hocon.lang.HoconLanguage import org.jetbrains.plugins.hocon.psi.HKeyedField class HoconBreadcrumbsInfoProvider extends BreadcrumbsInfoProvider { def getElementTooltip(e: PsiElement) = null def getElementInfo(e: PsiElement): String = e match { case kf: HKeyedField => kf.key.map(_.stringValue).getOrElse("") case _ => "" } def acceptElement(e: PsiElement): Boolean = e match { case _: HKeyedField => true case _ => false } def getLanguages = Array(HoconLanguage) }
{'content_hash': '5a63083ddf29feded05294f5a117eca1', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 68, 'avg_line_length': 30.09090909090909, 'alnum_prop': 0.7522658610271903, 'repo_name': 'loskutov/intellij-scala', 'id': '0fc95d7dcab59656b53fc4efed2ef81453c363f6', 'size': '662', 'binary': False, 'copies': '2', 'ref': 'refs/heads/idea172.x-better-implicits', 'path': 'src/org/jetbrains/plugins/hocon/misc/HoconBreadcrumbsInfoProvider.scala', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '55566'}, {'name': 'Java', 'bytes': '1397858'}, {'name': 'Lex', 'bytes': '35728'}, {'name': 'Scala', 'bytes': '11387086'}, {'name': 'Shell', 'bytes': '537'}]}
export default connect()(App)
{'content_hash': 'e182d1add0a3d11793f891809b401601', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 29, 'avg_line_length': 30.0, 'alnum_prop': 0.7666666666666667, 'repo_name': 'yp/eslint-plugin-import', 'id': '9c1d8d40706b16077e1649bf8f5d1f4e44f8b275', 'size': '45', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'tests/files/redux.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CoffeeScript', 'bytes': '27'}, {'name': 'JavaScript', 'bytes': '141336'}]}