code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
# -*- coding: utf-8 -*- """Functions for manipulating FGONG files. These are provided through the **FGONG** object and a module function to read an **FGONG** object from a file. """ import numpy as np import warnings from .adipls import fgong_to_amdl from .constants import G_DEFAULT from .utils import integrate, tomso_open, regularize from .utils import FullStellarModel def load_fgong(filename, fmt='ivers', return_comment=False, return_object=True, G=None): """Given an FGONG file, returns NumPy arrays ``glob`` and ``var`` that correspond to the scalar and point-wise variables, as specified in the `FGONG format`_. .. _FGONG format: https://www.astro.up.pt/corot/ntools/docs/CoRoT_ESTA_Files.pdf Also returns the first four lines of the file as a `comment`, if desired. The version number ``ivers`` is used to infer the format of floats if ``fmt='ivers'``. If ``return_object`` is ``True``, instead returns an :py:class:`FGONG` object. This is the default behaviour as of v0.0.12. The old behaviour will be dropped completely from v0.1.0. Parameters ---------- filename: str Name of the FGONG file to read. fmt: str, optional Format string for floats in `glob` and `var`. If ``'ivers'``, uses ``%16.9E`` if the file's ``ivers < 1000`` or ``%26.18E3` if ``ivers >= 1000``. If ``'auto'``, tries to guess the size of each float. (default: 'ivers') return_comment: bool, optional If ``True``, return the first four lines of the FGONG file. These are comments that are not used in any calculations. Returns ------- glob: NumPy array The scalar (or global) variables for the stellar model var: NumPy array The point-wise variables for the stellar model. i.e. things that vary through the star like temperature, density, etc. comment: list of strs, optional The first four lines of the FGONG file. These are comments that are not used in any calculations. Only returned if ``return_comment=True``. """ with tomso_open(filename, 'rb') as f: comment = [f.readline().decode('utf-8').strip() for i in range(4)] nn, iconst, ivar, ivers = [int(i) for i in f.readline().decode('utf-8').split()] # lines = f.readlines() lines = [line.decode('utf-8').lower().replace('d', 'e') for line in f.readlines()] tmp = [] if fmt == 'ivers': if ivers < 1000: N = 16 else: N = 27 # try to guess the length of each float in the data elif fmt == 'auto': N = len(lines[0])//5 else: N = len(fmt % -1.111) for line in lines: for i in range(len(line)//N): s = line[i*N:i*N+N] # print(s) if s[-9:] == '-Infinity': s = '-Inf' elif s[-9:] == ' Infinity': s = 'Inf' elif s.lower().endswith('nan'): s = 'nan' elif 'd' in s.lower(): s = s.lower().replace('d','e') tmp.append(float(s)) glob = np.array(tmp[:iconst]) var = np.array(tmp[iconst:]).reshape((-1, ivar)) if return_object: return FGONG(glob, var, ivers=ivers, G=G, description=comment) else: warnings.warn("From tomso 0.1.0+, `fgong.load_fgong` will only " "return an `FGONG` object: use `return_object=True` " "to mimic future behaviour", FutureWarning) if return_comment: return glob, var, comment else: return glob, var def save_fgong(filename, glob, var, ivers=1300, comment=['','','',''], float_formatter='ivers'): """Given data for an FGONG file in the format returned by :py:meth:`~tomso.fgong.load_fgong` (i.e. two NumPy arrays and a possible header), writes the data to a file. This function will be dropped from v0.1.0 in favour of the `to_file` function of the :py:class:`FGONG` object. Parameters ---------- filename: str Filename to which FGONG data is written. glob: NumPy array The global variables for the stellar model. var: NumPy array The point-wise variables for the stellar model. i.e. things that vary through the star like temperature, density, etc. ivers: int, optional The integer indicating the version number of the file. (default=1300) comment: list of strs, optional The first four lines of the FGONG file, which usually contain notes about the stellar model. float_formatter: str or function Determines how floating point numbers are formatted. If ``'ivers'`` (the default), use the standard formats ``%16.9E`` if ``ivers < 1000`` or ``%26.18E3`` if ``ivers >= 1000``. If a Python format specifier (e.g. ``'%16.9E'``), pass floats into that like ``float_formatter % float``. Otherwise, must be a function that takes a float as an argument and returns a string. In most circumstances you'll want to control the output by changing the value of ``'ivers'``. """ nn, ivar = var.shape iconst = len(glob) if float_formatter == 'ivers': if ivers < 1000: def ff(x): if not np.isfinite(x): return '%16s' % x s = np.format_float_scientific(x, precision=9, unique=False, exp_digits=2, sign=True) if s[0] == '+': s = ' ' + s[1:] return s else: def ff(x): if not np.isfinite(x): return '%27s' % x s = np.format_float_scientific(x, precision=18, unique=False, exp_digits=3, sign=True) if s[0] == '+': s = ' ' + s[1:] return ' ' + s else: try: float_formatter % 1.111 ff = lambda x: float_formatter % x except TypeError: ff = float_formatter with open(filename, 'wt') as f: f.write('\n'.join(comment) + '\n') line = '%10i'*4 % (nn, iconst, ivar, ivers) + '\n' f.write(line) for i, val in enumerate(glob): f.write(ff(val)) if i % 5 == 4: f.write('\n') if i % 5 != 4: f.write('\n') for row in var: for i, val in enumerate(row): f.write(ff(val)) if i % 5 == 4: f.write('\n') if i % 5 != 4: f.write('\n') def fgong_get(key_or_keys, glob, var, reverse=False, G=G_DEFAULT): """Retrieves physical properties of a FGONG model from the ``glob`` and ``var`` arrays. This function will be dropped from v0.1.0 in favour of the attributes of the :py:class:`FGONG` object. Parameters ---------- key_or_keys: str or list of strs The desired variable or a list of desired variables. Current options are: - ``M``: total mass (float) - ``R``: photospheric radius (float) - ``L``: total luminosity (float) - ``r``: radius (array) - ``x``: fractional radius (array) - ``m``: mass co-ordinate (array) - ``q``: fractional mass co-ordinate (array) - ``g``: gravity (array) - ``rho``: density (array) - ``P``: pressure (array) - ``AA``: Ledoux discriminant (array) - ``Hp``: pressure scale height (array) - ``Hrho``: density scale height (array) - ``G1``: first adiabatic index (array) - ``T``: temperature (array) - ``X``: hydrogen abundance (array) - ``L_r``: luminosity at radius ``r`` (array) - ``kappa``: opacity (array) - ``epsilon``: specific energy generation rate (array) - ``cp``: specific heat capacity (array) - ``cs2``: sound speed squared (array) - ``cs``: sound speed (array) - ``tau``: acoustic depth (array) For example, if ``glob`` and ``var`` have been returned from :py:meth:`~tomso.fgong.load_fgong`, you could use >>> M, m = fgong.fgong_get(['M', 'm'], glob, var) to get the total mass and mass co-ordinate. If you only want one variable, you don't need to use a list. The return type is just the one corresponding float or array. So, to get a single variable you could use either >>> x, = fgong.fgong_get(['x'], glob, var) or >>> x = fgong.fgong_get('x', glob, var) glob: NumPy array The scalar (or global) variables for the stellar model var: NumPy array The point-wise variables for the stellar model. i.e. things that vary through the star like temperature, density, etc. reverse: bool (optional) If ``True``, reverse the arrays so that the first element is the centre. G: float (optional) Value of the gravitational constant. Returns ------- output: list of floats and arrays A list returning the floats or arrays in the order requested by the parameter ``keys``. """ M, R, L = glob[:3] r, lnq, T, P, rho, X, L_r, kappa, epsilon, G1 = var[:,:10].T cp = var[:,12] AA = var[:,14] x = r/R q = np.exp(lnq) m = q*M g = G*m/r**2 Hp = P/(rho*g) Hrho = 1/(1/G1/Hp + AA/r) cs2 = G1*P/rho # square of the sound speed cs = np.sqrt(cs2) if np.all(np.diff(x) < 0): tau = -integrate(1./cs, r) # acoustic depth else: tau = integrate(1./cs[::-1], r[::-1])[::-1] tau = np.max(tau)-tau if type(key_or_keys) == str: keys = [key_or_keys] just_one = True else: keys = key_or_keys just_one = False I = np.arange(len(var), dtype=int) if reverse: I = I[::-1] output = [] for key in keys: if key == 'M': output.append(M) elif key == 'R': output.append(R) elif key == 'L': output.append(L) elif key == 'r': output.append(r[I]) elif key == 'x': output.append(x[I]) elif key == 'm': output.append(m[I]) elif key == 'q': output.append(q[I]) elif key == 'g': output.append(g[I]) elif key == 'rho': output.append(rho[I]) elif key == 'P': output.append(P[I]) elif key == 'AA': output.append(AA[I]) elif key == 'Hp': output.append(Hp[I]) elif key == 'Hrho': output.append(Hrho[I]) elif key == 'G1': output.append(G1[I]) elif key == 'T': output.append(T[I]) elif key == 'X': output.append(X[I]) elif key == 'L_r': output.append(L_r[I]) elif key == 'kappa': output.append(kappa[I]) elif key == 'epsilon': output.append(epsilon[I]) elif key == 'cp': output.append(cp[I]) elif key == 'cs2': output.append(cs2[I]) elif key == 'cs': output.append(cs[I]) elif key == 'tau': output.append(tau[I]) else: raise ValueError('%s is not a valid key for fgong.fgong_get' % key) if just_one: assert(len(output) == 1) return output[0] else: return output class FGONG(FullStellarModel): """A class that contains and allows one to manipulate the data in a stellar model stored in the `FGONG format`_. .. _FGONG format: https://www.astro.up.pt/corot/ntools/docs/CoRoT_ESTA_Files.pdf The main attributes are the **glob** and **var** arrays, which follow the definitions in the FGONG standard. The data in these arrays can be accessed via the attributes with more physically-meaningful names (e.g. the radius is ``FGONG.r``). Some of these values can also be set via the attributes if doing so is unambiguous. For example, the fractional radius **x** is not a member of the **var** array but setting **x** will assign the actual radius **r**, which is the first column of **var**. Values that are settable are indicated in the list of parameters. Parameters ---------- glob: NumPy array The global variables for the stellar model. var: NumPy array The point-wise variables for the stellar model. i.e. things that vary through the star like temperature, density, etc. ivers: int, optional The integer indicating the version number of the file. (default=0) G: float, optional Value for the gravitational constant. If not given (which is the default behaviour), we use ``glob[14]`` if it exists and is close to the module-wide default value. Otherwise, we use the module-wide default value. description: list of 4 strs, optional The first four lines of the FGONG file, which usually contain notes about the stellar model. Attributes ---------- iconst: int number of global data entries (i.e. length of **glob**) nn: int number of points in stellar model (i.e. number of rows in **var**) ivar: int number of variables recorded at each point in stellar model (i.e. number of columns in **var**) M: float, settable total mass R: float, settable photospheric radius L: float, settable total luminosity Teff: float effective temperature, derived from luminosity and radius r: NumPy array, settable radius co-ordinate lnq: NumPy array, settable natural logarithm of the fractional mass co-ordinate T: NumPy array, settable temperature P: NumPy array, settable pressure rho: NumPy array, settable density X: NumPy array, settable fractional hydrogen abundance (by mass) L_r: NumPy array, settable luminosity at radius **r** kappa: NumPy array, settable Rosseland mean opacity epsilon: NumPy array, settable specific energy generation rate Gamma_1: NumPy array, settable first adiabatic index, aliased by **G1** G1: NumPy array, settable first adiabatic index, alias of **Gamma_1** cp: NumPy array, settable specific heat capacity AA: NumPy array, settable Ledoux discriminant Z: NumPy array, settable metal abundance x: NumPy array, settable fractional radius co-ordinate q: NumPy array, settable fractional mass co-ordinate m: NumPy array, settable mass co-ordinate g: NumPy array local gravitational acceleration Hp: NumPy array pressure scale height Hrho: NumPy array density scale height N2: NumPy array squared Brunt–Väisälä (angular) frequency cs2: NumPy array squared adiabatic sound speed cs: NumPy array adiabatic sound speed U: NumPy array homology invariant *dlnm/dlnr* V: NumPy array homology invariant *dlnP/dlnr* Vg: NumPy array homology invariant *V/Gamma_1* tau: NumPy array acoustic depth """ def __init__(self, glob, var, ivers=300, G=None, description=['', '', '', '']): self.ivers = ivers self.glob = glob self.var = var self.description = description # if G is None, use glob[14] if it exists and looks like a # reasonable value of G if G is None: if len(glob) >= 14 and np.isclose(glob[14], G_DEFAULT, rtol=1e-3, atol=0.01e-8): self.G = glob[14] else: self.G = G_DEFAULT else: self.G = G def __len__(self): return len(self.var) def __repr__(self): with np.printoptions(threshold=10): return('FGONG(\nglob=\n%s,\nvar=\n%s,\ndescription=\n%s)' % (self.glob, self.var, '\n'.join(self.description))) def to_file(self, filename, float_formatter='ivers'): """Save the model to an FGONG file. Parameters ---------- filename: str Filename to which the data is written. float_formatter: str or function Determines how floating point numbers are formatted. If ``'ivers'`` (the default), use the standard formats ``%16.9E`` if ``ivers < 1000`` or ``%26.18E3`` if ``ivers >= 1000``. If a Python format specifier (e.g. ``'%16.9E'``), pass floats into that like ``float_formatter % float``. Otherwise, must be a function that takes a float as an argument and returns a string. In most circumstances you'll want to control the output by changing the value of ``'ivers'``. """ save_fgong(filename, self.glob, self.var, ivers=self.ivers, comment=self.description, float_formatter=float_formatter) def to_amdl(self): """Convert the model to an ``ADIPLSStellarModel`` object.""" from .adipls import ADIPLSStellarModel return ADIPLSStellarModel( *fgong_to_amdl(self.glob, self.var, G=self.G), G=self.G) def to_gyre(self, version=None): """Convert the model to a ``GYREStellarModel`` object. Parameters ---------- version: int, optional Specify GYRE format version number times 100. i.e., ``version=101`` produce a file with data version 1.01. If ``None`` (the default), the latest version available in TOMSO is used. """ from .gyre import gyre_header_dtypes, gyre_data_dtypes, GYREStellarModel if version is None: version = max([k for k in gyre_header_dtypes.keys()]) header = np.zeros(1, gyre_header_dtypes[version]) header['M'] = self.glob[0] header['R'] = self.glob[1] header['L'] = self.glob[2] if version > 1: header['version'] = version data = np.zeros(self.nn, gyre_data_dtypes[version]) # data['r'] = self.var[:,0] # data['T'] = self.var[:,2] # data['P'] = self.var[:,3] # data['rho'] = self.var[:,4] # if np.all(np.diff(data['r']) <= 0): # return GYREStellarModel(header, data[::-1], G=self.G) # else: # return GYREStellarModel(header, data, G=self.G) g = GYREStellarModel(header[0], data, G=self.G) g.r = self.r g.m = self.m g.T = self.T g.P = self.P g.rho = self.rho g.Gamma_1 = self.Gamma_1 g.N2 = self.N2 g.kappa = self.kappa g.L_r = self.L_r g.data['nabla_ad'] = self.var[:,10] g.data['delta'] = self.var[:,11] # The definitions of epsilon in FGONG and GYRE formats might # be different. Compute non-adiabatic modes at your peril! if version < 101: g.data['eps_tot'] = self.epsilon else: g.data['eps'] = self.epsilon if np.all(np.diff(g.r) <= 0): g.data = g.data[::-1] g.data['k'] = np.arange(self.nn) + 1 return g # FGONG parameters that can be derived from data @property def iconst(self): return len(self.glob) @property def nn(self): return self.var.shape[0] @property def ivar(self): return self.var.shape[1] # Various properties for easier access to the data in `glob` and # `var`. @property def M(self): return self.glob[0] @M.setter def M(self, val): self.glob[0] = val @property def R(self): return self.glob[1] @R.setter def R(self, val): self.glob[1] = val @property def L(self): return self.glob[2] @L.setter def L(self, val): self.glob[2] = val @property def r(self): return self.var[:,0] @r.setter def r(self, val): self.var[:,0] = val self.var[:,17] = self.R-val @property def lnq(self): return self.var[:,1] @lnq.setter def lnq(self, val): self.var[:,1] = val @property def T(self): return self.var[:,2] @T.setter def T(self, val): self.var[:,2] = val @property def P(self): return self.var[:,3] @P.setter def P(self, val): self.var[:,3] = val @property def rho(self): return self.var[:,4] @rho.setter def rho(self, val): self.var[:,4] = val @property def X(self): return self.var[:,5] @X.setter def X(self, val): self.var[:,5] = val @property def L_r(self): return self.var[:,6] @L_r.setter def L_r(self, val): self.var[:,6] = val @property def kappa(self): return self.var[:,7] @kappa.setter def kappa(self): self.var[:,7] = val @property def epsilon(self): return self.var[:,8] @epsilon.setter def epsilon(self, val): self.var[:,8] = val @property def Gamma_1(self): return self.var[:,9] @Gamma_1.setter def Gamma_1(self, val): self.var[:,9] = val @property def G1(self): return self.var[:,9] @G1.setter def G1(self, val): self.var[:,9] = val @property def grad_a(self): return self.var[:,10] @grad_a.setter def grad_a(self, val): self.var[:,10] = val @property def cp(self): return self.var[:,12] @cp.setter def cp(self, val): self.var[:,12] = val @property def AA(self): return self.var[:,14] @AA.setter def AA(self, val): self.var[:,14] = val @property def Z(self): return self.var[:,16] @Z.setter def Z(self, val): self.var[:,16] = val # Some convenient quantities derived from `glob` and `var`. @property def x(self): return self.r/self.R @x.setter def x(self, val): self.r = val*self.R @property def q(self): return np.exp(self.lnq) @q.setter def q(self, val): self.lnq = np.log(val) @property def m(self): return self.q*self.M @m.setter def m(self, val): self.q = val/self.M @property @regularize() def N2(self): return self.AA*self.g/self.r @property @regularize(y0=3) def U(self): return 4.*np.pi*self.rho*self.r**3/self.m @property @regularize() def V(self): return self.G*self.m*self.rho/self.P/self.r @property def Vg(self): return self.V/self.Gamma_1 @property def tau(self): if np.all(np.diff(self.x) < 0): return -integrate(1./self.cs, self.r) else: tau = integrate(1./self.cs[::-1], self.r[::-1])[::-1] return np.max(tau)-tau # - ``G1``: first adiabatic index (array)
warrickball/tomso
tomso/fgong.py
Python
mit
22,737
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.mod.mixin.core.world; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.util.BlockPos; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.storage.WorldInfo; import net.minecraftforge.common.util.BlockSnapshot; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import java.util.ArrayList; @Mixin(value = net.minecraft.world.World.class, priority = 1001) public abstract class MixinWorld implements org.spongepowered.api.world.World { @Shadow public WorldInfo worldInfo; private long weatherStartTime; private Block tempBlock; private BlockSnapshot tempSnapshot; @Inject(method = "updateWeatherBody()V", remap = false, at = { @At(value = "INVOKE", target = "Lnet/minecraft/world/storage/WorldInfo;setThundering(Z)V"), @At(value = "INVOKE", target = "Lnet/minecraft/world/storage/WorldInfo;setRaining(Z)V") }) private void onUpdateWeatherBody(CallbackInfo ci) { this.weatherStartTime = this.worldInfo.getWorldTotalTime(); } @Inject(method = "setBlockState", at = @At(value = "INVOKE", target = "Ljava/util/ArrayList;add(Ljava/lang/Object;)Z", remap = false, ordinal = 0), locals = LocalCapture.CAPTURE_FAILEXCEPTION) public void onSetBlockState(BlockPos pos, IBlockState newState, int flags, CallbackInfoReturnable<Boolean> cir, Chunk chunk, Block block, BlockSnapshot blockSnapshot) { this.tempBlock = block; this.tempSnapshot = blockSnapshot; } @SuppressWarnings({"rawtypes", "unchecked"}) @Redirect(method = "setBlockState", at = @At(value = "INVOKE", target = "Ljava/util/ArrayList;add(Ljava/lang/Object;)Z", remap = false)) public boolean onAddSnapshot(ArrayList list, Object snapshot) { // Only capture if existing block was replaced by different block type if (tempSnapshot.getReplacedBlock().getBlock() != tempBlock) { return list.add(snapshot); } else { // ignore block state changes for replaced blocks tempSnapshot = null; } return false; } @Override public long getRunningDuration() { return this.worldInfo.getWorldTotalTime() - this.weatherStartTime; } }
joseph00713/Sponge
src/main/java/org/spongepowered/mod/mixin/core/world/MixinWorld.java
Java
mit
3,950
namespace Tharga.Toolkit.Console.Entities { public class Position { public int Left { get; } public int Top { get; } public int? Width { get; } public int? Height { get; } public int? BufferWidth { get; } public int? BufferHeight { get; } public Position(int left, int top, int? width = null, int? height = null, int? bufferWidth = null, int? bufferHeight = null) { Left = left; Top = top; Width = width; Height = height; BufferWidth = bufferWidth; BufferHeight = bufferHeight; } } }
poxet/tharga-console
Tharga.Toolkit.Console/Entities/Position.cs
C#
mit
640
"""Automatically format references in a LaTeX file.""" import argparse from multiprocessing import Pool from reference_utils import Reference, extract_bibtex_items from latex_utils import read_latex_file, write_latex_file class ReferenceFormatter: def __init__(self, add_arxiv): self.add_arxiv = add_arxiv def get_reference(self, bibtex_entry): """Wrapper for multithreading.""" reference = Reference(bibtex_entry.rstrip(), self.add_arxiv) reference.main() return reference.bibitem_data, reference.bibitem_identifier, reference.reformatted_original_reference, reference.formatted_reference def format_references(self, latex_source): """Format all references in the given LaTeX source.""" bibtex_entries = extract_bibtex_items(latex_source) # Parallelising the reference lookup gives a 15x speedup. # Values larger than 15 for the poolsize do not give a further speedup. with Pool(15) as pool: res = pool.map(self.get_reference, bibtex_entries) for r in res: bibitem_data, bibitem_identifier, reformatted_original_reference, formatted_reference = r latex_source = latex_source.replace(bibitem_data, f"\\bibitem{{{bibitem_identifier}}} \\textcolor{{red}}{{TODO}}\n{reformatted_original_reference}\n\n%{formatted_reference}\n\n\n") return latex_source if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('latex_file') parser.add_argument('--add_arxiv', action="store_true") args = parser.parse_args() latex_source = read_latex_file(args.latex_file) print("Processing references...") reference_formatter = ReferenceFormatter(args.add_arxiv) latex_source = reference_formatter.format_references(latex_source) write_latex_file(args.latex_file, latex_source)
teunzwart/latex-production-tools
reference_formatter.py
Python
mit
1,870
<!-- SECTION Judul--> <!--===============================================================--> <div class="section-heading-page"> <div class="container"> <div class="row"> <div class="col-sm-6"> <h1 class="heading-page text-center-xs">Dashboard</h1> </div> <div class="col-sm-6"> <ol class="breadcrumb text-right text-center-xs"> <li> <a href="#">Home</a> </li> <li class="active">Dashboard</li> </ol> </div> </div> </div> </div> <!-- SECTION KONTEN --> <div class="container"> <div class="row"> <!-- SIDE NAV --> <!--===============================================================--> <?php $this->load->view('front/template/menu_member'); ?> <!-- END SIDE NAV --> <!-- CONTENT COLUMN --> <!--===============================================================--> <div class="col-md-9"> <div class="row"> <div class="col-md-12"> <h3 class="title-v2">Transaksi anda</h3> </div> </div> <div class="row"> <div class="col-md-12"> <?php if ($this->session->flashdata('msg_success')): ?> <!-- alert jika sukses simpan --> <div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <?php echo $this->session->flashdata('msg_success'); ?> </div> <?php endif ?> <?php if ($this->session->flashdata('msg_error_upload')): ?> <!-- alert jika ada error ketika upload --> <div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> <?php echo $this->session->flashdata('msg_error_upload'); ?> </div> <?php endif ?> <!-- alert jika ada form error --> <?php echo validation_errors('<div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>','</div>'); ?> </div> </div> <div class="row"> <div class="col-md-12"> <?php foreach ($arr_transaksi as $transaksi): ?> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">Informasi Pemesanan</h3> </div> <div class="panel-body"> <div class="row"> <div class="col-md-6"> <h3 class="text-theme title-sm hr-before">Tanggal Pesan</h3> <p class="text-theme"> <?php $date = new DateTime($transaksi->tgl_pesan); echo $date->format('d F Y H:i'); ?> </p> <h3 class="text-theme title-md hr-left">Biaya</h3> <table class="table table-bordered"> <thead> <tr> <th>No</th> <th>Deskripsi</th> <th>Harga</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Total</td> <td><h3 class="text-right text-theme title-md">Rp <?php echo number_format($total['sub_total'],2,'.',','); ?></h3></td> </tr> <tr> <td colspan="2" class="btn-sea text-right">Sub Total</td> <td class="btn-sea"><h3 class=" text-right text-theme title-md"> Rp <?php echo number_format($total['sub_total'],2,'.',','); ?> </h3></td> </tr> <tr> <td>2</td> <td>Ongkir</td> <td><h3 class="text-right text-theme title-md"> Rp <?php echo number_format($transaksi->tarif,2,'.',','); ?> </h3> </td> </tr> <tr> <td colspan="2" class="btn-green text-right">Total Bayar</td> <td class="btn-green"><h3 class=" text-right text-theme title-md">Rp <?php echo number_format($total['grand_total'],2,'.',','); ?></h3></td> </tr> </tbody> </table> </div> <div class="col-md-6"> <h3 class="text-theme title-sm hr-before">Status</h3> <p class="text-theme"> <?php if ($transaksi->status=='pending'): ?> <div class="label label-warning">Pending</div> <small><a href="<?php echo site_url('member/konfirmasi') ?>">Silahkan Konfirmasi</a></small> <?php elseif($transaksi->status=='terkonfirmasi'): ?> <div class="label label-info">Terkonfirmasi</div> <?php elseif($transaksi->status=='proses'): ?> <div class="label label-primary">Sedang Diproses</div> <?php elseif($transaksi->status=='kirim'): ?> <div class="label label-success">Dikirim</div> <?php endif ?> </p> <h3 class="text-theme title-sm hr-before">No Resi</h3> <p class="text-theme"> <?php if (empty($transaksi->no_resi)): ?> - <?php else: ?> <?php echo $transaksi->no_resi; ?> <?php endif ?> </p> <h3 class="text-theme title-sm hr-before">Dikirim ke</h3> <p class="text-theme"><?php echo $transaksi->alamat_kirim; ?></p> <h3 class="text-theme title-sm hr-before">Kota Tujuan</h3> <p class="text-theme"><?php echo $transaksi->nama_kota; ?></p> </div> </div> </div> </div> <?php endforeach ?> </div> </div> <div class="row"> <div class="col-md-12"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">Informasi barang yang dipesan</h3> </div> <div class="panel-body"> <div class="row"> <div class="col-md-12"> <table class="table table-bordered table-striped"> <thead> <tr> <th>#</th> <th>Kode</th> <th>Nama</th> <th>Jumlah</th> <th>Harga</th> <th>Total</th> </tr> </thead> <tbody> <?php $no=1; ?> <?php foreach ($arr_transaksi_detail as $transaksi_detail): ?> <tr> <td><?php echo $no;$no++; ?></td> <td>BRG<?php echo $transaksi_detail->id_barang; ?></td> <td><?php echo $transaksi_detail->nama_barang; ?></td> <td><?php echo $transaksi_detail->jumlah; ?></td> <td>Rp <?php echo number_format($transaksi_detail->harga,2,'.',','); ?></td> <td>Rp <?php echo number_format($transaksi_detail->sub_total,2,'.',','); ?></td> </tr> <?php endforeach ?> </tbody> </table> </div> </div> <hr class="hr-divider-ghost"> </div> </div> </div> </div> <hr class="hr-divider-ghost"> </div> </div> </div> <!-- END SECTION KONTEN --> <script type="text/javascript"> window.pilih_alamat = function() { if(document.getElementById("alamat_baru1").checked) { document.getElementById("input_alamat").readOnly = false; document.getElementById("input_alamat").value = ''; } else { document.getElementById("input_alamat").readOnly = true; document.getElementById("input_alamat").value = '<?php echo $alamat_user; ?>'; } } window.onload = pilih_alamat(); </script> <!-- modal konfirmasi hapus --> <div class="modal fade" id="deleteKeranjang" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="exampleModalLabel">Konfirmasi Hapus</h4> </div> <div class="modal-body"> Apa Anda yakin akan menghapus Pesanan ini ? </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Tutup</button> <a class="btn btn-primary">Hapus</a> </div> </div> </div> </div>
reeganaga/tokoonline
application/views/front/history/content_detail.php
PHP
mit
10,478
import sqlite3 import requests from random import sample import textwrap from printer import ThermalPrinter LINE_WIDTH = 32 potm = "http://creepypasta.wikia.com/api/v1/Articles/List?category=PotM&limit=1000" spotlighted = "http://creepypasta.wikia.com/api/v1/Articles/List?category=Spotlighted_Pastas&limit=1000" def get_json_from_url(url): return requests.get(url).json() def get_ids_from_article_list(data): return [item['id'] for item in data['items']] def get_ids_from_url(url): data = get_json_from_url(url) return get_ids_from_article_list(data) def get_id_list(): each = get_ids_from_url(potm) + get_ids_from_url(spotlighted) return each def get_newest_story(c, story_list): if len(story_list) == 0: return "NO STORIES FOUND" first = story_list[0] c.execute("INSERT INTO `visited` (`source`, `source_id`) VALUES (?, ?)", ('creepypasta.wikia.com', first)) story_data = get_json_from_url("http://creepypasta.wikia.com/api/v1/Articles/AsSimpleJson?id=%s" % first) return story_data def strip_printed_stories(c, story_list, source): existing_ids = [item[0] for item in c.execute("SELECT source_id FROM `visited` WHERE `source`='%s'" % source)] return [story for story in story_list if story not in existing_ids] def parse_list_item(item): return textwrap.fill("* %s" % item['text'], LINE_WIDTH) def parse_content_item(item): if item['type'] == 'paragraph': return textwrap.fill(item['text'], LINE_WIDTH) elif item['type'] == 'list': return "\n".join(parse_list_item(li) for li in item['elements']) return '' def parse_content_list(section): return "\n".join(parse_content_item(item) for item in section['content']) def parse_title(section): # CENTRE ME return "\n" + textwrap.fill(section['title'], LINE_WIDTH) def parse_section(section): return "\n".join([parse_title(section), parse_content_list(section)]) def parse_story(data): sections = [parse_section(section) for section in data['sections']] return "\n".join(sections) conn = sqlite3.connect('creepypasta.db') c = conn.cursor() ids = get_id_list() stripped = strip_printed_stories(c, ids, "creepypasta.wikia.com") shuffled = sample(ids, len(ids)) newest = get_newest_story(c, shuffled) lines = parse_story(newest).encode('ascii', 'replace') printer = ThermalPrinter() for line in lines.split("\n"): printer.print_text("\n" + line) conn.commit() conn.close()
AngryLawyer/creepypasta-strainer
src_python/strainer.py
Python
mit
2,457
<?php class CM_WP_Exception_PluginNotRegisteredException extends Exception { /** * Plugin slug * * @var string */ protected $slug; /** * [__construct description] * * @param string $slug */ public function __construct( $slug ) { $this->slug = $slug; parent::__construct( sprintf( "Plugin with the slug '%s' has not been registered yet", $this->slug ) ); } }
cubicmushroom/wordpress-helper
src/CM/WP/Exception/PluginNotRegisteredException.php
PHP
mit
504
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("01.Money")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("01.Money")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("440019dd-1371-4262-ab79-93b0b6be4cc1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Steffkn/SoftUni
01.ProgrammingBasicsC#/Exams/17July2016/01.Money/Properties/AssemblyInfo.cs
C#
mit
1,387
import { NgModule } from '@angular/core'; import { ToolbarModule } from 'primeng/primeng'; import { PageToolbarComponent } from './page-toolbar.component'; @NgModule({ exports: [PageToolbarComponent], declarations: [PageToolbarComponent], imports: [ ToolbarModule ] }) export class PageToolbarModule { }
dreamer99x/ceb
src/app/shared/components/page-toolbar/index.ts
TypeScript
mit
321
class ParseException < Exception end
ably-forks/cloudyscripts
lib/audit/lib/parser/parse_exception.rb
Ruby
mit
36
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== import show_and_tell_model from inference_utils import inference_wrapper_base class InferenceWrapper(inference_wrapper_base.InferenceWrapperBase): """Model wrapper class for performing inference with a ShowAndTellModel.""" def __init__(self): super(InferenceWrapper, self).__init__() def build_model(self, model_config): model = show_and_tell_model.ShowAndTellModel(model_config, mode="inference") model.build() return model def feed_image(self, sess, encoded_image): initial_state = sess.run(fetches="lstm/initial_state:0", feed_dict={"image_feed:0": encoded_image}) return initial_state def inference_step(self, sess, input_feed, state_feed): softmax_output, state_output = sess.run( fetches=["softmax:0", "lstm/state:0"], feed_dict={ "input_feed:0": input_feed, "lstm/state_feed:0": state_feed, }) return softmax_output, state_output, None
hkhpub/show_and_tell_korean
webdemo/webdemo/inference_wrapper.py
Python
mit
1,658
#include <cstdlib> #include <stack> #include <vector> using namespace std; #include "binary_tree_inorder_traversal.h" #include "../util/util_tree.h" vector<int> BinaryTreeInorderTraversal::inorderTraversalRecursive(TreeNode *root) { vector<int> traversal_history; if (root == NULL) return traversal_history; // Traverse the left sub-tree. vector<int> left_traversal_history = inorderTraversalRecursive(root->left); traversal_history.insert(traversal_history.end(), left_traversal_history.begin(), left_traversal_history.end()); // Visit the root node. traversal_history.push_back(root->val); // Traverse the right sub-tree. vector<int> right_traversal_history = inorderTraversalRecursive(root->right); traversal_history.insert(traversal_history.end(), right_traversal_history.begin(), right_traversal_history.end()); return traversal_history; } vector<int> BinaryTreeInorderTraversal::inorderTraversalIterative(TreeNode* root) { vector<int> traversal_history; if (root == NULL) return traversal_history; TreeNode *root_node = root; stack<TreeNode*> candidate_list; do { // If current sub-tree is empty, then popup LCA node, visit it, and update // next sub-tree to its right sub-tree. if (root_node == NULL) { root_node = candidate_list.top(); candidate_list.pop(); traversal_history.push_back(root_node->val); root_node = root_node->right; } // If current sub-tree is not empty, then push the root node, update next // sub-tree to its left sub-tree. if (root_node) { candidate_list.push(root_node); root_node = root_node->left; } } while (!candidate_list.empty()); return traversal_history; }
metacpp/LeetCpp
src/tree/binary_tree_inorder_traversal.cc
C++
mit
1,826
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> ERROR - 2015-11-08 00:53:15 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 02:46:43 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 02:47:31 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 03:10:36 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 03:16:58 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 03:27:38 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 04:24:55 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 05:00:06 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 05:27:49 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 05:28:38 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 05:37:42 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 06:05:11 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 06:05:21 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 06:34:01 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 07:14:20 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 08:45:39 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 09:04:40 --> 404 Page Not Found --> manager ERROR - 2015-11-08 09:33:08 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 09:33:10 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 09:37:13 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 09:41:28 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 10:08:47 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 11:01:06 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 11:01:30 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 11:02:02 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 11:58:34 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 12:03:29 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 13:53:24 --> 404 Page Not Found --> wp-admin ERROR - 2015-11-08 13:53:25 --> 404 Page Not Found --> wp-admin ERROR - 2015-11-08 13:53:25 --> 404 Page Not Found --> wp-admin ERROR - 2015-11-08 13:53:26 --> 404 Page Not Found --> wp-admin ERROR - 2015-11-08 13:53:27 --> 404 Page Not Found --> wp-admin ERROR - 2015-11-08 13:53:27 --> 404 Page Not Found --> wp-admin ERROR - 2015-11-08 18:01:12 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 19:17:50 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 19:18:14 --> 404 Page Not Found --> robots.txt ERROR - 2015-11-08 22:31:45 --> 404 Page Not Found --> robots.txt
cmorenokkatoo/kkatooapp
application/logs/log-2015-11-08.php
PHP
mit
2,507
#include <iostream> #include <stdlib.h> int main() { // int a = 1; // int *b = &a; int *b = (int *) malloc(sizeof(int)); *b = 5; int *c = b; int *d = c; free (d); // *b = 7; std::cout << *b << std::endl; }
lindsayad/programming
cpp/lots_of_pointers.cpp
C++
mit
225
package no.notanumber.sosql; import java.util.Objects; public class Join { public final DatabaseColumn primary; public final DatabaseColumn foreign; public Join(DatabaseColumn primary, DatabaseColumn foreign) { this.primary = primary; this.foreign = foreign; } @Override public boolean equals(Object obj) { if (obj == null) return false; if (!(obj instanceof Join)) return false; Join other = (Join) obj; return Objects.equals(primary, other.primary) && Objects.equals(foreign, other.foreign); } @Override public int hashCode() { return Objects.hash(primary, foreign); } @Override public String toString() { return primary.columnName + " = " + foreign.columnName; } }
NotANumber-no/sosql
src/main/java/no/notanumber/sosql/Join.java
Java
mit
803
package com.bitdubai.fermat_dmp_plugin.layer.world.crypto_index.developer.bitdubai; import com.bitdubai.fermat_api.Plugin; import com.bitdubai.fermat_api.PluginDeveloper; import com.bitdubai.fermat_api.layer.all_definition.enums.CryptoCurrency; import com.bitdubai.fermat_api.layer.all_definition.enums.TimeFrequency; import com.bitdubai.fermat_api.layer.all_definition.license.PluginLicensor; import com.bitdubai.fermat_dmp_plugin.layer.world.crypto_index.developer.bitdubai.version_1.CryptoIndexWorldPluginRoot; /** * Created by loui on 12/02/15. */ public class DeveloperBitDubai implements PluginDeveloper, PluginLicensor { Plugin plugin; @Override public Plugin getPlugin() { return plugin; } public DeveloperBitDubai () { /** * I will choose from the different versions of my implementations which one to start. Now there is only one, so * it is easy to choose. */ plugin = new CryptoIndexWorldPluginRoot(); } @Override public int getAmountToPay() { return 100; } @Override public CryptoCurrency getCryptoCurrency() { return CryptoCurrency.BITCOIN; } @Override public String getAddress() { return "13gpMizSNvQCbJzAPyGCUnfUGqFD8ryzcv"; } @Override public TimeFrequency getTimePeriod() { return TimeFrequency.MONTHLY; } }
fvasquezjatar/fermat-unused
DMP/plugin/world/fermat-dmp-plugin-world-crypto-index-bitdubai/src/main/java/com/bitdubai/fermat_dmp_plugin/layer/world/crypto_index/developer/bitdubai/DeveloperBitDubai.java
Java
mit
1,395
'use strict'; /** * @ngdoc directive * @name myDashingApp.directive:widgetText * @description * # widgetText */ angular.module('myDashingApp') .directive('widgetText', function () { return { template: '<div><div class="title">{{data.title}}</div><div class="value">{{data.value}}</div><div updated-at="data.updatedAt"></div></div>', restrict: 'A', scope:{ 'data': '=widgetText' } }; });
GuyMograbi/ng-dashing
app/scripts/directives/widgettext.js
JavaScript
mit
482
<?php /* SMASMABundle:Public:about2.html.twig */ class __TwigTemplate_95bc6be8200ffe9eef6c99c778e963bf4ee22d5d533dcb62c75dbe15624dff5e extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = $this->env->loadTemplate("SMASMABundle:Public:templatedetail2.html.twig"); $this->blocks = array( 'body' => array($this, 'block_body'), ); } protected function doGetParent(array $context) { return "SMASMABundle:Public:templatedetail2.html.twig"; } protected function doDisplay(array $context, array $blocks = array()) { $this->parent->display($context, array_merge($this->blocks, $blocks)); } // line 3 public function block_body($context, array $blocks = array()) { // line 4 echo " <h2>Tentang Kami</h2> <p> SMA Negeri (SMAN) 11 Medan, merupakan salah satu Sekolah Menengah Atas Negeri yang ada di Provinsi Sumatera Utara, Indonesia. Sama dengan SMA pada umumnya di Indonesia masa pendidikan sekolah di SMAN 11 Medan ditempuh dalam waktu tiga tahun pelajaran, mulai dari Kelas X sampai Kelas XII. Pada tahun 2007, sekolah ini menggunakan Kurikulum Tingkat Satuan Pendidikan sebelumnya dengan KBK. <dl class=\"dl-horizontal\"> <dt>Akreditasi :<dt> <dd> Nilai Akreditasi : 82</dd> <dd>Peringkat Akreditasi : B</dd> <dd>Tanggal Penetapan : 05-Oct-2009.</dd> <dt>Fasilitas</dt> <dd>Kelas</dd> <dd>Perpustakaan</dd> <dd>Laboratorium Biologi</dd> <dd>Laboratorium Fisika</dd> <dd>Laboratorium Kimia</dd> <dd>Laboratorium Komputer</dd> <dd>Laboratorium Bahasa.</dd> <dt>ekstrakurikuler</dt> <dd>PASSDAN</dd> <dd>BSC (Bio Sains Community)</dd> <dd>BKM</dd> <dd>PA</dd> <dd>IT Community</dd> <dd>LNC (Eleven English Club)</dd> <dd>PRAMUKA</dd> <dd>FAMOUS-T.</dd> </dl> </p> <p> <dl class=\"dl-horizontal\"> <dt>Alamat :</dt> <dd>Jl. Pertiwi No.93 Medan Tembung (20236)</dd> <dt>Email :</dt> <dd>sman11medan81@yahoo.com</dd> <dt>Telpon :</dt> <dd>(061) 7382448</dd> <dt>NSS :</dt> <dd>301076009010</dd> <dt>NPSN :</dt> <dd>10210875</dd> </dl> </p> "; } public function getTemplateName() { return "SMASMABundle:Public:about2.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 31 => 4, 28 => 3,); } }
matsuyuki/smanegeri11
app/cache/dev/twig/95/bc/6be8200ffe9eef6c99c778e963bf4ee22d5d533dcb62c75dbe15624dff5e.php
PHP
mit
2,653
window.dev1(1);
delambo/gettit
test/assets/dev1/js/test2.js
JavaScript
mit
16
/* * The MIT License * * Copyright 2014 Kamnev Georgiy (nt.gocha@gmail.com). * * Данная лицензия разрешает, безвозмездно, лицам, получившим копию данного программного * обеспечения и сопутствующей документации (в дальнейшем именуемыми "Программное Обеспечение"), * использовать Программное Обеспечение без ограничений, включая неограниченное право на * использование, копирование, изменение, объединение, публикацию, распространение, сублицензирование * и/или продажу копий Программного Обеспечения, также как и лицам, которым предоставляется * данное Программное Обеспечение, при соблюдении следующих условий: * * Вышеупомянутый копирайт и данные условия должны быть включены во все копии * или значимые части данного Программного Обеспечения. * * ДАННОЕ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ «КАК ЕСТЬ», БЕЗ ЛЮБОГО ВИДА ГАРАНТИЙ, * ЯВНО ВЫРАЖЕННЫХ ИЛИ ПОДРАЗУМЕВАЕМЫХ, ВКЛЮЧАЯ, НО НЕ ОГРАНИЧИВАЯСЬ ГАРАНТИЯМИ ТОВАРНОЙ ПРИГОДНОСТИ, * СООТВЕТСТВИЯ ПО ЕГО КОНКРЕТНОМУ НАЗНАЧЕНИЮ И НЕНАРУШЕНИЯ ПРАВ. НИ В КАКОМ СЛУЧАЕ АВТОРЫ * ИЛИ ПРАВООБЛАДАТЕЛИ НЕ НЕСУТ ОТВЕТСТВЕННОСТИ ПО ИСКАМ О ВОЗМЕЩЕНИИ УЩЕРБА, УБЫТКОВ * ИЛИ ДРУГИХ ТРЕБОВАНИЙ ПО ДЕЙСТВУЮЩИМ КОНТРАКТАМ, ДЕЛИКТАМ ИЛИ ИНОМУ, ВОЗНИКШИМ ИЗ, ИМЕЮЩИМ * ПРИЧИНОЙ ИЛИ СВЯЗАННЫМ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ ИЛИ ИСПОЛЬЗОВАНИЕМ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ * ИЛИ ИНЫМИ ДЕЙСТВИЯМИ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ. */ package xyz.cofe.lang2.parser; import java.io.OutputStreamWriter; import java.lang.reflect.Array; import xyz.cofe.lang2.vm.Value; import xyz.cofe.lang2.vm.op.AbstractTreeNode; import xyz.cofe.collection.iterators.TreeWalk; import xyz.cofe.text.IndentStackWriter; import xyz.cofe.types.TypesUtil; import xyz.cofe.types.ValueController; /** * Класс отображение дерева * @author gocha */ public class SyntaxTreeDump { public void printTree(Value code){ IndentStackWriter w = new IndentStackWriter(new OutputStreamWriter(System.out)); printTree(w, code); } protected String getClassNameOf(Value v){ String cls = v.getClass().getName(); return cls; } protected boolean isShowAttribute(Value value,String attribute){ return true; } protected void printHeader(IndentStackWriter log){ } public void printTree(IndentStackWriter log, Value codeV){ printHeader(log); for( TreeWalk<Value> tw : AbstractTreeNode.tree(codeV) ){ int level = tw.currentLevel(); if( level>=0 )log.level(level); Value v = tw.currentNode(); if( v==null ){ log.println( "node is null" ); continue; } int idx = v.getIndex(); String cls = getClassNameOf( v ); log.template("{0}. {1}", idx, cls); log.println(); Iterable<ValueController> props = TypesUtil.Iterators.propertiesOf(v); log.incLevel(); for( ValueController vc : props ){ String attr = vc.getName(); // if( attr.equals("parent") )continue; if( !isShowAttribute(v, attr) )continue; try{ Object val = vc.getValue(); printAttribute( log, attr, val ); }catch( Throwable ex ){ log.template("Exception ! {0}", ex.getMessage()); log.println(); } } } log.level(0); log.flush(); } public void printAttribute( IndentStackWriter log, String attr, Object value ){ if( value!=null ){ Class cval = value.getClass(); if( cval.isArray() ){ log.template("{0} = ", attr); printArray(log, cval, value); }else{ log.template("{0} = ", attr); printValue(log, value); } log.println(); }else{ log.template("{0} is null", attr); log.println(); } } public void printValue( IndentStackWriter log, Object value ){ if( value==null ){ log.template("null"); }else{ Class c = value.getClass(); if( c.isArray() ){ printArray(log, c, value); }else{ log.template("{0}", value); } } } public void printArray( IndentStackWriter log, Class valueClass, Object value ){ int length = Array.getLength(value); log.print("{"); for( int idx = 0; idx<length; idx++ ){ if( idx>0 ){ log.print(", "); } Object item = Array.get(value, idx); printValue(log, item); } log.print("}"); } }
gochaorg/lang2
src/main/java/xyz/cofe/lang2/parser/SyntaxTreeDump.java
Java
mit
5,610
/* ** GENEREATED FILE - DO NOT MODIFY ** */ package com.wilutions.mslib.office; import com.wilutions.com.*; /** * MsoTextTabAlign. * */ @SuppressWarnings("all") @CoInterface(guid="{00000000-0000-0000-0000-000000000000}") public class MsoTextTabAlign implements ComEnum { static boolean __typelib__loaded = __TypeLib.load(); // Typed constants public final static MsoTextTabAlign msoTabAlignMixed = new MsoTextTabAlign(-2); public final static MsoTextTabAlign msoTabAlignLeft = new MsoTextTabAlign(0); public final static MsoTextTabAlign msoTabAlignCenter = new MsoTextTabAlign(1); public final static MsoTextTabAlign msoTabAlignRight = new MsoTextTabAlign(2); public final static MsoTextTabAlign msoTabAlignDecimal = new MsoTextTabAlign(3); // Integer constants for bitsets and switch statements public final static int _msoTabAlignMixed = -2; public final static int _msoTabAlignLeft = 0; public final static int _msoTabAlignCenter = 1; public final static int _msoTabAlignRight = 2; public final static int _msoTabAlignDecimal = 3; // Value, readonly field. public final int value; // Private constructor, use valueOf to create an instance. private MsoTextTabAlign(int value) { this.value = value; } // Return one of the predefined typed constants for the given value or create a new object. public static MsoTextTabAlign valueOf(int value) { switch(value) { case -2: return msoTabAlignMixed; case 0: return msoTabAlignLeft; case 1: return msoTabAlignCenter; case 2: return msoTabAlignRight; case 3: return msoTabAlignDecimal; default: return new MsoTextTabAlign(value); } } public String toString() { switch(value) { case -2: return "msoTabAlignMixed"; case 0: return "msoTabAlignLeft"; case 1: return "msoTabAlignCenter"; case 2: return "msoTabAlignRight"; case 3: return "msoTabAlignDecimal"; default: { StringBuilder sbuf = new StringBuilder(); sbuf.append("[").append(value).append("="); if ((value & -2) != 0) sbuf.append("|msoTabAlignMixed"); if ((value & 0) != 0) sbuf.append("|msoTabAlignLeft"); if ((value & 1) != 0) sbuf.append("|msoTabAlignCenter"); if ((value & 2) != 0) sbuf.append("|msoTabAlignRight"); if ((value & 3) != 0) sbuf.append("|msoTabAlignDecimal"); return sbuf.toString(); } } } }
wolfgangimig/joa
java/joa/src-gen/com/wilutions/mslib/office/MsoTextTabAlign.java
Java
mit
2,449
#include "optionsdialog.h" #include "ui_optionsdialog.h" #include "bitcoinunits.h" #include "monitoreddatamapper.h" #include "netbase.h" #include "optionsmodel.h" #include <QDir> #include <QIntValidator> #include <QLocale> #include <QMessageBox> OptionsDialog::OptionsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::OptionsDialog), model(0), mapper(0), fRestartWarningDisplayed_Proxy(false), fRestartWarningDisplayed_Lang(false), fProxyIpValid(true) { ui->setupUi(this); /* Network elements init */ #ifndef USE_UPNP ui->mapPortUpnp->setEnabled(false); #endif ui->proxyIp->setEnabled(false); ui->proxyPort->setEnabled(false); ui->proxyPort->setValidator(new QIntValidator(1, 65535, this)); ui->socksVersion->setEnabled(false); ui->socksVersion->addItem("5", 5); ui->socksVersion->addItem("4", 4); ui->socksVersion->setCurrentIndex(0); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy())); ui->proxyIp->installEventFilter(this); /* Window elements init */ #ifdef Q_OS_MAC /* remove Window tab on Mac */ ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWindow)); #endif /* Display elements init */ QDir translations(":translations"); ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant("")); foreach(const QString &langStr, translations.entryList()) { QLocale locale(langStr); /** check if the locale name consists of 2 parts (language_country) */ if(langStr.contains("_")) { #if QT_VERSION >= 0x040800 /** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } else { #if QT_VERSION >= 0x040800 /** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language (locale name)", e.g. "German (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } } ui->unit->setModel(new BitcoinUnits(this)); /* Widget-to-option mapper */ mapper = new MonitoredDataMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); mapper->setOrientation(Qt::Vertical); /* enable apply button when data modified */ connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApplyButton())); /* disable apply button when new data loaded */ connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApplyButton())); /* setup/change UI elements when proxy IP is invalid/valid */ connect(this, SIGNAL(proxyIpValid(QValidatedLineEdit *, bool)), this, SLOT(handleProxyIpValid(QValidatedLineEdit *, bool))); } OptionsDialog::~OptionsDialog() { delete ui; } void OptionsDialog::setModel(OptionsModel *model) { this->model = model; if(model) { connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); mapper->setModel(model); setMapper(); mapper->toFirst(); } /* update the display unit, to not use the default ("BTC") */ updateDisplayUnit(); /* warn only when language selection changes by user action (placed here so init via mapper doesn't trigger this) */ connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning_Lang())); /* disable apply button after settings are loaded as there is nothing to save */ disableApplyButton(); } void OptionsDialog::setMapper() { /* Main */ mapper->addMapping(ui->transactionFee, OptionsModel::Fee); mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup); /* Network */ mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP); mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse); mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP); mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort); mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion); /* Window */ #ifndef Q_OS_MAC mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray); mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose); #endif /* Display */ mapper->addMapping(ui->lang, OptionsModel::Language); mapper->addMapping(ui->unit, OptionsModel::DisplayUnit); mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses); } void OptionsDialog::enableApplyButton() { ui->applyButton->setEnabled(true); } void OptionsDialog::disableApplyButton() { ui->applyButton->setEnabled(false); } void OptionsDialog::enableSaveButtons() { /* prevent enabling of the save buttons when data modified, if there is an invalid proxy address present */ if(fProxyIpValid) setSaveButtonState(true); } void OptionsDialog::disableSaveButtons() { setSaveButtonState(false); } void OptionsDialog::setSaveButtonState(bool fState) { ui->applyButton->setEnabled(fState); ui->okButton->setEnabled(fState); } void OptionsDialog::on_resetButton_clicked() { if(model) { // confirmation dialog QMessageBox::StandardButton btnRetVal = QMessageBox::question(this, tr("Confirm options reset"), tr("Some settings may require a client restart to take effect.") + "<br><br>" + tr("Do you want to proceed?"), QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if(btnRetVal == QMessageBox::Cancel) return; disableApplyButton(); /* disable restart warning messages display */ fRestartWarningDisplayed_Lang = fRestartWarningDisplayed_Proxy = true; /* reset all options and save the default values (QSettings) */ model->Reset(); mapper->toFirst(); mapper->submit(); /* re-enable restart warning messages display */ fRestartWarningDisplayed_Lang = fRestartWarningDisplayed_Proxy = false; } } void OptionsDialog::on_okButton_clicked() { mapper->submit(); accept(); } void OptionsDialog::on_cancelButton_clicked() { reject(); } void OptionsDialog::on_applyButton_clicked() { mapper->submit(); disableApplyButton(); } void OptionsDialog::showRestartWarning_Proxy() { if(!fRestartWarningDisplayed_Proxy) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Maxcoin."), QMessageBox::Ok); fRestartWarningDisplayed_Proxy = true; } } void OptionsDialog::showRestartWarning_Lang() { if(!fRestartWarningDisplayed_Lang) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Maxcoin."), QMessageBox::Ok); fRestartWarningDisplayed_Lang = true; } } void OptionsDialog::updateDisplayUnit() { if(model) { /* Update transactionFee with the current unit */ ui->transactionFee->setDisplayUnit(model->getDisplayUnit()); } } void OptionsDialog::handleProxyIpValid(QValidatedLineEdit *object, bool fState) { // this is used in a check before re-enabling the save buttons fProxyIpValid = fState; if(fProxyIpValid) { enableSaveButtons(); ui->statusLabel->clear(); } else { disableSaveButtons(); object->setValid(fProxyIpValid); ui->statusLabel->setStyleSheet("QLabel { color: red; }"); ui->statusLabel->setText(tr("The supplied proxy address is invalid.")); } } bool OptionsDialog::eventFilter(QObject *object, QEvent *event) { if(event->type() == QEvent::FocusOut) { if(object == ui->proxyIp) { CService addr; /* Check proxyIp for a valid IPv4/IPv6 address and emit the proxyIpValid signal */ emit proxyIpValid(ui->proxyIp, LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr)); } } return QDialog::eventFilter(object, event); }
max-winderbaum/maxcoin
src/qt/optionsdialog.cpp
C++
mit
8,952
describe ApiGuardian::Helpers::Digits do let(:subject) do ApiGuardian::Helpers::Digits.new( auth_url, auth_header ) end let(:auth_url) { 'https://api.digits.com/v1/something.json' } let(:auth_header) { 'OAuth oauth_consumer_key="foo"' } it { should have_attr_reader(:auth_url) } it { should have_attr_reader(:auth_header) } describe 'methods' do describe '#validate' do it 'fails when oauth key is missing' do expect_any_instance_of(ApiGuardian::Configuration::Registration).to( receive(:digits_key).and_return('') ) result = subject.validate expect(result.succeeded).to eq false expect(result.error).to eq( 'Digits consumer key not set! Please add ' \ '"config.registration.digits_key" to the ApiGuardian initializer!' ) end it 'fails with invalid auth header' do expect_any_instance_of(ApiGuardian::Configuration::Registration).to( receive(:digits_key).twice.and_return('bar') ) result = subject.validate expect(result.succeeded).to eq false expect(result.error).to eq 'Digits consumer key does not match this request.' end context 'with invalid auth url' do let(:auth_url) { 'https://example.com/stuff.json' } it 'fails with invalid auth url' do expect_any_instance_of(ApiGuardian::Configuration::Registration).to( receive(:digits_key).twice.and_return('foo') ) result = subject.validate expect(result.succeeded).to eq false expect(result.error).to eq 'Auth url is for invalid domain. Must match "api.digits.com".' end end it 'succeeds if validations pass' do expect_any_instance_of(ApiGuardian::Configuration::Registration).to( receive(:digits_key).twice.and_return('foo') ) result = subject.validate expect(result.succeeded).to eq true expect(result.error).to eq '' end end describe '#authorize!' do it 'should authorize digits request' do stub_request(:get, auth_url).to_return(status: 200) expect(subject.authorize!).to be_a Net::HTTPResponse expect(WebMock).to have_requested(:get, auth_url). with(headers: { 'Authorization' => auth_header }).once end it 'fails when HTTP response is not 200' do stub_request(:get, auth_url).to_return(status: 400) expect { subject.authorize! }.to raise_error( ApiGuardian::Errors::IdentityAuthorizationFailed, 'Digits API responded with 400. Expected 200!' ) expect(WebMock).to have_requested(:get, auth_url). with(headers: { 'Authorization' => auth_header }).once end end end end
lookitsatravis/api_guardian
spec/lib/helpers/digits_spec.rb
Ruby
mit
2,828
<div class="box box-danger"> <div class="box-header with-border"> <h3 class="box-title">Ínteres por tipo de alimento</h3> <div class="box-tools pull-right"> <button class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button> <button class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button> </div> </div> <div class="box-body"> <canvas id="pieChart" style="height:250px"></canvas> </div> </div> <script> var pieChartCanvas = $("#pieChart").get(0).getContext("2d"); var pieChart = new Chart(pieChartCanvas); var PieData = [ { value: 700, color: "#f56954", highlight: "#f56954", label: "Pollo" }, { value: 500, color: "#00a65a", highlight: "#00a65a", label: "Pescado" }, { value: 400, color: "#20a40a", highlight: "#20a40a", label: "Pavo" }, { value: 600, color: "#33CCFF", highlight: "#33CCFF", label: "Solo bebidas" } ]; var pieOptions = { segmentShowStroke: true, segmentStrokeColor: "#fff", segmentStrokeWidth: 2, percentageInnerCutout: 50, animationSteps: 100, animationEasing: "easeOutBounce", animateRotate: true, animateScale: true, responsive: true, maintainAspectRatio: true, legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>" }; pieChart.Doughnut(PieData, pieOptions); </script>
adrianturnes/menorcagastronomic
resources/views/backend/partials/donutChart.blade.php
PHP
mit
1,877
var searchData= [ ['parseprocinfo',['ParseProcInfo',['../tinyoslib_8h.html#ab98738d69f4b198fbcad1a6f2e20a44d',1,'tinyoslib.c']]], ['pipe',['Pipe',['../group__syscalls.html#gab6355ce54e047c31538ed5ed9108b5b3',1,'Pipe(pipe_t *pipe):&#160;kernel_pipe.c'],['../group__syscalls.html#gab6355ce54e047c31538ed5ed9108b5b3',1,'Pipe(pipe_t *pipe):&#160;kernel_pipe.c']]] ];
TedPap/opsys
doc/html/search/functions_b.js
JavaScript
mit
367
var util = require('util') , StoreError = require('jsr-error') , CommandArgLength = StoreError.CommandArgLength , InvalidFloat = StoreError.InvalidFloat , Constants = require('jsr-constants') , AbstractCommand = require('jsr-exec').DatabaseCommand; /** * Handler for the ZADD command. */ function SortedSetAdd() { AbstractCommand.apply(this, arguments); } util.inherits(SortedSetAdd, AbstractCommand); /** * Validate the ZADD command. */ function validate(cmd, args, info) { AbstractCommand.prototype.validate.apply(this, arguments); var i , num; if((args.length - 1) % 2 !== 0) { throw new CommandArgLength(cmd); } for(i = 1;i < args.length;i += 2) { num = parseFloat('' + args[i]); if(isNaN(num)) { throw InvalidFloat; } args[i] = num; } } SortedSetAdd.prototype.validate = validate; module.exports = new SortedSetAdd(Constants.MAP.zadd);
freeformsystems/jsr-server
lib/command/database/zset/zadd.js
JavaScript
mit
907
var expect = require('expect.js'), _ = require('lodash'), RevisionGuard = require('../../lib/revisionGuard'), revGuardStore = require('../../lib/revisionGuardStore'); describe('revisionGuard', function () { var store; before(function (done) { revGuardStore.create(function (err, s) { store = s; done(); }) }); describe('creating a new guard', function () { it('it should not throw an error', function () { expect(function () { new RevisionGuard(store); }).not.to.throwError(); }); it('it should return a correct object', function () { var guard = new RevisionGuard(store); expect(guard.definition).to.be.an('object'); expect(guard.defineEvent).to.be.a('function'); expect(guard.onEventMissing).to.be.a('function'); }); describe('defining the event structure', function() { var guard; beforeEach(function () { guard = new RevisionGuard(store); }); describe('using the defaults', function () { it('it should apply the defaults', function() { var defaults = _.cloneDeep(guard.definition); guard.defineEvent({ payload: 'data', aggregate: 'aggName', context: 'ctx.Name', revision: 'rev', version: 'v.', meta: 'pass' }); expect(defaults.correlationId).to.eql(guard.definition.correlationId); expect(defaults.id).to.eql(guard.definition.id); expect(guard.definition.payload).to.eql('data'); expect(defaults.payload).not.to.eql(guard.definition.payload); expect(defaults.name).to.eql(guard.definition.name); expect(defaults.aggregateId).to.eql(guard.definition.aggregateId); expect(guard.definition.aggregate).to.eql('aggName'); expect(defaults.aggregate).not.to.eql(guard.definition.aggregate); expect(guard.definition.context).to.eql('ctx.Name'); expect(defaults.context).not.to.eql(guard.definition.context); expect(guard.definition.revision).to.eql('rev'); expect(defaults.revision).not.to.eql(guard.definition.revision); expect(guard.definition.version).to.eql('v.'); expect(defaults.version).not.to.eql(guard.definition.version); expect(guard.definition.meta).to.eql('pass'); expect(defaults.meta).not.to.eql(guard.definition.meta); }); }); describe('overwriting the defaults', function () { it('it should apply them correctly', function() { var defaults = _.cloneDeep(guard.definition); guard.defineEvent({ correlationId: 'cmdId', id: 'eventId', payload: 'data', name: 'defName', aggregateId: 'path.to.aggId', aggregate: 'aggName', context: 'ctx.Name', revision: 'rev', version: 'v.', meta: 'pass' }); expect(guard.definition.correlationId).to.eql('cmdId'); expect(defaults.correlationId).not.to.eql(guard.definition.correlationId); expect(guard.definition.id).to.eql('eventId'); expect(defaults.id).not.to.eql(guard.definition.id); expect(guard.definition.payload).to.eql('data'); expect(defaults.payload).not.to.eql(guard.definition.payload); expect(guard.definition.name).to.eql('defName'); expect(defaults.name).not.to.eql(guard.definition.name); expect(guard.definition.aggregateId).to.eql('path.to.aggId'); expect(defaults.aggregateId).not.to.eql(guard.definition.aggregateId); expect(guard.definition.aggregate).to.eql('aggName'); expect(defaults.aggregate).not.to.eql(guard.definition.aggregate); expect(guard.definition.context).to.eql('ctx.Name'); expect(defaults.context).not.to.eql(guard.definition.context); expect(guard.definition.revision).to.eql('rev'); expect(defaults.revision).not.to.eql(guard.definition.revision); expect(guard.definition.version).to.eql('v.'); expect(defaults.version).not.to.eql(guard.definition.version); expect(guard.definition.meta).to.eql('pass'); expect(defaults.meta).not.to.eql(guard.definition.meta); }); }); }); describe('guarding an event', function () { var guard; var evt1 = { id: 'evtId1', aggregate: { id: 'aggId1', name: 'agg' }, context: { name: 'ctx' }, revision: 1 }; var evt2 = { id: 'evtId2', aggregate: { id: 'aggId1', name: 'agg' }, context: { name: 'ctx' }, revision: 2 }; var evt3 = { id: 'evtId3', aggregate: { id: 'aggId1', name: 'agg' }, context: { name: 'ctx' }, revision: 3 }; before(function () { guard = new RevisionGuard(store, { queueTimeout: 200 }); guard.defineEvent({ correlationId: 'correlationId', id: 'id', payload: 'payload', name: 'name', aggregateId: 'aggregate.id', aggregate: 'aggregate.name', context: 'context.name', revision: 'revision', version: 'version', meta: 'meta' }); }); beforeEach(function (done) { guard.currentHandlingRevisions = {}; store.clear(done); }); describe('in correct order', function () { it('it should work as expected', function (done) { var guarded = 0; function check () { guarded++; if (guarded === 3) { done(); } } guard.guard(evt1, function (err, finish) { expect(err).not.to.be.ok(); finish(function (err) { expect(err).not.to.be.ok(); expect(guarded).to.eql(0); check(); }); }); setTimeout(function () { guard.guard(evt2, function (err, finish) { expect(err).not.to.be.ok(); finish(function (err) { expect(err).not.to.be.ok(); expect(guarded).to.eql(1); check(); }); }); }, 10); setTimeout(function () { guard.guard(evt3, function (err, finish) { expect(err).not.to.be.ok(); finish(function (err) { expect(err).not.to.be.ok(); expect(guarded).to.eql(2); check(); }); }); }, 20); }); }); describe('in wrong order', function () { it('it should work as expected', function (done) { var guarded = 0; function check () { guarded++; // if (guarded === 3) { // done(); // } } guard.guard(evt1, function (err, finish) { expect(err).not.to.be.ok(); finish(function (err) { expect(err).not.to.be.ok(); expect(guarded).to.eql(0); check(); }); }); setTimeout(function () { guard.guard(evt2, function (err, finish) { expect(err).not.to.be.ok(); finish(function (err) { expect(err).not.to.be.ok(); expect(guarded).to.eql(1); check(); }); }); }, 30); setTimeout(function () { guard.guard(evt3, function (err, finish) { expect(err).not.to.be.ok(); finish(function (err) { expect(err).not.to.be.ok(); expect(guarded).to.eql(2); check(); }); }); guard.guard(evt3, function (err, finish) { expect(err).to.be.ok(); expect(err.name).to.eql('AlreadyHandlingError'); }); }, 10); setTimeout(function () { guard.guard(evt2, function (err) { expect(err).to.be.ok(); expect(err.name).to.eql('AlreadyHandledError'); expect(guarded).to.eql(3); guard.guard(evt3, function (err) { expect(err).to.be.ok(); expect(err.name).to.eql('AlreadyHandledError'); expect(guarded).to.eql(3); store.getLastEvent(function (err, evt) { expect(err).not.to.be.ok(); expect(evt.id).to.eql(evt3.id); done(); }); }); }); }, 300); }); }); describe('and missing something', function () { it('it should work as expected', function (done) { var guarded = 0; function check () { guarded++; // if (guarded === 3) { // done(); // } } guard.onEventMissing(function (info, evt) { expect(guarded).to.eql(1); expect(evt).to.eql(evt3); expect(info.aggregateId).to.eql('aggId1'); expect(info.aggregateRevision).to.eql(3); expect(info.guardRevision).to.eql(2); expect(info.aggregate).to.eql('agg'); expect(info.context).to.eql('ctx'); done(); }); guard.guard(evt1, function (err, finish) { expect(err).not.to.be.ok(); finish(function (err) { expect(err).not.to.be.ok(); expect(guarded).to.eql(0); check(); }); }); setTimeout(function () { guard.guard(evt3, function (err, finish) { expect(err).not.to.be.ok(); finish(function (err) { expect(err).not.to.be.ok(); expect(guarded).to.eql(2); check(); }); }); }, 20); }); }); }); }); });
togusafish/adrai-_-node-cqrs-saga
test/unit/revisionGuardTest.js
JavaScript
mit
10,450
/** * Copyright 2016 Facebook, Inc. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to * use, copy, modify, and distribute this software in source code or binary * form for use in connection with the web services and APIs provided by * Facebook. * * As with any software that integrates with the Facebook platform, your use * of this software is subject to the Facebook Developer Principles and * Policies [http://developers.facebook.com/policy/]. This copyright notice * shall be included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE * * @flow */ 'use strict'; const React = require('react-native'); const { View, ScrollView, } = React; const StyleSheet = require('F8StyleSheet'); const Header = require('./Header'); const RatingQuestion = require('./RatingQuestion'); const F8Button = require('F8Button'); import type {Question} from '../reducers/surveys'; import type {Session} from '../reducers/sessions'; type Props = { session: Session; questions: Array<Question>; onSubmit: (answers: Array<number>) => void; style?: any; }; class RatingCard extends React.Component { props: Props; state: Object; constructor(props: Props) { super(props); this.state = {}; } render() { const questions = this.props.questions.map((question, ii) => ( <RatingQuestion key={ii} style={styles.question} question={question} rating={this.state[ii]} onChange={(rating) => this.setState({[ii]: rating})} /> )); const completed = Object.keys(this.state).length === this.props.questions.length; return ( <View style={[styles.container, this.props.style]}> <ScrollView> <Header session={this.props.session} /> {questions} </ScrollView> <F8Button style={styles.button} type={completed ? 'primary' : 'bordered'} caption="Submit Review" onPress={() => completed && this.submit()} /> </View> ); } submit() { const answers = this.props.questions.map((_, ii) => this.state[ii]); this.props.onSubmit(answers); } } var styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'white', }, question: { padding: 40, paddingVertical: 25, }, button: { marginHorizontal: 15, marginVertical: 20, } }); module.exports = RatingCard;
josedab/react-native-examples
meetup-information/js/rating/RatingCard.js
JavaScript
mit
2,905
#ifndef __ciri_graphics_CullMode__ #define __ciri_graphics_CullMode__ namespace ciri { /** * Triangle winding order cull mode. */ enum class CullMode { None, /**< Do not cull triangles regardless of vertex ordering. */ Clockwise, /**< Cull triangles with clockwise vertex ordering. */ CounterClockwise /**< Cull triangles with counter-clockwise vertex ordering. */ }; } #endif
KasumiL5x/ciri
ciri/inc/ciri/graphics/CullMode.hpp
C++
mit
402
#region Copyright (c) 2007 Ryan Williams <drcforbin@gmail.com> /// <copyright> /// Copyright (c) 2007 Ryan Williams <drcforbin@gmail.com> /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. /// </copyright> #endregion using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Xml; using System.Text.RegularExpressions; using System.IO; using Mono.Cecil; using Mono.Security.Cryptography; using System.Security.Cryptography; namespace Obfuscar { class Project : IEnumerable<AssemblyInfo> { private const string SPECIALVAR_PROJECTFILEDIRECTORY = "ProjectFileDirectory"; private readonly List<AssemblyInfo> assemblyList = new List<AssemblyInfo> (); public List<AssemblyInfo> CopyAssemblyList { get { return copyAssemblyList; } } private readonly List<AssemblyInfo> copyAssemblyList = new List<AssemblyInfo> (); private readonly Dictionary<string, AssemblyInfo> assemblyMap = new Dictionary<string, AssemblyInfo> (); private readonly Variables vars = new Variables (); InheritMap inheritMap; Settings settings; // FIXME: Figure out why this exists if it is never used. private RSA keyvalue; // don't create. call FromXml. private Project () { } public string [] ExtraPaths { get { return vars.GetValue ("ExtraFrameworkFolders", "").Split (new char [] { Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries); } } public string KeyContainerName = null; public RSA KeyValue { get { if (keyvalue != null) return keyvalue; var lKeyFileName = vars.GetValue ("KeyFile", null); var lKeyContainerName = vars.GetValue ("KeyContainer", null); if (lKeyFileName == null && lKeyContainerName == null) return null; if (lKeyFileName != null && lKeyContainerName != null) throw new Exception ("'Key file' and 'Key container' properties cann't be setted together."); if (vars.GetValue ("KeyContainer", null) != null) { KeyContainerName = vars.GetValue ("KeyContainer", null); return RSA.Create (); //if (Type.GetType("System.MonoType") != null) // throw new Exception("Key containers are not supported for Mono."); //try //{ // CspParameters cp = new CspParameters(); // cp.KeyContainerName = vars.GetValue("KeyContainer", null); // cp.Flags = CspProviderFlags.UseMachineKeyStore | CspProviderFlags.UseExistingKey; // cp.KeyNumber = 1; // RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp); // keyvalue = CryptoConvert.FromCapiKeyBlob(rsa.ExportCspBlob(false)); //} //catch (Exception CryptEx) ////catch (System.Security.Cryptography.CryptographicException CryptEx) //{ // try // { // CspParameters cp = new CspParameters(); // cp.KeyContainerName = vars.GetValue("KeyContainer", null); // cp.Flags = CspProviderFlags.UseExistingKey; // cp.KeyNumber = 1; // RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp); // keyvalue = CryptoConvert.FromCapiKeyBlob(rsa.ExportCspBlob(false)); // } // catch // { // throw new ApplicationException(String.Format("Failure loading key from container - \"{0}\"", vars.GetValue("KeyContainer", null)), CryptEx); // } //} } else { try { keyvalue = CryptoConvert.FromCapiKeyBlob (File.ReadAllBytes (vars.GetValue ("KeyFile", null))); } catch (Exception ex) { throw new ApplicationException (String.Format ("Failure loading key file \"{0}\"", vars.GetValue ("KeyFile", null)), ex); } } return keyvalue; } } AssemblyCache m_cache; internal AssemblyCache Cache { get { if (m_cache == null) { m_cache = new AssemblyCache(this); } return m_cache; } } public static Project FromXml (XmlReader reader, string projectFileDirectory) { Project project = new Project (); project.vars.Add (SPECIALVAR_PROJECTFILEDIRECTORY, string.IsNullOrEmpty (projectFileDirectory) ? "." : projectFileDirectory); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { switch (reader.Name) { case "Var": { string name = Helper.GetAttribute (reader, "name"); if (name.Length > 0) { string value = Helper.GetAttribute (reader, "value"); if (value.Length > 0) project.vars.Add (name, value); else project.vars.Remove (name); } break; } case "Module": AssemblyInfo info = AssemblyInfo.FromXml (project, reader, project.vars); if (info.Exclude) { project.copyAssemblyList.Add (info); break; } Console.WriteLine ("Processing assembly: " + info.Definition.Name.FullName); project.assemblyList.Add (info); project.assemblyMap [info.Name] = info; break; } } } return project; } /// <summary> /// Looks through the settings, trys to make sure everything looks ok. /// </summary> public void CheckSettings () { if (!Directory.Exists (Settings.InPath)) throw new ApplicationException ("Path specified by InPath variable must exist:" + Settings.InPath); if (!Directory.Exists (Settings.OutPath)) { try { Directory.CreateDirectory (Settings.OutPath); } catch (IOException e) { throw new ApplicationException ("Could not create path specified by OutPath: " + Settings.OutPath, e); } } } internal InheritMap InheritMap { get { return inheritMap; } } internal Settings Settings { get { if (settings == null) settings = new Settings (vars); return settings; } } public void LoadAssemblies () { // build reference tree foreach (AssemblyInfo info in assemblyList) { // add self reference...makes things easier later, when // we need to go through the member references info.ReferencedBy.Add (info); // try to get each assembly referenced by this one. if it's in // the map (and therefore in the project), set up the mappings foreach (AssemblyNameReference nameRef in info.Definition.MainModule.AssemblyReferences) { AssemblyInfo reference; if (assemblyMap.TryGetValue (nameRef.Name, out reference)) { info.References.Add (reference); reference.ReferencedBy.Add (info); } } } // make each assembly's list of member refs foreach (AssemblyInfo info in assemblyList) { info.Init (); } // build inheritance map inheritMap = new InheritMap (this); } /// <summary> /// Returns whether the project contains a given type. /// </summary> public bool Contains (TypeReference type) { string name = Helper.GetScopeName (type); return assemblyMap.ContainsKey (name); } /// <summary> /// Returns whether the project contains a given type. /// </summary> internal bool Contains (TypeKey type) { return assemblyMap.ContainsKey (type.Scope); } public TypeDefinition GetTypeDefinition (TypeReference type) { if (type == null) return null; TypeDefinition typeDef = type as TypeDefinition; if (typeDef == null) { string name = Helper.GetScopeName (type); AssemblyInfo info; if (assemblyMap.TryGetValue (name, out info)) { string fullName = type.Namespace + "." + type.Name; typeDef = info.Definition.MainModule.GetType (fullName); } } return typeDef; } IEnumerator IEnumerable.GetEnumerator () { return assemblyList.GetEnumerator (); } public IEnumerator<AssemblyInfo> GetEnumerator () { return assemblyList.GetEnumerator (); } } }
remobjects/Obfuscar
Obfuscar/Project.cs
C#
mit
8,875
#include <iostream> #include <unordered_map> #include <string> using namespace std; vector <string> computeKMostFrequentQueries(vector <string> queries) { }
tzhenghao/InterviewQuestionExercises
ElementsOfProgrammingInterviews/Chapter13/ComputeKMostFrequentQueries.cpp
C++
mit
162
namespace Reusable.Diagnostics { public static class DebuggerDisplayString { public const string DefaultNoQuotes = "{DebuggerDisplay,nq}"; } }
he-dev/Reusable
Reusable.Core/src/Diagnostics/DebuggerDisplayString.cs
C#
mit
162
/* * RPCType.cpp * * Created on: 30 Apr 2014 * Author: meltuhamy */ #include <string> #include "ppapi/cpp/var.h" #include "RPCType.h" #include <vector> namespace pprpc{ //TODO - right now all the integer type marshaling is just wrapping the int32_t type! // byte pp::Var ByteType::AsVar(const ValidType<int8_t>& v){ return pp::Var((int) v.getValue()); } ValidType<int8_t> ByteType::Extract(const pp::Var& v){ if(v.is_int()){ return ValidType<int8_t>((int8_t)v.AsInt()); } else { return ValidType<int8_t>(); } } // octet pp::Var OctetType::AsVar(const ValidType<uint8_t>& v){ return pp::Var((int) v.getValue()); } ValidType<uint8_t> OctetType::Extract(const pp::Var& v){ if(v.is_int()){ return ValidType<uint8_t>((uint8_t)v.AsInt()); } else { return ValidType<uint8_t>(); } } // short pp::Var ShortType::AsVar(const ValidType<int16_t>& v){ return pp::Var((int) v.getValue()); } ValidType<int16_t> ShortType::Extract(const pp::Var& v){ if(v.is_int()){ return ValidType<int16_t>((int16_t)v.AsInt()); } else { return ValidType<int16_t>(); } } // ushort pp::Var UnsignedShortType::AsVar(const ValidType<uint16_t>& v){ return pp::Var((int) v.getValue()); } ValidType<uint16_t> UnsignedShortType::Extract(const pp::Var& v){ if(v.is_int()){ return ValidType<uint16_t>((uint16_t)v.AsInt()); } else { return ValidType<uint16_t>(); } } // long pp::Var LongType::AsVar(const ValidType<int32_t>& v){ return pp::Var((int) v.getValue()); } ValidType<int32_t> LongType::Extract(const pp::Var& v){ if(v.is_int()){ return ValidType<int32_t>((int32_t)v.AsInt()); } else { return ValidType<int32_t>(); } } // ulong pp::Var UnsignedLongType::AsVar(const ValidType<uint32_t>& v){ return pp::Var((int) v.getValue()); } ValidType<uint32_t> UnsignedLongType::Extract(const pp::Var& v){ if(v.is_int()){ return ValidType<uint32_t>((uint32_t)v.AsInt()); } else { return ValidType<uint32_t>(); } } // longlong pp::Var LongLongType::AsVar(const ValidType<int64_t>& v){ return pp::Var((int) v.getValue()); } ValidType<int64_t> LongLongType::Extract(const pp::Var& v){ if(v.is_int()){ return ValidType<int64_t>((int64_t)v.AsInt()); } else { return ValidType<int64_t>(); } } // ulonglong pp::Var UnsignedLongLongType::AsVar(const ValidType<uint64_t>& v){ return pp::Var((int) v.getValue()); } ValidType<uint64_t> UnsignedLongLongType::Extract(const pp::Var& v){ if(v.is_int()){ return ValidType<uint64_t>((uint64_t)v.AsInt()); } else { return ValidType<uint64_t>(); } } // float pp::Var FloatType::AsVar(const ValidType<float>& v){ return pp::Var(v.getValue()); } ValidType<float> FloatType::Extract(const pp::Var& v){ if(v.is_number()){ return ValidType<float>((float)v.AsDouble()); } else { return ValidType<float>(); } } // double pp::Var DoubleType::AsVar(const ValidType<double>& v){ return pp::Var(v.getValue()); } ValidType<double> DoubleType::Extract(const pp::Var& v){ if(v.is_number()){ return ValidType<double>(v.AsDouble()); } else { return ValidType<double>(); } } // domstring pp::Var DOMStringType::AsVar(const ValidType<std::string>& v){ return pp::Var(v.getValue()); } ValidType<std::string> DOMStringType::Extract(const pp::Var& v){ if(v.is_string()){ return ValidType<std::string>(v.AsString()); } else { return ValidType<std::string>(); } } // boolean pp::Var BooleanType::AsVar(const ValidType<bool>& v){ return pp::Var(v.getValue()); } ValidType<bool> BooleanType::Extract(const pp::Var& v){ if(v.is_bool()){ return ValidType<bool>(v.AsBool()); } else { return ValidType<bool>(); } } // null pp::Var NullType::AsVar(const ValidType<pp::Var::Null>& v){ return pp::Var(pp::Var::Null()); } ValidType<pp::Var::Null> NullType::Extract(const pp::Var& v){ if(v.is_null()){ return ValidType<pp::Var::Null>(pp::Var::Null()); } else { return ValidType<pp::Var::Null>(); } } // object pp::Var ObjectType::AsVar(const ValidType<pp::VarDictionary>& v){ return v.getValue(); } ValidType<pp::VarDictionary> ObjectType::Extract(const pp::Var& v){ if(v.is_dictionary()){ return ValidType<pp::VarDictionary>(pp::VarDictionary(v)); } else { return ValidType<pp::VarDictionary>(); } } // error pp::Var RPCErrorType::AsVar(const ValidType<RPCError>& v){ RPCError value = v.getValue(); pp::VarDictionary r; r.Set("code", LongType(value.code).AsVar()); r.Set("message", DOMStringType(value.message).AsVar()); r.Set("type", DOMStringType(value.type).AsVar()); return r; } ValidType<RPCError> RPCErrorType::Extract(const pp::Var& v){ ValidType<RPCError> invalid; if(v.is_dictionary()){ pp::VarDictionary vDict(v); RPCError r; /* member: code */ if(!vDict.HasKey("code")) return invalid; const ValidType< int32_t >& codePart = LongType::Extract(vDict.Get("code")); if(!codePart.isValid()) return invalid; r.code = codePart.getValue(); /* member: message */ if(!vDict.HasKey("message")) return invalid; const ValidType< std::string >& messagePart = DOMStringType::Extract(vDict.Get("message")); if(!messagePart.isValid()) return invalid; r.message = messagePart.getValue(); /* optional member: type */ if(vDict.HasKey("type")){ const ValidType< std::string >& typePart = DOMStringType::Extract(vDict.Get("type")); r.type = typePart.isValid() ? typePart.getValue() : ""; } else { r.type = ""; } return ValidType<RPCError>(r); } return ValidType<RPCError>(); } //pp::Var MyErrorType::AsVar(const ValidType<MyError>& v){ // MyError value = v.getValue(); // pp::VarDictionary r = pp::VarDictionary(RPCErrorType::AsVar(ValidType<RPCError>(value))); // r.Set("myNumber", FloatType::AsVar(value.myNumber)); // // return r; //} // //ValidType<MyError> MyErrorType::Extract(const pp::Var& v){ // MyError r; // r.init(RPCErrorType::Extract(v).getValue()); // if(v.is_dictionary()){ // pp::VarDictionary vDict(v); // r.myNumber = FloatType::Extract(vDict.Get("myNumber")).getValue(); // } // return ValidType<MyError>(r); //} }
meltuhamy/native-calls
cpp/RPCType.cpp
C++
mit
5,999
package org.knowm.xchange.gemini.v1.service; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.stream.Collectors; import lombok.Getter; import lombok.Setter; import org.knowm.xchange.Exchange; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order; import org.knowm.xchange.dto.trade.LimitOrder; import org.knowm.xchange.dto.trade.MarketOrder; import org.knowm.xchange.dto.trade.OpenOrders; import org.knowm.xchange.dto.trade.UserTrades; import org.knowm.xchange.exceptions.ExchangeException; import org.knowm.xchange.exceptions.NotAvailableFromExchangeException; import org.knowm.xchange.gemini.v1.GeminiAdapters; import org.knowm.xchange.gemini.v1.GeminiOrderType; import org.knowm.xchange.gemini.v1.dto.trade.GeminiCancelAllOrdersParams; import org.knowm.xchange.gemini.v1.dto.trade.GeminiLimitOrder; import org.knowm.xchange.gemini.v1.dto.trade.GeminiOrderStatusResponse; import org.knowm.xchange.gemini.v1.dto.trade.GeminiTradeResponse; import org.knowm.xchange.service.trade.TradeService; import org.knowm.xchange.service.trade.params.CancelAllOrders; import org.knowm.xchange.service.trade.params.CancelOrderByIdParams; import org.knowm.xchange.service.trade.params.CancelOrderParams; import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrencyPair; import org.knowm.xchange.service.trade.params.TradeHistoryParamLimit; import org.knowm.xchange.service.trade.params.TradeHistoryParamPaging; import org.knowm.xchange.service.trade.params.TradeHistoryParams; import org.knowm.xchange.service.trade.params.TradeHistoryParamsTimeSpan; import org.knowm.xchange.service.trade.params.orders.DefaultOpenOrdersParamCurrencyPair; import org.knowm.xchange.service.trade.params.orders.OpenOrdersParamCurrencyPair; import org.knowm.xchange.service.trade.params.orders.OpenOrdersParams; import org.knowm.xchange.service.trade.params.orders.OrderQueryParams; import org.knowm.xchange.utils.DateUtils; public class GeminiTradeService extends GeminiTradeServiceRaw implements TradeService { private static final OpenOrders noOpenOrders = new OpenOrders(new ArrayList<LimitOrder>()); public GeminiTradeService(Exchange exchange) { super(exchange); } @Override public OpenOrders getOpenOrders() throws IOException { return getOpenOrders(null); } @Override public OpenOrders getOpenOrders(OpenOrdersParams params) throws IOException { GeminiOrderStatusResponse[] activeOrders = getGeminiOpenOrders(); if (activeOrders.length <= 0) { return noOpenOrders; } else { if (params != null && params instanceof OpenOrdersParamCurrencyPair) { OpenOrdersParamCurrencyPair openOrdersParamCurrencyPair = (OpenOrdersParamCurrencyPair) params; return GeminiAdapters.adaptOrders( activeOrders, openOrdersParamCurrencyPair.getCurrencyPair()); } return GeminiAdapters.adaptOrders(activeOrders); } } @Override public String placeMarketOrder(MarketOrder marketOrder) throws IOException { throw new NotAvailableFromExchangeException(); } @Override public String placeLimitOrder(LimitOrder limitOrder) throws IOException { GeminiOrderStatusResponse newOrder = placeGeminiLimitOrder(limitOrder, GeminiOrderType.LIMIT); // The return value contains details of any trades that have been immediately executed as a // result // of this order. Make these available to the application if it has provided a GeminiLimitOrder. if (limitOrder instanceof GeminiLimitOrder) { GeminiLimitOrder raw = (GeminiLimitOrder) limitOrder; raw.setResponse(newOrder); } return String.valueOf(newOrder.getId()); } @Override public boolean cancelOrder(String orderId) throws IOException { return cancelGeminiOrder(orderId); } @Override public boolean cancelOrder(CancelOrderParams orderParams) throws IOException { if (orderParams instanceof CancelOrderByIdParams) { return cancelOrder(((CancelOrderByIdParams) orderParams).getOrderId()); } else { return false; } } @Override public Collection<String> cancelAllOrders(CancelAllOrders orderParams) throws IOException { if (orderParams instanceof GeminiCancelAllOrdersParams) { return Arrays.stream( cancelAllGeminiOrders( ((GeminiCancelAllOrdersParams) orderParams).isSessionOnly(), ((GeminiCancelAllOrdersParams) orderParams).getAccount()) .getDetails() .getCancelledOrders()) .mapToObj(id -> String.valueOf(id)) .collect(Collectors.toList()); } else { return null; } } /** * @param params Implementation of {@link TradeHistoryParamCurrencyPair} is mandatory. Can * optionally implement {@link TradeHistoryParamPaging} and {@link * TradeHistoryParamsTimeSpan#getStartTime()}. All other TradeHistoryParams types will be * ignored. */ @Override public UserTrades getTradeHistory(TradeHistoryParams params) throws IOException { final String symbol; if (params instanceof TradeHistoryParamCurrencyPair && ((TradeHistoryParamCurrencyPair) params).getCurrencyPair() != null) { symbol = GeminiAdapters.adaptCurrencyPair( ((TradeHistoryParamCurrencyPair) params).getCurrencyPair()); } else { // Exchange will return the errors below if CurrencyPair is not provided. // field not on request: "Key symbol was not present." // field supplied but blank: "Key symbol may not be the empty string" throw new ExchangeException("CurrencyPair must be supplied"); } final long timestamp; if (params instanceof TradeHistoryParamsTimeSpan) { Date startTime = ((TradeHistoryParamsTimeSpan) params).getStartTime(); timestamp = DateUtils.toUnixTime(startTime); } else { timestamp = 0; } Integer limit; if (params instanceof TradeHistoryParamPaging) { TradeHistoryParamPaging pagingParams = (TradeHistoryParamPaging) params; Integer pageLength = pagingParams.getPageLength(); Integer pageNum = pagingParams.getPageNumber(); limit = (pageLength != null && pageNum != null) ? pageLength * (pageNum + 1) : 50; } else { limit = 50; } if (params instanceof TradeHistoryParamLimit) { limit = ((TradeHistoryParamLimit) params).getLimit(); } final GeminiTradeResponse[] trades = getGeminiTradeHistory(symbol, timestamp, limit); return GeminiAdapters.adaptTradeHistory(trades, symbol); } @Override public TradeHistoryParams createTradeHistoryParams() { return new GeminiTradeHistoryParams(CurrencyPair.BTC_USD, 500, new Date(0)); } @Override public OpenOrdersParams createOpenOrdersParams() { return new DefaultOpenOrdersParamCurrencyPair(); } @Override public Collection<Order> getOrder(OrderQueryParams... params) throws IOException { Collection<Order> orders = new ArrayList<>(params.length); for (OrderQueryParams param : params) { orders.add(GeminiAdapters.adaptOrder(super.getGeminiOrderStatus(param))); } return orders; } @Getter @Setter public static class GeminiOrderQueryParams implements OrderQueryParams { private String orderId; private String clientOrderId; private boolean includeTrades; private String account; public GeminiOrderQueryParams( String orderId, String clientOrderId, boolean includeTrades, String account) { this.orderId = orderId; this.clientOrderId = clientOrderId; this.includeTrades = includeTrades; this.account = account; } @Override public String getOrderId() { return orderId; } @Override public void setOrderId(String orderId) { this.orderId = orderId; } } public static class GeminiTradeHistoryParams implements TradeHistoryParamCurrencyPair, TradeHistoryParamLimit, TradeHistoryParamsTimeSpan { private CurrencyPair currencyPair; private Integer limit; private Date startTime; public GeminiTradeHistoryParams(CurrencyPair currencyPair, Integer limit, Date startTime) { this.currencyPair = currencyPair; this.limit = limit; this.startTime = startTime; } public GeminiTradeHistoryParams() {} @Override public CurrencyPair getCurrencyPair() { return currencyPair; } @Override public void setCurrencyPair(CurrencyPair currencyPair) { this.currencyPair = currencyPair; } @Override public Integer getLimit() { return limit; } @Override public void setLimit(Integer limit) { this.limit = limit; } @Override public Date getStartTime() { return startTime; } @Override public void setStartTime(Date startTime) { this.startTime = startTime; } @Override public Date getEndTime() { return null; } @Override public void setEndTime(Date endTime) { // ignored } } }
stachon/XChange
xchange-gemini/src/main/java/org/knowm/xchange/gemini/v1/service/GeminiTradeService.java
Java
mit
9,136
#include <map> #include <set> #include <vector> #include <memory> #include <gumbo.h> #include <goosepp/contentExtraction/BoostChecker.h> #include <goosepp/contentExtraction/NodeTextCleaner.h> #include <goosepp/contentExtraction/TextNodeCollector.h> #include <goosepp/util/gumboUtils.h> #include <goosepp/stopwords/stopwords.h> #include <goosepp/stopwords/StopwordCounter.h> namespace scivey { namespace goosepp { namespace contentExtraction { using stopwords::StopwordCounter; BoostChecker::BoostChecker(shared_ptr<NodeTextCleanerIf> cleaner, shared_ptr<StopwordCounterIf> counter, size_t minStopwords, size_t maxStepsAway) : cleaner_(cleaner), stopwordCounter_(counter), minStopwords_(minStopwords), maxStepsAway_(maxStepsAway) {} bool BoostChecker::shouldBoost(const GumboNode *node) { bool isOk = false; size_t stepsAway = 0; auto visitor = [&isOk, &stepsAway, this](const GumboNode* sibling, function<void()> escape) { if (sibling->type == GUMBO_NODE_ELEMENT && sibling->v.element.tag == GUMBO_TAG_P) { if (stepsAway >= this->maxStepsAway_) { isOk = false; escape(); return; } auto siblingText = this->cleaner_->getText(sibling); if (this->stopwordCounter_->countStopwords(siblingText) > this->minStopwords_) { isOk = true; escape(); return; } stepsAway++; } }; util::walkSiblings(node, visitor); return isOk; } BoostCheckerFactory::BoostCheckerFactory(shared_ptr<NodeTextCleanerIf> cleaner, shared_ptr<StopwordCounterIf> counter, size_t minStopwords, size_t maxStepsAway) : cleaner_(cleaner), stopwordCounter_(counter), minStopwords_(minStopwords), maxStepsAway_(maxStepsAway) {} BoostChecker BoostCheckerFactory::build() { BoostChecker checker(cleaner_, stopwordCounter_, minStopwords_, maxStepsAway_); return checker; } } // contentExraction } // goosepp } // scivey
scivey/goosepp
src/contentExtraction/BoostChecker.cpp
C++
mit
2,214
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.4.4.17-7-c-iii-19 description: > Array.prototype.some - return value of callbackfn is a Number object includes: [runTestCase.js] ---*/ function testcase() { function callbackfn(val, idx, obj) { return new Number(); } return [11].some(callbackfn); } runTestCase(testcase);
PiotrDabkowski/Js2Py
tests/test_cases/built-ins/Array/prototype/some/15.4.4.17-7-c-iii-19.js
JavaScript
mit
707
$(document).ready(function(){ $('#environment,#language').change(function(){ var environment = $('#environment').val(); var language = $('#language').val(); if(environment==0) return true; $('#file').parent('div').addClass('hidden'); $('#load').addClass('hidden'); $.ajax({ type:'POST', url:translate_environment, data:{'_token':_token,'environment':environment,'language':language}, dataType:'json', success:function(dataJson) { if(dataJson.status=='success') { $('#file').find('option').remove(); $.each(dataJson.files,function(e,item){ $('#file').append($('<option>', {value:item, text:item})); }); $('#file').closest('div.form-group').removeClass('hidden'); $('#file').parent('div').removeClass('hidden'); $('#file').select2({width:'50%'}); $('#load').removeClass('hidden'); } else { $.growl.error({'title':'',message:dataJson.msg}); } } }) }); });
cobonto/public
admin/js/translate.js
JavaScript
mit
1,275
using System; namespace Nancy.Swagger.ObjectModel.Attributes { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Enum, AllowMultiple = false, Inherited = true)] public class SwaggerDataAttribute : Attribute { } }
pinnstrat/snap-nancy-swagger
src/Nancy.Swagger/ObjectModel/Attributes/SwaggerDataAttribute.cs
C#
mit
261
/** * @author Joe Adams */ goog.provide('CrunchJS.Systems.PathfindingSystem'); goog.require('CrunchJS.System'); goog.require('CrunchJS.Components.Path'); goog.require('goog.structs'); goog.require('goog.array'); goog.require('goog.math'); /** * Creates a new Pathfinding System * @constructor * @class */ CrunchJS.Systems.PathfindingSystem = function() { }; goog.inherits(CrunchJS.Systems.PathfindingSystem, CrunchJS.System); CrunchJS.Systems.PathfindingSystem.prototype.name = 'CrunchJS.Systems.PathfindingSystem'; /** * Called when the systme is activated. Sets the entity composition */ CrunchJS.Systems.PathfindingSystem.prototype.activate = function() { goog.base(this, 'activate'); this.setEntityComposition(this.getScene().createEntityComposition().all('PathQuery')); }; CrunchJS.Systems.PathfindingSystem.prototype.processEntity = function(frame, ent) { var query = this.getScene().getComponent(ent, 'PathQuery'), transform = this.getScene().getComponent(ent, 'Transform'), occGrid = this.getScene().getComponent(query.gridId, 'OccupancyGrid'), steps; this.getScene().removeComponent(ent, 'PathQuery'); steps = this.astar(occGrid, query.start, query.end, false); this.getScene().addComponent(ent, new CrunchJS.Components.Path({ steps : steps, step : 0 })); }; CrunchJS.Systems.PathfindingSystem.prototype.astar = function(occGrid, start, end, diagEnabled) { var openList = [], closedList = new goog.structs.Set(), startTile = occGrid.coordToTile(start.x, start.y), endTile = occGrid.findNearestUnoccupiedTile({ x : end.x, y : end.y }), currentNode, neighbors, steps, success = false; openList.push(this.createSearchNode(startTile,0,endTile)); while(openList.length != 0){ // Expand this node currentNode = openList.pop(); // we are done here if(currentNode.x == endTile.x && currentNode.y == endTile.y){ success = true; break; } closedList.add(currentNode); neighbors = occGrid.getNeighbors({ x : currentNode.x, y : currentNode.y, diag : diagEnabled }); goog.structs.forEach(neighbors, function(neighbor) { var notOccupied = !occGrid.isOccupied({ x : neighbor.x, y : neighbor.y }), notClosed = goog.structs.every(closedList, function(node) { return neighbor.x != node.x || neighbor.y != node.y; }); // If neighbor is not occupied and not already exanded if(notOccupied && notClosed){ // Create the node var neighborNode = this.createSearchNode(neighbor, currentNode.distFromStart+1, endTile); neighborNode.parent = currentNode; var node = goog.array.find(openList, function(node) { return node.x == neighborNode.x && node.y == neighborNode.y; }); // If neighbor is on openlist, but needs updated if(node && node.distFromStart > neighborNode.distFromStart){ node.distFromStart = neighborNode.distFromStart; node.parent = neighborNode.parent; node.heuristic = neighborNode.heuristic; } // Put it on the openlist else openList.push(neighborNode); } }, this); goog.array.stableSort(openList, function(o1, o2) { return o2.heuristic-o1.heuristic; }); } steps = this.reconstructPath(currentNode, occGrid); // Make sure it goes to exact coord instead of center of tile // if(success){ // steps[steps.length-1].x = end.x; // steps[steps.length-1].y = end.y; // } return steps; }; CrunchJS.Systems.PathfindingSystem.prototype.createSearchNode = function(tile, distFromStart, goalTile) { var node = {}, distToGoal; node.x = tile.x; node.y = tile.y; distToGoal = goog.math.safeFloor(Math.sqrt(Math.pow(Math.abs(goalTile.x - node.x),2) + Math.pow(Math.abs(goalTile.y - node.y), 2))); node.heuristic = distFromStart + distToGoal; node.distFromStart = distFromStart; return node; }; CrunchJS.Systems.PathfindingSystem.prototype.reconstructPath = function(node, occGrid) { var steps = [], step; while(node){ step = { x : node.x, y : node.y } steps.push(step); node = node.parent; } steps = this.lineOfSightPath(steps.reverse(), occGrid); for(var i = 0; i < steps.length; i++){ steps[i] = occGrid.tileToCoord(steps[i].x, steps[i].y); } return steps; }; CrunchJS.Systems.PathfindingSystem.prototype.lineOfSightPath = function(steps, occGrid) { var newSteps = [], currentLoc = steps[0]; for(var i = 1; i < steps.length; i++){ if(!this.canSee(currentLoc.x, currentLoc.y, steps[i].x, steps[i].y, occGrid)){ currentLoc = steps[i-1]; newSteps.push(currentLoc); i--; } else if(i == steps.length-1){ newSteps.push(steps[i]); } } return newSteps; }; // Algorithm : http://playtechs.blogspot.com/2007/03/raytracing-on-grid.html CrunchJS.Systems.PathfindingSystem.prototype.canSee = function(x0, y0, x1, y1, occGrid) { var dx = Math.abs(x1-x0), dy = Math.abs(y1-y0), x = x0, y = y0, n = 1 + dx + dy, x_inc = (x1>x0) ? 1 : -1, y_inc = (y1>y0) ? 1 : -1, error = dx-dy; dx *= 2; dy *= 2; var startN = n; while(n>0){ if(occGrid.isOccupied({ x : x, y : y })){ return false; } if(error>0){ x += x_inc; error -= dy; } else if(error == 0){ if(occGrid.isOccupied({ x : x, y : y+y_inc }) || occGrid.isOccupied({ x : x+x_inc, y : y })){ return false; } x += x_inc; error -= dy; } else{ y += y_inc; error += dx; } n--; } return true; };
jadmz/CrunchJS
app/js/engine/systems/PathfindingSystem.js
JavaScript
mit
5,422
using System; using System.Windows.Forms; namespace DocumentExplorerExample { /// <summary> /// Provides full information about application exception. /// </summary> public class ExceptionDialog : Form { #region Windows Form Designer generated code private System.ComponentModel.Container components = null; private System.Windows.Forms.Button buttonOk; private System.Windows.Forms.TextBox text1; private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(ExceptionDialog)); this.text1 = new System.Windows.Forms.TextBox(); this.buttonOk = new System.Windows.Forms.Button(); this.SuspendLayout(); // // text1 // this.text1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.text1.AutoSize = false; this.text1.Location = new System.Drawing.Point(8, 8); this.text1.Multiline = true; this.text1.Name = "text1"; this.text1.ReadOnly = true; this.text1.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.text1.Size = new System.Drawing.Size(524, 244); this.text1.TabIndex = 0; this.text1.Text = ""; this.text1.WordWrap = false; // // buttonOk // this.buttonOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; this.buttonOk.FlatStyle = System.Windows.Forms.FlatStyle.System; this.buttonOk.Location = new System.Drawing.Point(432, 260); this.buttonOk.Name = "buttonOk"; this.buttonOk.Size = new System.Drawing.Size(100, 24); this.buttonOk.TabIndex = 12; this.buttonOk.Text = "Continue"; // // ExceptionDialog // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(540, 288); this.Controls.Add(this.buttonOk); this.Controls.Add(this.text1); this.DockPadding.All = 8; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ExceptionDialog"; this.ShowInTaskbar = false; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Unexpected error occured"; this.ResumeLayout(false); } protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #endregion public ExceptionDialog() { InitializeComponent(); } public ExceptionDialog(Exception ex) { InitializeComponent(); Text = "Document Explorer - unexpected error occured"; text1.Text = "\r\n" + Application.ProductName + ".exe \r\n\r\n" + "Version " + Application.ProductVersion + "\r\n\r\n" + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() + "\r\n\r\n" + ex.ToString() + "\r\n"; text1.SelectionStart = text1.Text.Length; } } }
assadvirgo/Aspose_Words_NET
Examples/CSharp/Viewers-Visualizers/Document-Explorer/ExceptionDialog.cs
C#
mit
3,308
#define PROTOTYPE using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; using ProBuilder2.Common; using ProBuilder2.MeshOperations; namespace ProBuilder2.Examples { [RequireComponent(typeof(AudioSource))] public class IcoBumpin : MonoBehaviour { pb_Object ico; // A reference to the icosphere pb_Object component Mesh icoMesh; // A reference to the icosphere mesh (cached because we access the vertex array every frame) Transform icoTransform; // A reference to the icosphere transform component. Cached because I can't remember if GameObject.transform is still a performance drain :| AudioSource audioSource;// Cached reference to the audiosource. /** * Holds a pb_Face, the normal of that face, and the index of every vertex that touches it (sharedIndices). */ struct FaceRef { public pb_Face face; public Vector3 nrm; // face normal public int[] indices; // all vertex indices (including shared connected vertices) public FaceRef(pb_Face f, Vector3 n, int[] i) { face = f; nrm = n; indices = i; } } // All faces that have been extruded FaceRef[] outsides; // Keep a copy of the original vertex array to calculate the distance from origin. Vector3[] original_vertices, displaced_vertices; // The radius of the mesh icosphere on instantiation. [Range(1f, 10f)] public float icoRadius = 2f; // The number of subdivisions to give the icosphere. [Range(0, 3)] public int icoSubdivisions = 2; // How far along the normal should each face be extruded when at idle (no audio input). [Range(0f, 1f)] public float startingExtrusion = .1f; // The material to apply to the icosphere. public Material material; // The max distance a frequency range will extrude a face. [Range(1f, 50f)] public float extrusion = 30f; // An FFT returns a spectrum including frequencies that are out of human hearing range - // this restricts the number of bins used from the spectrum to the lower @fftBounds. [Range(8, 128)] public int fftBounds = 32; // How high the icosphere transform will bounce (sample volume determines height). [Range(0f, 10f)] public float verticalBounce = 4f; // Optionally weights the frequency amplitude when calculating extrude distance. public AnimationCurve frequencyCurve; // A reference to the line renderer that will be used to render the raw waveform. public LineRenderer waveform; // The y size of the waveform. public float waveformHeight = 2f; // How far from the icosphere should the waveform be. public float waveformRadius = 20f; // If @rotateWaveformRing is true, this is the speed it will travel. public float waveformSpeed = .1f; // If true, the waveform ring will randomly orbit the icosphere. public bool rotateWaveformRing = false; // If true, the waveform will bounce up and down with the icosphere. public bool bounceWaveform = false; public GameObject missingClipWarning; // Icosphere's starting position. Vector3 icoPosition = Vector3.zero; float faces_length; const float TWOPI = 6.283185f; // 2 * PI const int WAVEFORM_SAMPLES = 1024; // How many samples make up the waveform ring. const int FFT_SAMPLES = 4096; // How many samples are used in the FFT. More means higher resolution. // Keep copy of the last frame's sample data to average with the current when calculating // deformation amounts. Smoothes the visual effect. float[] fft = new float[FFT_SAMPLES], fft_history = new float[FFT_SAMPLES], data = new float[WAVEFORM_SAMPLES], data_history = new float[WAVEFORM_SAMPLES]; // Root mean square of raw data (volume, but not in dB). float rms = 0f, rms_history = 0f; /** * Creates the icosphere, and loads all the cache information. */ void Start() { audioSource = GetComponent<AudioSource>(); if( audioSource.clip == null ) missingClipWarning.SetActive(true); // Create a new icosphere. ico = pb_ShapeGenerator.IcosahedronGenerator(icoRadius, icoSubdivisions); // Shell is all the faces on the new icosphere. pb_Face[] shell = ico.faces; // Materials are set per-face on pb_Object meshes. pb_Objects will automatically // condense the mesh to the smallest set of subMeshes possible based on materials. #if !PROTOTYPE foreach(pb_Face f in shell) f.SetMaterial( material ); #else ico.gameObject.GetComponent<MeshRenderer>().sharedMaterial = material; #endif pb_Face[] connectingFaces; // Extrude all faces on the icosphere by a small amount. The third boolean parameter // specifies that extrusion should treat each face as an individual, not try to group // all faces together. ico.Extrude(shell, startingExtrusion, false, out connectingFaces); // ToMesh builds the mesh positions, submesh, and triangle arrays. Call after adding // or deleting vertices, or changing face properties. ico.ToMesh(); // Refresh builds the normals, tangents, and UVs. ico.Refresh(); outsides = new FaceRef[shell.Length]; Dictionary<int, int> lookup = ico.sharedIndices.ToDictionary(); // Populate the outsides[] cache. This is a reference to the tops of each extruded column, including // copies of the sharedIndices. for(int i = 0; i < shell.Length; ++i) outsides[i] = new FaceRef( shell[i], pb_Math.Normal(ico, shell[i]), ico.sharedIndices.AllIndicesWithValues(lookup, shell[i].distinctIndices).ToArray() ); // Store copy of positions array un-modified original_vertices = new Vector3[ico.vertices.Length]; System.Array.Copy(ico.vertices, original_vertices, ico.vertices.Length); // displaced_vertices should mirror icosphere mesh vertices. displaced_vertices = ico.vertices; icoMesh = ico.msh; icoTransform = ico.transform; faces_length = (float)outsides.Length; // Build the waveform ring. icoPosition = icoTransform.position; waveform.SetVertexCount(WAVEFORM_SAMPLES); if( bounceWaveform ) waveform.transform.parent = icoTransform; audioSource.Play(); } void Update() { // fetch the fft spectrum audioSource.GetSpectrumData(fft, 0, FFTWindow.BlackmanHarris); // get raw data for waveform audioSource.GetOutputData(data, 0); // calculate root mean square (volume) rms = RMS(data); /** * For each face, translate the vertices some distance depending on the frequency range assigned. * Not using the TranslateVertices() pb_Object extension method because as a convenience, that method * gathers the sharedIndices per-face on every call, which while not tremondously expensive in most * contexts, is far too slow for use when dealing with audio, and especially so when the mesh is * somewhat large. */ for(int i = 0; i < outsides.Length; i++) { float normalizedIndex = (i/faces_length); int n = (int)(normalizedIndex*fftBounds); Vector3 displacement = outsides[i].nrm * ( ((fft[n]+fft_history[n]) * .5f) * (frequencyCurve.Evaluate(normalizedIndex) * .5f + .5f)) * extrusion; foreach(int t in outsides[i].indices) { displaced_vertices[t] = original_vertices[t] + displacement; } } Vector3 vec = Vector3.zero; // Waveform ring for(int i = 0; i < WAVEFORM_SAMPLES; i++) { int n = i < WAVEFORM_SAMPLES-1 ? i : 0; vec.x = Mathf.Cos((float)n/WAVEFORM_SAMPLES * TWOPI) * (waveformRadius + (((data[n] + data_history[n]) * .5f) * waveformHeight)); vec.z = Mathf.Sin((float)n/WAVEFORM_SAMPLES * TWOPI) * (waveformRadius + (((data[n] + data_history[n]) * .5f) * waveformHeight)); vec.y = 0f; waveform.SetPosition(i, vec); } // Ring rotation if( rotateWaveformRing ) { Vector3 rot = waveform.transform.localRotation.eulerAngles; rot.x = Mathf.PerlinNoise(Time.time * waveformSpeed, 0f) * 360f; rot.y = Mathf.PerlinNoise(0f, Time.time * waveformSpeed) * 360f; waveform.transform.localRotation = Quaternion.Euler(rot); } icoPosition.y = -verticalBounce + ((rms + rms_history) * verticalBounce); icoTransform.position = icoPosition; // Keep copy of last FFT samples so we can average with the current. Smoothes the movement. System.Array.Copy(fft, fft_history, FFT_SAMPLES); System.Array.Copy(data, data_history, WAVEFORM_SAMPLES); rms_history = rms; icoMesh.vertices = displaced_vertices; } /** * Root mean square is a good approximation of perceived loudness. */ float RMS(float[] arr) { float v = 0f, len = (float)arr.Length; for(int i = 0; i < len; i++) v += Mathf.Abs(arr[i]); return Mathf.Sqrt(v / (float)len); } } }
hakur/shooter
Assets/ProCore/ProBuilder/API Examples/Icosphere FFT/Scripts/IcoBumpin.cs
C#
mit
8,702
require 'rails_helper' RSpec.describe OnlineApplicationPolicy, type: :policy do subject(:policy) { described_class.new(user, online_application) } let(:online_application) { build_stubbed(:online_application) } context 'for staff' do let(:user) { build_stubbed(:staff) } it { is_expected.to permit_action(:edit) } it { is_expected.to permit_action(:update) } it { is_expected.to permit_action(:show) } it { is_expected.to permit_action(:complete) } it { is_expected.to permit_action(:approve) } it { is_expected.to permit_action(:approve_save) } end context 'for manager' do let(:user) { build_stubbed(:manager) } it { is_expected.to permit_action(:edit) } it { is_expected.to permit_action(:update) } it { is_expected.to permit_action(:show) } it { is_expected.to permit_action(:complete) } it { is_expected.to permit_action(:approve) } it { is_expected.to permit_action(:approve_save) } end context 'for admin' do let(:user) { build_stubbed(:admin) } it { is_expected.not_to permit_action(:edit) } it { is_expected.not_to permit_action(:update) } it { is_expected.not_to permit_action(:show) } it { is_expected.not_to permit_action(:complete) } end end
ministryofjustice/fr-staffapp
spec/policies/online_application_policy_spec.rb
Ruby
mit
1,255
require "active_record" require "active_record/mass_assignment_security/associations" require "active_record/mass_assignment_security/attribute_assignment" require "active_record/mass_assignment_security/core" require "active_record/mass_assignment_security/nested_attributes" require "active_record/mass_assignment_security/persistence" require "active_record/mass_assignment_security/reflection" require "active_record/mass_assignment_security/relation" require "active_record/mass_assignment_security/validations" require "active_record/mass_assignment_security/associations" require "active_record/mass_assignment_security/inheritance" class ActiveRecord::Base include ActiveRecord::MassAssignmentSecurity::Core include ActiveRecord::MassAssignmentSecurity::AttributeAssignment include ActiveRecord::MassAssignmentSecurity::Persistence include ActiveRecord::MassAssignmentSecurity::Validations include ActiveRecord::MassAssignmentSecurity::NestedAttributes include ActiveRecord::MassAssignmentSecurity::Inheritance end class ActiveRecord::SchemaMigration < ActiveRecord::Base attr_accessible :version end
rails/protected_attributes
lib/active_record/mass_assignment_security.rb
Ruby
mit
1,126
/** * Created by james on 3/11/15. */ var crypto = Npm.require('crypto'); IntercomHash = function(user, secret) { var secret = new Buffer(secret, 'utf8') return crypto.createHmac('sha256', secret) .update(user._id).digest('hex'); }
jamesoy/Microscope
packages/intercom/intercom_server.js
JavaScript
mit
251
using System; using System.Drawing.Imaging; using System.IO; using System.Text; namespace TeknikProgramlama.Tools.Image { public static class Utils { public static string Image2Base64(this System.Drawing.Image image, ImageFormat format) { var imgBytes = image.ToBytes(format); var b64str = Convert.ToBase64String(imgBytes); return $@"data:image/{format.ToString().ToLower()};base64,{b64str}"; } public static string Image2Base64Html( this System.Drawing.Image image, ImageFormat format) => $@"<img src='{Image2Base64(image, format)}'/>"; public static byte[] ToBytes( this System.Drawing.Image image, ImageFormat format) { if (image == null) throw new ArgumentNullException(nameof(image)); if (format == null) throw new ArgumentNullException(nameof(format)); using (var stream = new MemoryStream()) { image.Save(stream, format); return stream.ToArray(); } } } }
teknikprogramlama/Teknikprogramlama.Tools
TeknikProgramlama.Tools/Image/Utils.cs
C#
mit
1,121
using UnityEngine; using System.Collections; public class sample : MonoBehaviour { // Use this for initialization void Start () { Vector3 startPos = new Vector3(0,0,0); Vector3 endPos = new Vector3(10,-10,0); Vector3 center = Vector3.Lerp(startPos, endPos, 0.5f); Vector3 cut = (endPos - startPos).normalized; Vector3 fwd = (center).normalized; Vector3 normal = Vector3.Cross(fwd, cut).normalized; GameObject goCutPlane = new GameObject("CutPlane", typeof(BoxCollider), typeof(Rigidbody)); goCutPlane.GetComponent<Collider>().isTrigger = true; Rigidbody bodyCutPlane = goCutPlane.GetComponent<Rigidbody>(); bodyCutPlane.useGravity = false; bodyCutPlane.isKinematic = true; Transform transformCutPlane = goCutPlane.transform; transformCutPlane.position = center; transformCutPlane.localScale = new Vector3(10f, .01f, 0.01f); transformCutPlane.rotation = transform.rotation; transformCutPlane.up = normal; } }
HackathonHC/team-z
Assets/sample.cs
C#
mit
985
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import 'babel-core/polyfill'; import path from 'path'; import express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import Router from './routes'; import Html from './components/Html'; import assets from './assets'; import { port } from './config'; import Config from './config.json'; import fetch from './core/fetch'; const server = global.server = express(); // // Register Node.js middleware // ----------------------------------------------------------------------------- server.use(express.static(path.join(__dirname, 'public'))); // // Register API middleware // ----------------------------------------------------------------------------- server.use('/api/content', require('./api/content')); server.all('*', (req, res, next) => { res.header('Access-Control-Allow-Origin', Config[process.env.NODE_ENV].clientUri); res.header('Access-Control-Allow-Headers', 'X-Requested-With'); res.header('Access-Control-Allow-Headers', 'Content-Type'); next(); }); server.get('/api/steam', async (req, res, next) => { var url = req.query.path; var isXml = false; for (var key in req.query) { if (key !== 'path') { var joiner = url.indexOf('?') > -1 ? '&' : '?'; url = url + joiner + key + '=' + encodeURIComponent(req.query[key]); } if (key === 'xml') { isXml = true; } } if (isXml) { url = 'http://steamcommunity.com' + url; } else { url = 'http://api.steampowered.com' + url + (url.indexOf('?') > -1 ? '&' : '?') + 'key=' + process.env.STEAM_API_KEY; } const response = await fetch(url); const data = isXml ? await response.text() : await response.json(); if (isXml) { res.set('Content-Type', 'text/xml'); } res.send(data); }); // // Register server-side rendering middleware // ----------------------------------------------------------------------------- server.get('*', async (req, res, next) => { try { let statusCode = 200; const data = { title: '', description: '', css: '', body: '', entry: assets.main.js }; const css = []; const context = { insertCss: styles => css.push(styles._getCss()), onSetTitle: value => data.title = value, onSetMeta: (key, value) => data[key] = value, onPageNotFound: () => statusCode = 404, }; await Router.dispatch({ path: req.path, query: req.query, context }, (state, component) => { data.body = ReactDOM.renderToString(component); data.css = css.join(''); }); const html = ReactDOM.renderToStaticMarkup(<Html {...data} />); res.status(statusCode).send('<!doctype html>\n' + html); } catch (err) { next(err); } }); // // Launch the server // ----------------------------------------------------------------------------- server.listen(port, () => { /* eslint-disable no-console */ console.log(`The server is running at http://localhost:${port}/`); });
cheshire137/cheevo-plotter
src/server.js
JavaScript
mit
3,191
package com.github.robocup_atan.atan.parser.objects; /* * #%L * Atan * %% * Copyright (C) 2003 - 2014 Atan * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ //~--- non-JDK imports -------------------------------------------------------- import com.github.robocup_atan.atan.model.ControllerCoach; import com.github.robocup_atan.atan.model.ControllerPlayer; import com.github.robocup_atan.atan.model.ControllerTrainer; import com.github.robocup_atan.atan.model.enums.Flag; /** * The parser object for goal west. * * @author Atan */ public class ObjNameFlagGoalWest implements ObjName { char qualifier; /** * A constructor for goal west. * * @param qualifier Either 't' or 'b'. */ public ObjNameFlagGoalWest(char qualifier) { this.qualifier = qualifier; } /** {@inheritDoc} */ @Override public void infoSeeFromEast(ControllerPlayer c, double distance, double direction, double distChange, double dirChange, double bodyFacingDirection, double headFacingDirection) { switch (qualifier) { case 't' : c.infoSeeFlagGoalOther(Flag.RIGHT, distance, direction, distChange, dirChange, bodyFacingDirection, headFacingDirection); break; case 'b' : c.infoSeeFlagGoalOther(Flag.LEFT, distance, direction, distChange, dirChange, bodyFacingDirection, headFacingDirection); break; default : c.infoSeeFlagGoalOther(Flag.CENTER, distance, direction, distChange, dirChange, bodyFacingDirection, headFacingDirection); break; } } /** {@inheritDoc} */ @Override public void infoSeeFromWest(ControllerPlayer c, double distance, double direction, double distChange, double dirChange, double bodyFacingDirection, double headFacingDirection) { switch (qualifier) { case 't' : c.infoSeeFlagGoalOwn(Flag.LEFT, distance, direction, distChange, dirChange, bodyFacingDirection, headFacingDirection); break; case 'b' : c.infoSeeFlagGoalOwn(Flag.RIGHT, distance, direction, distChange, dirChange, bodyFacingDirection, headFacingDirection); break; default : c.infoSeeFlagGoalOwn(Flag.CENTER, distance, direction, distChange, dirChange, bodyFacingDirection, headFacingDirection); break; } } /** {@inheritDoc} */ @Override public void infoSeeFromEast(ControllerCoach c, double x, double y, double deltaX, double deltaY, double bodyAngle, double neckAngle) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ @Override public void infoSeeFromWest(ControllerCoach c, double x, double y, double deltaX, double deltaY, double bodyAngle, double neckAngle) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ @Override public void infoSee(ControllerTrainer c) { throw new UnsupportedOperationException(); } }
robocup-atan/atan
src/main/java/com/github/robocup_atan/atan/parser/objects/ObjNameFlagGoalWest.java
Java
mit
4,455
#pragma once #include <app/common.hpp> #include <app/LedDisplay.hpp> #include <audio.hpp> namespace rack { namespace app { struct AudioWidget : LedDisplay { LedDisplayChoice* driverChoice; LedDisplaySeparator* driverSeparator; LedDisplayChoice* deviceChoice; LedDisplaySeparator* deviceSeparator; LedDisplayChoice* sampleRateChoice; LedDisplaySeparator* sampleRateSeparator; LedDisplayChoice* bufferSizeChoice; void setAudioPort(audio::Port* port); }; } // namespace app } // namespace rack
AndrewBelt/Rack
include/app/AudioWidget.hpp
C++
mit
505
// @flow /* eslint-disable no-console */ import chalk from "chalk"; import createWatcher from "./watch"; import loadWatches from "./load-watches"; import hasWatchman from "./utils/has-watchman"; import type { WatchDefinition } from "./load-watches"; import getConfig from "./config"; type Targets = { [target: string]: Array<{ wd: string, data: Array<WatchDefinition> }> }; const getTargets = (definitions): Targets => { const targets = {}; definitions.forEach(def => { Object.keys(def.data).forEach(target => { targets[target] = targets[target] || []; targets[target].push({ wd: def.wd, data: def.data[target] }); }); }); return targets; }; const setupPhaseWatch = (definitions, watcher, config) => phase => { definitions.forEach(({ wd, data: phaseData }) => { if (!phaseData[phase]) { return; } const phaseWatches = phaseData[phase]; phaseWatches.forEach(watcher.add(wd, config[phase])); }); }; const setupWatches = async (phase: string | Array<string>) => { let phases; if (typeof phase === "string") { phases = [phase]; } else { phases = phase; } const [definitions, watchman, config] = await Promise.all([ loadWatches(), hasWatchman(), getConfig() ]); const watcher = createWatcher(watchman); const setup = setupPhaseWatch(definitions, watcher, config); phases.forEach(setup); const targets = getTargets(definitions); phases.forEach(p => { if (!Object.keys(targets).includes(p)) { console.error( `\n${chalk.yellow("WARNING")}: target ${chalk.yellow( p )} not found in any .watch files\n` ); } }); watcher.start(); }; export const listTargets = async (): Promise<Targets> => { const definitions = await loadWatches(); return getTargets(definitions); }; export default setupWatches;
laat/nurture
src/index.js
JavaScript
mit
1,846
$(document).ready(function(){ initUploadExcerptPhoto(); initUploadMedia(); $('#edcomment_save').removeAttr('disabled'); $(document).on('click', '.js-single-click', function(){ $(this).attr('disabled', 'disabled'); }); $(document).on('submit', '.js-single-submit', function(){ var submitBtn=$(this).find(':submit'); submitBtn.attr('disabled', 'disabled'); }); $(document).on('click', '.js-add-media', function(e){ e.preventDefault(); $('.js-modal-add-media').modal(); $('.js-modal-add-media').on('shown.bs.modal', function (e) { refreshIsotope(); }) }); $(document).on('click', '.js-pick-or-upload', function(e){ e.preventDefault(); $('.js-modal-add-excerpt-media').modal(); $('.js-modal-add-excerpt-media').on('shown.bs.modal', function (e) { refreshIsotope(); }) }); $(document).on('click', '.js-trigger-upload', function(){ $('.js-upload-input').click(); }); $(document).on('click', '.js-trigger-upload-medias', function(){ $('#article_media_media').click(); }); $(document).on('click', '.js-trigger-upload-excerpt', function(){ $('#article_excerpt_media').click(); }); $(document).on('click', '.js-media-object-remove', function(e){ e.preventDefault(); $.post($(this).attr('data-href'), function(){ $('.js-media-object-remove').addClass('hidden'); $('.js-media-object').attr('src', '/bundles/blog/img/svg/image-placeholder.svg'); $('#article_excerpt_photo').val(''); }); }); $(document).on('click', '.js-media-object-reset', function(e) { $('.js-media-object-remove').addClass('hidden'); $('.js-media-object').attr('src', '/bundles/blog/img/svg/image-placeholder.svg'); $('#article_excerpt_photo').val(''); }); $(document).on('click', '.js-delete-object', function(e){ e.preventDefault(); $('.js-delete-object-text').text($(this).attr('data-text')); $('.js-delete-object-title').text($(this).attr('data-title')); $('.js-delete-object-href').attr('href',$(this).attr('data-href')); }); $(document).on('click', '.js-insert-media', function(e){ e.preventDefault(); $('.phototiles__iteminner.selected').each(function(){ var caption = $(this).parents('li').find('.ajax_media_form textarea').val(); if(caption) { tinymce.editors[0].insertContent('<div>'+ $(this).find('.js-add-media-editor').attr('data-content') +'<span class="d--b margin--halft app-grey text--mini text--italic">'+ caption +'</span></div>'); } else tinymce.editors[0].insertContent($(this).find('.js-add-media-editor').attr('data-content')); }); $('.js-close-insert-modal').click(); }); $(document).on('click', '.js-pagination-pager', function(e){ e.preventDefault(); $.post($(this).attr('href'), function(data){ $('.js-load-more').remove(); $('.js-media-content').after(data.pagination); if ($('.js-media-content').hasClass("js-noisotope")){ $('.js-media-content').append(data.html); } else{ // Isotope after Load more // Second approach $container = $('.isotope:visible'); // We need jQuery object, so instead of response.photoContent we use $(response.photoContent) var $new_items = $(data.html); // imagesLoaded is independent plugin, which we use as timeout until all images in $container are fetched, so their real size can be calculated; When they all are on the page, than code within will be executed $container.append( $new_items ); $container.imagesLoaded( function() { $container.isotope( 'appended', $new_items ); //$container.isotope( 'prepended', $new_items ); $container.isotope('layout'); $('.phototiles__item').removeClass('muted--total'); if ( $('.modal:visible').length ) { $('.modal:visible').each(centerModal); } else { if ( $(window).width() >= 992 ) { $('html, body').animate({ scrollTop: $(document).height() }, 1200); $('.dashboard-menu.alltheway').css('min-height', $('.dashboard-content').height()); } } }); } }); }); $(document).on('click', '.js-content-replace', function(e){ e.preventDefault(); element=$(this); $.post($(this).attr('data-href'), function(data){ element.parent().html(data.html); }); }); // Correct display after slow page load $('.gl.muted--total').each(function() { $(this).removeClass('muted--total'); }); // Make modal as wide as possible $('.modal--full').on('shown.bs.modal', function (e) { recalculateModal($(this)); }); // Select image for insert into article $(document).on('click', '.js-modal-add-media .phototiles__iteminner', function(e){ $(this).toggleClass('selected'); }); $(document).on('click', '.js-modal-add-excerpt-media .phototiles__iteminner', function(e){ var item = $(this).find('.js-add-media-editor'); $('.js-excerpt-holder').html( item.attr('data-content') ); $('#article_excerptPhoto').val(item.attr('data-val')); $('.js-modal-add-excerpt-media .js-close-insert-modal').trigger('click'); }); $(document).on('submit', '.js-comment-form', function(e){ e.preventDefault(); var form=$(this); var submit=form.find(':submit'); submit.attr('disabled', 'disabled'); $.post($(this).attr('action'),$(this).serialize() , function(data){ $('.js-comments-content').replaceWith(data.html); if (data.currentComment) { $('html, body').animate({ scrollTop: $("#"+data.currentComment).offset().top }, 2000); } }); }); $(document).on('submit', '.ajax_media_form', function(e){ e.preventDefault(); $.post($(this).attr('action'), $(this).serialize(), function(data){}); }); getFancyCategories(); }); // End of $(document).ready() // Resize or orientationchange of document $(window).bind('resize orientationchange', function(){ if ( $('.modal--full:visible').length ) { recalculateModal($('.modal--full')); } }); // Calculate position for full-width modal function recalculateModal($this) { mod_width = Math.floor($(window).width()*0.96); mod_height = Math.floor($(window).height()*0.96); $this.find('.modal-dialog').css('width', mod_width); head_foot_offset = 150; $this.find('.modal-body').css('max-height', mod_height - head_foot_offset); $this.removeClass('muted--total'); refreshIsotope(); } // Refresh Isotope function refreshIsotope() { $container = $('.isotope'); $container.imagesLoaded(function () { $container.isotope().isotope('layout'); $('.phototiles__item').removeClass('muted--total'); $('.modal:visible').each(centerModal); }); } function initUploadExcerptPhoto() { $('#form_excerptImage').fileupload({ url: $('#form_excerptImage').attr('data-href'), dataType: 'json', maxFileSize: 20000000, done: function (e, response) { var data = response.result; if (data.success == 'true') { $('.js-media-object').replaceWith(data.media); $('.js-excerpt-photo').val(data.id); $('.js-media-object-remove').removeClass('hidden'); $('.js-media-object-remove').attr('data-href', data.href); } }, progressall: function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); $('#progress .bar').css('width', progress + '%'); } }); } function initUploadMedia() { $('#article_media_media').fileupload({ url: $('#article_media_media').attr('data-href'), dataType: 'json', maxFileSize: 20000000, done: function (e, response) { var data = response.result; $('.js-load-more').remove(); $('.pagination').remove(); $('.js-media-content').replaceWith(data.html); // $('.js-trigger-upload-medias').parent().removeClass('muted--total'); // $('.js-trigger-upload-medias').removeClass('muted--total'); // $('.js-trigger-upload-medias').parent().css('position', 'relative'); refreshIsotope(); }, progressall: function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); $('#progress .bar').css('width', progress + '%'); } }); $('#article_excerpt_media').fileupload({ url: $('#article_excerpt_media').attr('data-href'), dataType: 'json', maxFileSize: 20000000, done: function (e, response) { var data = response.result; $('.js-load-more').remove(); $('.pagination').remove(); $('.js-media-content').replaceWith(data.html); // $('.js-trigger-upload-medias').parent().removeClass('muted--total'); // $('.js-trigger-upload-medias').removeClass('muted--total'); // $('.js-trigger-upload-medias').parent().css('position', 'relative'); refreshIsotope(); }, progressall: function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); $('#progress .bar').css('width', progress + '%'); } }); } function getFancyCategories() { $('.js-get-pretty-categories').each(function(){ var input = $(this); var url = input.attr('data-category-url'); var selected = []; input.find('[checked]').each(function(){ selected.push($(this).val()); }); input.find('[selected]').each(function(){ selected.push($(this).val()); }); $.post(url, { 'select': selected }, function(data){ if(data.success === true) { if(input.attr('data-empty-option') != undefined) { input.html('<option value="">' + input.attr('data-empty-option') + '</option>'); } else input.html(''); input.append(data.html).removeClass('hide'); } }); }); } function initNprogress() { $(document).ajaxStart(function(e) { if( (e.target.activeElement == undefined) || !$(e.target.activeElement).hasClass('js-skip-nprogress') ) NProgress.start(); }).ajaxStop(function(e){ NProgress.done(); }); }
NegMozzie/tapha
src/BlogBundle/Resources/public/js/fe-general.js
JavaScript
mit
10,917
<?php namespace Arthem\GoogleApi\Infrastructure\Client; use Arthem\GoogleApi\Infrastructure\Client\Decoder\DecoderInterface; use Arthem\GoogleApi\Infrastructure\Client\Exception\ClientErrorException; use GuzzleHttp\ClientInterface; use Psr\Log\LoggerAwareInterface; use Psr\Log\LoggerInterface; abstract class Client implements LoggerAwareInterface { /** * @var string */ protected $apiUrl; /** * The client API key. * * @var string */ private $apiKey; /** * @var ClientInterface */ private $httpClient; /** * @var DecoderInterface */ private $decoder; /** * @var LoggerInterface */ private $logger; /** * @param ClientInterface $httpClient * @param DecoderInterface $decoder * @param string $apiKey */ public function __construct(ClientInterface $httpClient, DecoderInterface $decoder, $apiKey) { $this->apiKey = $apiKey; $this->decoder = $decoder; $this->httpClient = $httpClient; } /** * @param string $method * @param string $uri * @param array $parameters * @param array $options * * @return array * * @throws ClientErrorException */ public function request($method, $uri, array $parameters = [], array $options = []) { $parameters['key'] = $this->apiKey; $options['query'] = $parameters; $uri = $this->apiUrl.$uri.'/json'; $this->log($method, $uri, $options); $response = $this->httpClient->request($method, $uri, $options); $result = $this->decoder->decode($response); if (!isset($result['status'])) { throw new ClientErrorException('Missing return status'); } if (!in_array($result['status'], [ 'OK', 'ZERO_RESULTS', ], true)) { throw new ClientErrorException(sprintf('Invalid return status "%s"', $result['status'])); } return $result; } /** * @param string $method * @param string $uri * @param array $options */ private function log($method, $uri, array $options = []) { if (null === $this->logger) { return; } $this->logger->info( sprintf( 'google-api request: %s %s', $method, $uri ), [ 'params' => http_build_query( $options['query'] ), ] ); } /** * {@inheritdoc} */ public function setLogger(LoggerInterface $logger) { $this->logger = $logger; return $this; } }
4rthem/google-api
src/Infrastructure/Client/Client.php
PHP
mit
2,757
require 'brahma/web/fall' class CmsController < ApplicationController def index @title = t('web.title.cms') @fall_card = Brahma::Web::FallCard.new nil lang = I18n.locale Cms::Article.select(:id, :title, :summary, :logo).where(lang: lang).order(created: :desc).limit(20).each { |a| @fall_card.add cms_article_path(a.id), a.title, a.summary, a.logo } @tags = Cms::Tag.select(:id, :name).where(lang: lang).order(visits: :desc).limit(10) end end
chonglou/portal
app/controllers/cms_controller.rb
Ruby
mit
468
var statusItems = initStatusItems(); module.exports = { // check for an item completion checkItems: function(content, callback) { // iterate each status item to check for matches for (var i = 0; i < statusItems.length; i++) { var item = statusItems[i]; // skip item if it is already complete if (item.complete === true) { continue; } // item is incomplete, check the document if (content.indexOf(item.text) >= 0) { item.complete = true; callback(item.output); } } }, // cleanup phantom variables once installation finishes cleanup: function() { //statusItems = null; statusItems = initStatusItems(); }, // check if the script completed checkComplete: function() { var lastItem = statusItems[statusItems.length - 1]; // only check the last item in the array if it's complete if (lastItem.complete === true) { return true; } return false; } }; // initialize the status items to check the DOM against function initStatusItems() { return [ newStatusItem( 'Creating Sugar configuration file (config.php)', 'Creating Sugar Configuration File...' ), newStatusItem( 'Creating Sugar application tables, audit tables and relationship metadata', 'Creating application/audit tables and relationship data...' ), newStatusItem( 'Creating the database', 'Creating the database...' ), newStatusItem( 'Creating default Sugar data', 'Creating default Sugar data...' ), newStatusItem( 'Updating license information...', 'Updating license information...' ), newStatusItem( 'Creating default users...', 'Creating default users...' ), newStatusItem( 'Creating default reports...', 'Creating default reports...' ), newStatusItem( 'Populating the database tables with demo data', 'Inserting demo data...' ), newStatusItem( 'Creating default scheduler jobs...', 'Creating default scheduler jobs...' ) /*newStatusItem( 'is now complete!', 'Installation is complete!' )*/ ]; } // create a new status item to check against function newStatusItem(searchText, outputText, isComplete) { if (typeof(isComplete) === 'undefined') { isComplete = false; } return { text: searchText, output: outputText, complete: isComplete }; }
ScopeXL/sugarbuild
lib/phantom-install-helper.js
JavaScript
mit
2,815
import numpy as np def random_flips(X): """ Take random x-y flips of images. Input: - X: (N, C, H, W) array of image data. Output: - An array of the same shape as X, containing a copy of the data in X, but with half the examples flipped along the horizontal direction. """ N, C, H, W = X.shape mask = np.random.randint(2, size=N) # what this means is the ith image should be flipped with probability 1/2 out = np.zeros_like(X) out[mask==1] = X[mask==1,:,:,::-1] out[mask==0] = X[mask==0] return out def random_crops(X, crop_shape): """ Take random crops of images. For each input image we will generate a random crop of that image of the specified size. Input: - X: (N, C, H, W) array of image data - crop_shape: Tuple (HH, WW) to which each image will be cropped. Output: - Array of shape (N, C, HH, WW) """ N, C, H, W = X.shape HH, WW = crop_shape assert HH < H and WW < W out = np.zeros((N, C, HH, WW), dtype=X.dtype) np.random.randint((H-HH), size=N) y_start = np.random.randint((H-HH), size=N) #(H-HH)*np.random.random_sample(N) x_start = np.random.randint((W-WW), size=N) #(W-WW)*np.random.random_sample(N) for i in xrange(N): out[i] = X[i, :, y_start[i]:y_start[i]+HH, x_start[i]:x_start[i]+WW] return out def random_contrast(X, scale=(0.8, 1.2)): """ Randomly adjust the contrast of images. For each input image, choose a number uniformly at random from the range given by the scale parameter, and multiply each pixel of the image by that number. Inputs: - X: (N, C, H, W) array of image data - scale: Tuple (low, high). For each image we sample a scalar in the range (low, high) and multiply the image by that scaler. Output: - Rescaled array out of shape (N, C, H, W) where out[i] is a contrast adjusted version of X[i]. """ low, high = scale N = X.shape[0] out = np.zeros_like(X) l = (scale[1]-scale[0])*np.random.random_sample(N)+scale[0] # for i in xrange(N): # out[i] = X[i] * l[i] out = X * l[:,None,None,None] # TODO: vectorize this somehow... #out = #np.diag(l).dot(X)#X*l[:,np.newaxis, np.newaxis, np.newaxis] return out def random_tint(X, scale=(-10, 10)): """ Randomly tint images. For each input image, choose a random color whose red, green, and blue components are each drawn uniformly at random from the range given by scale. Add that color to each pixel of the image. Inputs: - X: (N, C, W, H) array of image data - scale: A tuple (low, high) giving the bounds for the random color that will be generated for each image. Output: - Tinted array out of shape (N, C, H, W) where out[i] is a tinted version of X[i]. """ low, high = scale N, C = X.shape[:2] out = np.zeros_like(X) # for i in xrange(N): # l = (scale[1]-scale[0])*np.random.random_sample(C)+scale[0] # out[i] = X[i]+l[:,None,None] l = (scale[1]-scale[0])*np.random.random_sample((N,C))+scale[0] out = X+l[:,:,None,None] return out def fixed_crops(X, crop_shape, crop_type): """ Take center or corner crops of images. Inputs: - X: Input data, of shape (N, C, H, W) - crop_shape: Tuple of integers (HH, WW) giving the size to which each image will be cropped. - crop_type: One of the following strings, giving the type of crop to compute: 'center': Center crop 'ul': Upper left corner 'ur': Upper right corner 'bl': Bottom left corner 'br': Bottom right corner Returns: Array of cropped data of shape (N, C, HH, WW) """ N, C, H, W = X.shape HH, WW = crop_shape x0 = (W - WW) / 2 y0 = (H - HH) / 2 x1 = x0 + WW y1 = y0 + HH if crop_type == 'center': return X[:, :, y0:y1, x0:x1] elif crop_type == 'ul': return X[:, :, :HH, :WW] elif crop_type == 'ur': return X[:, :, :HH, -WW:] elif crop_type == 'bl': return X[:, :, -HH:, :WW] elif crop_type == 'br': return X[:, :, -HH:, -WW:] else: raise ValueError('Unrecognized crop type %s' % crop_type)
UltronAI/Deep-Learning
CS231n/reference/cnn_assignments-master/assignment3/cs231n/data_augmentation.py
Python
mit
4,178
/** * Copyright (c) Tiny Technologies, Inc. All rights reserved. * Licensed under the LGPL or a commercial license. * For LGPL see License.txt in the project root for license information. * For commercial licenses see https://www.tiny.cloud/ * * Version: 5.1.1 (2019-10-28) */ (function (domGlobals) { 'use strict'; var global = tinymce.util.Tools.resolve('tinymce.PluginManager'); function Plugin () { global.add('textcolor', function () { domGlobals.console.warn('Text color plugin is now built in to the core editor, please remove it from your editor configuration'); }); } Plugin(); }(window));
cdnjs/cdnjs
ajax/libs/tinymce/5.1.1/plugins/textcolor/plugin.js
JavaScript
mit
650
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using ZSUIFramework; public class CreatRoomGUI : ZSUI { public Button mBtnClose = null; public override void Init() { ZSUIListener.AddClickEvent( mBtnClose.gameObject, Close ); } }
zhanshu233/ZSUIFramework
Assets/Example/Scripts/UI/CreatRoomGUI.cs
C#
mit
293
export {NavbarItemComponent} from './navbar-item/navbar-item.component'; export {NavbarComponent} from './navbar.component';
Hertox82/Lortom
angular-backend/src/app/backend-module/navbar/index.ts
TypeScript
mit
125
# frozen_string_literal: true module DropletKit class AccountMapping include Kartograph::DSL kartograph do root_key singular: 'account', scopes: [:read] mapping Account scoped :read do property :droplet_limit property :floating_ip_limit property :email property :uuid property :email_verified end end end end
digitalocean/droplet_kit
lib/droplet_kit/mappings/account_mapping.rb
Ruby
mit
392
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-09-07 00:18 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('payments', '0004_auto_20160904_0048'), ] operations = [ migrations.AlterField( model_name='subscription', name='status', field=models.CharField(choices=[('new', 'Created'), ('unconfirmed', 'Waiting for payment'), ('active', 'Active'), ('cancelled', 'Cancelled'), ('error', 'Error')], default='new', max_length=16), ), ]
CCrypto/ccvpn3
payments/migrations/0005_auto_20160907_0018.py
Python
mit
612
#!/usr/bin/python import requests import json # Import modules for CGI handling import cgi, cgitb # Create instance of FieldStorage form = cgi.FieldStorage() # Get data from fields user_title = form.getvalue('search_title') print "Content-type: text/html\n\n"; # Setting attributes to send to Wikipedia API baseurl = 'http://en.wikipedia.org/w/api.php' search_atts = {} search_atts['action'] = 'query' search_atts['list'] = 'search' search_atts['srwhat'] = 'text' search_atts['format'] = 'json' search_atts['srsearch'] = user_title search_resp = requests.get(baseurl, params = search_atts) search_data = search_resp.json() title = search_data["query"]["search"][0]["title"] # Make the title with no space which will be needed for making a url link to send for summary title_w_no_space = "" for i in title: if i==" ": title_w_no_space = title_w_no_space + "_" else: title_w_no_space = title_w_no_space + i # Getting related topics using the result given by Wikipedia API topics = [] for key in search_data["query"]["search"]: topics.append (key["title"]) topics = topics [1:len(topics)] # Summarizing the content: # setting attributes for to send to Smmry API link_for_smmry = 'https://en.wikipedia.org/wiki/' + title_w_no_space smmry_base_url = 'http://api.smmry.com/' #smmry_atts = {} #smmry_atts ['SM_URL'] = 'https://en.wikipedia.org/wiki/Guyana' #smmry_atts ['SM_API_KEY'] = '6F297A53E3' # represents your registered API key. # Optional, X represents the webpage to summarize. #smmry_atts ['SM_LENGTH'] = N # Optional, N represents the number of sentences returned, default is 7 #smmry_atts ['SM_KEYWORD_COUNT'] = N # Optional, N represents how many of the top keywords to return #smmry_atts ['SM_QUOTE_AVOID'] # Optional, summary will not include quotations #smmry_atts ['SM_WITH_BREAK'] # Optional, summary will contain string [BREAK] between each sentence api_key_link = '&SM_API_KEY=9B07893CAD&SM_URL=' api_lenght = 'SM_LENGTH=7&SM_WITH_BREAK' #print api_key_link api_link = smmry_base_url + api_lenght + api_key_link + link_for_smmry #smmry_resp = requests.get('http://api.smmry.com/&SM_API_KEY=6F297A53E3&SM_URL=https://en.wikipedia.org/wiki/Guyana') smmry_resp = requests.get(api_link) smmry_data = smmry_resp.json() content= '<p>Try adding another key word.</p><a style="color:white;" id="backbtn" href="#" onclick="myFunction()" >Go back.</a>' try: content = smmry_data['sm_api_content'] except: pass content_with_non_ascii = "" for word in content: if ord(word) < 128: content_with_non_ascii+=word else: content_with_non_ascii+= "?" if len(content_with_non_ascii) >0: content = content_with_non_ascii # replacing "[BREAK]"s with a new line while "[BREAK]" in content: length = len (content) break_position = content.find("[BREAK]") content = content [0:break_position] + "<br><br>" + content [break_position+7: length] print '<div id="all-cont-alt"><div class="select-nav"><div id="nav-top-main"><a id="backbtn" href="#" onclick="myFunction()" ><i style="float:left; position: relative;margin-left: 10px;top: 26px; color: #d8d8d8;" class= "fa fa-chevron-left fa-2x"></i></a><h1>Geddit</h1></div></div>' print '<div id="loaddddd"></div><div id="contentss">' print '<h1 id="user-title">' print user_title print "</h1>" print content print "</div></div>"
azimos/geddit
old/geddit-backend.py
Python
mit
3,469
/* Copyright (c) 2013 Chris Wraith Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.minorityhobbies.util; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; public class URLUtils { private URLUtils() { } /** * Useful for other classes which require a {@link URL} as a parameter. This * method allows a URL to be generated from a String. * * @param urlFilename * The filename to use for this URL. Can be anything. * @param content * The payload for this URL. This will be returned when you call * url.openStream() and read the data. * @return The URL backed by the specified content with the specified name. */ public static URL getStringBackedUrl(String urlFilename, String content) { return getStreamBackedUrl(urlFilename, new ByteArrayInputStream(content.getBytes())); } public static URL getStreamBackedUrl(String urlFilename, final InputStream content) { try { return new URL("bytes", "", 0, urlFilename, new URLStreamHandler() { @Override protected URLConnection openConnection(final URL url) throws IOException { return new URLConnection(url) { @Override public void connect() throws IOException { } @Override public InputStream getInputStream() throws IOException { return content; } }; } }); } catch (MalformedURLException e) { throw new RuntimeException(e); } } public static String readUrlData(URL url) throws IOException { URLConnection connection = url.openConnection(); InputStream in = connection.getInputStream(); if (in == null) { return null; } byte[] b = new byte[1024 * 64]; StringBuilder data = new StringBuilder(); for (int read = 0; (read = in.read(b)) > -1;) { data.append(new String(b, 0, read)); } return data.toString(); } }
jacksonps4/jutils
src/main/java/com/minorityhobbies/util/URLUtils.java
Java
mit
2,996
#region Usings using System; using Xunit; #endregion namespace Extend.Testing { public partial class StringExTest { [Fact] public void SubstringLeftSafeTest() { var actual = "testabc".SubstringLeftSafe( 4 ); Assert.Equal( "test", actual ); actual = "testabc".SubstringLeftSafe( 400 ); Assert.Equal( "testabc", actual ); actual = "".SubstringLeftSafe( 4 ); Assert.Equal( "", actual ); } [Fact] public void SubstringLeftSafeTest1() { var actual = "123test123".SubstringLeftSafe( 3, 4 ); Assert.Equal( "test", actual ); actual = "testabc".SubstringLeftSafe( 0, 400 ); Assert.Equal( "testabc", actual ); actual = "123tes".SubstringLeftSafe( 3, 4 ); Assert.Equal( "tes", actual ); actual = "".SubstringLeftSafe( 0, 4 ); Assert.Equal( "", actual ); actual = "".SubstringLeftSafe( 2, 4 ); Assert.Equal( "", actual ); } [Fact] public void SubstringLeftSafeTest1NullCheck() { // ReSharper disable once AssignNullToNotNullAttribute // ReSharper disable once ReturnValueOfPureMethodIsNotUsed Action test = () => StringEx.SubstringLeftSafe( null, 1, 5 ); Assert.Throws<ArgumentNullException>( test ); } [Fact] public void SubstringLeftSafeTestNullCheck() { // ReSharper disable once AssignNullToNotNullAttribute // ReSharper disable once ReturnValueOfPureMethodIsNotUsed Action test = () => StringEx.SubstringLeftSafe( null, 5 ); Assert.Throws<ArgumentNullException>( test ); } } }
DaveSenn/Extend
.Src/Extend.Testing/System.String/String.SubstringLeftSafe.Test.cs
C#
mit
1,814
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("PrintFirstAndLastName")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PrintFirstAndLastName")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("944423f7-a369-48ac-9b54-3b94dba73ae6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
BiserSirakov/TelerikAcademyHomeworks
C# - Part 1/Intro-Programming-Homework/04.PrintFirstAndLastName/Properties/AssemblyInfo.cs
C#
mit
1,418
// # Demo Particles 011 // Tracer entity: generation and functionality // [Run code](../../demo/particles-011.html) import * as scrawl from '../source/scrawl.js' import { reportSpeed } from './utilities.js'; // Get Scrawl-canvas to recognise and act on device pixel ratios greater than 1 scrawl.setIgnorePixelRatio(false); // #### Scene setup let canvas = scrawl.library.artefact.mycanvas; canvas.setBase({ backgroundColor: 'aliceblue', }); // Define some filters scrawl.makeFilter({ name: 'grayscale', method: 'grayscale', }).clone({ name: 'invert', method: 'invert', }); scrawl.makeFilter({ name: 'tint', method: 'tint', redInRed: 0.5, redInGreen: 1, redInBlue: 0.9, greenInRed: 0, greenInGreen: 0.3, greenInBlue: 0.8, blueInRed: 0.8, blueInGreen: 0.8, blueInBlue: 0.4, }); scrawl.makeFilter({ name: 'matrix', method: 'matrix', weights: [-1, -1, 0, -1, 1, 1, 0, 1, 1], }); // Create a Shape entity to act as a path for our Tracer entitys scrawl.makeShape({ name: 'my-arrow', pathDefinition: 'M266.2,703.1 h-178 L375.1,990 l287-286.9 H481.9 C507.4,365,683.4,91.9,911.8,25.5 877,15.4,840.9,10,803.9,10 525.1,10,295.5,313.4,266.2,703.1 z', start: ['center', 'center'], handle: ['center', 'center'], scale: 0.4, roll: -70, flipUpend: true, useAsPath: true, strokeStyle: 'gray', fillStyle: 'lavender', lineWidth: 8, method: 'fillThenDraw', bringToFrontOnDrag: false, }); // #### Particle physics animation scene // Tracer entitys don't have any color control built in; we need to create our own color factory let colorFactory = scrawl.makeColor({ name: 'tracer-3-color-factory', minimumColor: 'red', maximumColor: 'blue', }); // Create a Tracer entity // + Note that Tracers do not require a World object, cannot process Force objects, and cannot be connected together using Spring objects. scrawl.makeTracer({ name: 'trace-1', historyLength: 50, // We will delta-animate this Tracer alonbg the path of our Shape entity path: 'my-arrow', pathPosition: 0, lockTo: 'path', delta: { pathPosition: 0.002, }, artefact: scrawl.makeWheel({ name: 'burn-1', radius: 6, handle: ['center', 'center'], fillStyle: 'red', method: 'fill', visibility: false, noUserInteraction: true, noPositionDependencies: true, noFilters: true, noDeltaUpdates: true, }), // This Tracer will produce a 'dashed' effect, by displaying discrete ranges of its history stampAction: function (artefact, particle, host) { let history = particle.history, remaining, z, start; history.forEach((p, index) => { if (index < 10 || (index > 20 && index < 30) || index > 40) { [remaining, z, ...start] = p; artefact.simpleStamp(host, { start }); } }); }, // Clone the Tracer entity }).clone({ name: 'trace-2', pathPosition: 0.33, artefact: scrawl.library.artefact['burn-1'].clone({ name: 'burn-2', fillStyle: 'green', globalAlpha: 0.2, }), // Our second Tracer shows a 'tail-fade' effect stampAction: function (artefact, particle, host) { let history = particle.history, len = history.length, remaining, z, start; history.forEach((p, index) => { if (index % 3 === 0) { [remaining, z, ...start] = p; artefact.simpleStamp(host, { start, globalAlpha: (len - index) / len, }); } }); }, // Clone the second Tracer entity }).clone({ name: 'trace-3', pathPosition: 0.67, artefact: scrawl.library.artefact['burn-1'].clone({ name: 'burn-3', fillStyle: 'blue', }), // This Tracer varies its scale to create a 'teardrop' effect stampAction: function (artefact, particle, host) { let history = particle.history, len = history.length, remaining, z, start; history.forEach((p, index) => { [remaining, z, ...start] = p; let magicNumber = (len - index) / len; artefact.simpleStamp(host, { start, scale: magicNumber * 3, fillStyle: colorFactory.getRangeColor(magicNumber), }); }); }, }); // #### Scene animation // Function to display frames-per-second data, and other information relevant to the demo const report = reportSpeed('#reportmessage'); // Create the Display cycle animation scrawl.makeRender({ name: 'demo-animation', target: canvas, afterShow: report, }); // #### User interaction // Make the arrow draggable // + KNOWN BUG - the arrow is not draggable on first user mousedown, but is draggable afterwards scrawl.makeGroup({ name: 'my-draggable-group', }).addArtefacts('my-arrow'); scrawl.makeDragZone({ zone: canvas, collisionGroup: 'my-draggable-group', endOn: ['up', 'leave'], preventTouchDefaultWhenDragging: true, }); // Action user choice to apply a filter to a Tracer entity const filterChoice = function (e) { e.preventDefault(); e.returnValue = false; let val = e.target.value, entity = scrawl.library.entity['trace-2']; entity.clearFilters(); if (val) entity.addFilters(val); }; scrawl.addNativeListener(['input', 'change'], filterChoice, '#filter'); // @ts-expect-error document.querySelector('#filter').value = ''; // #### Development and testing console.log(scrawl.library);
KaliedaRik/Scrawl-canvas
demo/particles-011.js
JavaScript
mit
5,771
'use strict'; /** * Module dependencies. */ const express = require('express'); const session = require('express-session'); const compression = require('compression'); const morgan = require('morgan'); const cookieParser = require('cookie-parser'); const cookieSession = require('cookie-session'); const bodyParser = require('body-parser'); const methodOverride = require('method-override'); const upload = require('multer')(); const mongoStore = require('connect-mongo')(session); const flash = require('connect-flash'); const winston = require('winston'); const helpers = require('view-helpers'); const config = require('./'); const pkg = require('../package.json'); const env = process.env.NODE_ENV || 'development'; /** * Expose */ module.exports = function (app) { // Compression middleware (should be placed before express.static) app.use(compression({ threshold: 512 })); // Static files middleware app.use(express.static(config.root + '/public')); // Use winston on production let log = 'dev'; if (env !== 'development') { log = { stream: { write: message => winston.info(message) } }; } // Don't log during tests // Logging middleware if (env !== 'test') app.use(morgan(log)); // set views path, template engine and default layout app.set('views', config.root + '/app/views'); app.set('view engine', 'jade'); // expose package.json to views app.use(function (req, res, next) { res.locals.pkg = pkg; res.locals.env = env; next(); }); // bodyParser should be above methodOverride app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(upload.single('image')); app.use(methodOverride(function (req) { if (req.body && typeof req.body === 'object' && '_method' in req.body) { // look in urlencoded POST bodies and delete it var method = req.body._method; delete req.body._method; return method; } })); // CookieParser should be above session app.use(session({ resave: false, saveUninitialized: true, secret: pkg.name, cookie: { maxAge: 3600 * 24 * 365 * 1000 }, store: new mongoStore({ url: config.db, collection : 'sessions' }) })); app.use(cookieParser()); // app.use(cookieSession({ secret: 'accedotv' })); // connect flash for flash messages - should be declared after sessions app.use(flash()); // should be declared after session and flash app.use(helpers(pkg.name)); if (env === 'development') { app.locals.pretty = true; } };
kyue1005/accedotv-demo
config/express.js
JavaScript
mit
2,588
namespace Nancy.Serialization.ServiceStack { using System.Collections.Generic; using System.IO; using global::ServiceStack.Text; using Responses.Negotiation; public class ServiceStackJsonSerializer : ISerializer { /// <summary> /// Whether the serializer can serialize the content type /// </summary> /// <param name="mediaRange">Content type to serialise</param> /// <returns>True if supported, false otherwise</returns> public bool CanSerialize(MediaRange mediaRange) { return Helpers.IsJsonType(mediaRange); } /// <summary> /// Gets the list of extensions that the serializer can handle. /// </summary> /// <value>An <see cref="IEnumerable{T}"/> of extensions if any are available, otherwise an empty enumerable.</value> public IEnumerable<string> Extensions { get { yield return "json"; } } /// <summary> /// Serialize the given model with the given contentType /// </summary> /// <param name="mediaRange">Content type to serialize into</param> /// <param name="model">Model to serialize</param> /// <param name="outputStream">Output stream to serialize to</param> /// <returns>Serialised object</returns> public void Serialize<TModel>(MediaRange mediaRange, TModel model, Stream outputStream) { JsonSerializer.SerializeToStream(model, outputStream); } } }
NancyFx/Nancy.Serialization.ServiceStack
src/Nancy.Serialization.ServiceStack/ServiceStackJsonSerializer.cs
C#
mit
1,570
/* * Copyright (c) 2017-2019 by Botorabi. All rights reserved. * https://github.com/botorabi/Meet4Eat * * License: MIT License (MIT), read the LICENSE text in * main directory for more details. */ package net.m4e.update.rest.comm; import org.junit.jupiter.api.*; import javax.json.bind.*; import java.time.Instant; import static org.assertj.core.api.Assertions.assertThat; /** * @author boto * Date of creation March 12, 2018 */ public class UpdateCheckResultTest { private final String UPDATE_VERSION = "1.0.0"; private final String OS = "Win"; private final String URL = "https://update.org"; private final Long RELEASE_DATE = Instant.now().toEpochMilli(); private Jsonb json; @BeforeEach void setup() { json = JsonbBuilder.create(); } @Test void serialize() { UpdateCheckResult result = new UpdateCheckResult(); result.setUpdateVersion(UPDATE_VERSION); result.setOs(OS); result.setUrl(URL); result.setReleaseDate(RELEASE_DATE); String jsonString = json.toJson(result); assertThat(jsonString).contains("updateVersion"); assertThat(jsonString).contains("os"); assertThat(jsonString).contains("url"); assertThat(jsonString).contains("releaseDate"); } @Test void deserialize() { String jsonString = json.toJson(new UpdateCheckResult(UPDATE_VERSION, OS, URL, RELEASE_DATE)); UpdateCheckResult result = json.fromJson(jsonString, UpdateCheckResult.class); assertThat(result.getUpdateVersion()).isEqualTo(UPDATE_VERSION); assertThat(result.getOs()).isEqualTo(OS); assertThat(result.getUrl()).isEqualTo(URL); assertThat(result.getReleaseDate()).isEqualTo(RELEASE_DATE); } }
botorabi/Meet4Eat
src/test/java/net/m4e/update/rest/comm/UpdateCheckResultTest.java
Java
mit
1,790
#!/usr/bin/env python import os import sys from setuptools import setup os.system('make rst') try: readme = open('README.rst').read() except FileNotFoundError: readme = "" setup( name='leicaautomator', version='0.0.2', description='Automate scans on Leica SPX microscopes', long_description=readme, author='Arve Seljebu', author_email='arve.seljebu@gmail.com', url='https://github.com/arve0/leicaautomator', packages=[ 'leicaautomator', ], package_dir={'leicaautomator': 'leicaautomator'}, include_package_data=True, install_requires=[ 'scipy', 'numpy', 'matplotlib', 'scikit-image', 'leicascanningtemplate', 'leicacam', 'leicaexperiment', 'microscopestitching', 'dask[bag]', 'numba', ], license='MIT', zip_safe=False, keywords='leicaautomator', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', ], )
arve0/leicaautomator
setup.py
Python
mit
1,212
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /** * Class Jwt * jwt加密类 */ class Jwt { /** * @var int */ public static $leeway = 0; /** * @var null */ public static $timestamp = null; /** * @var array */ public static $supported_algs = array( 'HS256' => array('hash_hmac', 'SHA256'), 'HS512' => array('hash_hmac', 'SHA512'), 'HS384' => array('hash_hmac', 'SHA384'), 'RS256' => array('openssl', 'SHA256'), ); /** * @param $jwt * @param $key * @param array $allowed_algs * @return mixed */ public function decode($jwt, $key, $allowed_algs = array('HS256')) { $timestamp = is_null(static::$timestamp) ? time() : static::$timestamp; if (empty($key)) { throw new InvalidArgumentException('密钥不能为空');//Key may not be empty } if (!is_array($allowed_algs)) { throw new InvalidArgumentException('算法不允许');//Algorithm not allowed } $tks = explode('.', $jwt); if (count($tks) != 3) { throw new UnexpectedValueException('错误的段数');//Wrong number of segments } list($headb64, $bodyb64, $cryptob64) = $tks; if (null === ($header = static::jsonDecode(static::urlsafeB64Decode($headb64)))) { throw new UnexpectedValueException('无效的header编码');//Invalid encoding } if (null === $payload = static::jsonDecode(static::urlsafeB64Decode($bodyb64))) { throw new UnexpectedValueException('无效的claims编码');//Invalid claims encoding } $sig = static::urlsafeB64Decode($cryptob64); if (empty($header->alg)) { throw new UnexpectedValueException('alg是空的');//Empty algorithm } if (empty(static::$supported_algs[$header->alg])) { throw new UnexpectedValueException('算法不支持');//Algorithm not supported } if (!in_array($header->alg, $allowed_algs)) { throw new UnexpectedValueException('算法不允许');//Algorithm not allowed } if (is_array($key) || $key instanceof \ArrayAccess) { if (isset($header->kid)) { $key = $key[$header->kid]; } else { throw new UnexpectedValueException('"kid"空,无法查找正确的密钥');//"kid" empty, unable to lookup correct key } } // Check the signature 签名验证失败 if (!static::verify("$headb64.$bodyb64", $sig, $key, $header->alg)) { throw new UnexpectedValueException('签名验证失败');//Signature verification failed } // if (isset($payload->nbf) && $payload->nbf > ($timestamp + static::$leeway)) { // throw new UnexpectedValueException( // 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->nbf) // ); // } // // if (isset($payload->iat) && $payload->iat > ($timestamp + static::$leeway)) { // throw new UnexpectedValueException( // 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat) // ); // } // Check if this token has expired.过期令牌 if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) { throw new UnexpectedValueException('过期令牌');//Expired token } return $payload; } /** * @param $msg * @param $signature * @param $key * @param $alg * @return bool */ private static function verify($msg, $signature, $key, $alg) { if (empty(static::$supported_algs[$alg])) { throw new DomainException('Algorithm not supported'); } list($function, $algorithm) = static::$supported_algs[$alg]; switch($function) { case 'openssl': $success = openssl_verify($msg, $signature, $key, $algorithm); if (!$success) { throw new DomainException("OpenSSL unable to verify data: " . openssl_error_string()); } else { return $signature; } case 'hash_hmac': default: $hash = hash_hmac($algorithm, $msg, $key, true); if (function_exists('hash_equals')) { return hash_equals($signature, $hash); } $len = min(static::safeStrlen($signature), static::safeStrlen($hash)); $status = 0; for ($i = 0; $i < $len; $i++) { $status |= (ord($signature[$i]) ^ ord($hash[$i])); } $status |= (static::safeStrlen($signature) ^ static::safeStrlen($hash)); return ($status === 0); } } /** * @param $input * @return mixed */ public static function jsonDecode($input) { if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) { /** In PHP >=5.4.0, json_decode() accepts an options parameter, that allows you * to specify that large ints (like Steam Transaction IDs) should be treated as * strings, rather than the PHP default behaviour of converting them to floats. */ $obj = json_decode($input, false, 512, JSON_BIGINT_AS_STRING); } else { /** Not all servers will support that, however, so for older versions we must * manually detect large ints in the JSON string and quote them (thus converting *them to strings) before decoding, hence the preg_replace() call. */ $max_int_length = strlen((string) PHP_INT_MAX) - 1; $json_without_bigints = preg_replace('/:\s*(-?\d{'.$max_int_length.',})/', ': "$1"', $input); $obj = json_decode($json_without_bigints); } if (function_exists('json_last_error') && $errno = json_last_error()) { static::handleJsonError($errno); } elseif ($obj === null && $input !== 'null') { throw new DomainException('Null result with non-null input'); } return $obj; } /** * @param $input * @return bool|string */ public static function urlsafeB64Decode($input) { $remainder = strlen($input) % 4; if ($remainder) { $padlen = 4 - $remainder; $input .= str_repeat('=', $padlen); } return base64_decode(strtr($input, '-_', '+/')); } /** * @param $str * @return int */ private static function safeStrlen($str) { if (function_exists('mb_strlen')) { return mb_strlen($str, '8bit'); } return strlen($str); } /** * @param $payload * @param $key * @param string $alg * @param null $keyId * @param null $head * @return string */ public function encode($payload, $key, $alg = 'HS256', $keyId = null, $head = null) { $header = array('typ' => 'JWT', 'alg' => $alg); if ($keyId !== null) { $header['kid'] = $keyId; } if ( isset($head) && is_array($head) ) { $header = array_merge($head, $header); } $segments = array(); $segments[] = static::urlsafeB64Encode(static::jsonEncode($header)); $segments[] = static::urlsafeB64Encode(static::jsonEncode($payload)); $signing_input = implode('.', $segments); $signature = static::sign($signing_input, $key, $alg); $segments[] = static::urlsafeB64Encode($signature); return implode('.', $segments); } /** * @param $msg * @param $key * @param string $alg * @return string */ public static function sign($msg, $key, $alg = 'HS256') { if (empty(static::$supported_algs[$alg])) { throw new DomainException('Algorithm not supported'); } list($function, $algorithm) = static::$supported_algs[$alg]; switch($function) { case 'hash_hmac': return hash_hmac($algorithm, $msg, $key, true); case 'openssl': $signature = ''; $success = openssl_sign($msg, $signature, $key, $algorithm); if (!$success) { throw new DomainException("OpenSSL unable to sign data"); } else { return $signature; } } } /** * @param $input * @return string */ public static function jsonEncode($input) { $json = json_encode($input); if (function_exists('json_last_error') && $errno = json_last_error()) { static::handleJsonError($errno); } elseif ($json === 'null' && $input !== null) { throw new DomainException('Null result with non-null input'); } return $json; } /** * @param $input * @return mixed */ public static function urlsafeB64Encode($input) { return str_replace('=', '', strtr(base64_encode($input), '+/', '-_')); } /** * Helper method to create a JSON error. * @param int $errno An error number from json_last_error() * @return void */ private static function handleJsonError($errno) { $messages = array( JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON' ); throw new DomainException( isset($messages[$errno]) ? $messages[$errno] : 'Unknown JSON error: ' . $errno ); } }
wuanlife/wuanlife_api
application/libraries/Jwt.php
PHP
mit
9,916
<aside id="featured" class="body"> <article> <figure> <img src="img/logo/<?= $prj->slug ?>.png" alt="<?= sprintf(_('Project’s logo for %s'), $prj->name) ?>" /> </figure> <hgroup> <h2><?= $prj->name ?></h2> <h3><?= $prj->short ?></h3> </hgroup> <p><?= Malenki\Ruche\Util\RichText::getFormated($prj->description) ?></p> </article> </aside> <section id="content" class="body"> <?php if(count($mls)): ?> <ol id="posts-list" class="hfeed"> <?php foreach($mls as $m): ?> <li> <article class="hentry"> <header> <h2 class="entry-title"><a href="/project/<?= $prj->slug ?>/roadmap/<?= $m->id ?>" rel="bookmark" title="Permalink to this <?= $m->name ?>"><?= $m->name ?></a></h2> </header> <footer class="post-info"> <abbr class="published" title="<?= $m->ttd ?>"> <?= $m->ttd ?> </abbr> <!-- à faire --> <address class="vcard author"> Par <a class="url fn" href="#">Michel Petit</a> </address> </footer> <div class="entry-content"> <p><?= $m->description ?></p> </div> </article> </li> <?php endforeach; ?> </ol> <?php else: ?> <p><a href="#"><?= _('No milestone defined. You can create one now') ?></a></p> <?php endif; ?> </section> <section id="extras" class="body"> <!-- Cette liste correspondra aux événements, sera mise à jour via Ajax, une ligne par événement --> <div class="activityroll"> <h2>Activité</h2> <ul> <li><a href="#"><abbr class="published" title="2013-03-20T20:18:45+01:00">Aujourd’hui à 20h10</abbr> Révision <strong class="revision">[3045]</strong> par <strong class="author">Malenki</strong> <em>Corrige un test foireux</em></a></li> <li><a href="#"><abbr class="published" title="2013-03-20T20:18:45+01:00">Aujourd’hui à 18h20</abbr> Le ticket <strong class="ticket">#745</strong> a été créé par <strong class="author">Elvis</strong> <em>La génération de page échoue sur Windows Vista avec PHP 5.3</em></a></li> <li><a href="#"><abbr class="published" title="2013-03-20T20:18:45+01:00">Aujourd’hui à 14h30</abbr> Le ticket <strong class="ticket">#744</strong> a été créé par <strong class="author">Malenki</strong> <em>Créer de nouvelles entrées dans le fichier de configuration</em></a></li> <li><a href="#"><abbr class="published" title="2013-03-19T22:54:45+01:00">Hier à 22h54</abbr> Révision <strong class="revision">[3044]</strong> par <strong class="author">Elvis</strong> <em>Windows sucks, alors j’ai mis en place un hack…</em></a></li> <li><a href="#"><abbr class="published" title="2013-03-20T20:18:45+01:00">Hier à 20h02</abbr> Nouveau commentaire sur <strong class="ticket">#653</strong> par <strong class="author">Malenki</strong> <em>Serait-il possible d’utiliser la bibliothèque Yaml de Symfony pour…</em></a></li> </ul> </div> </section>
malenkiki/reine
templates/WebProjectsShow.php
PHP
mit
3,223
class Solution { public: vector<int> addNegabinary(vector<int>& arr1, vector<int>& arr2) { vector<int> result; int i = arr1.size() - 1, j = arr2.size() - 1, carry = 0; while (i >= 0 || j >= 0 || carry) { int s = carry; if (i >= 0) { s += arr1[i--]; } if (j >= 0) { s += arr2[j--]; } result.push_back(s & 1); carry = -(s >> 1); } while (result.size() > 1 && result.back() == 0) { result.pop_back(); } reverse(result.begin(), result.end()); return result; } };
jiadaizhao/LeetCode
1001-1100/1073-Adding Two Negabinary Numbers/1073-Adding Two Negabinary Numbers.cpp
C++
mit
660
"""Forms of the aps_bom app.""" from csv import DictReader from django import forms from django.core.urlresolvers import reverse from django.utils.translation import ugettext as __ from .models import BOM, BOMItem, CBOM, CBOMItem, EPN, IPN, Unit class BaseUploadForm(forms.ModelForm): csv_file = forms.FileField() def append_error(self, error_message, field="__all__"): if field in self.errors: self.errors[field].append(error_message) else: self.errors[field] = [error_message] def clean(self): cleaned_data = super(BaseUploadForm, self).clean() # don't do anything with the file if there are errors already if any(self.errors): return cleaned_data if self.Meta.model == CBOM: self.company = self.cleaned_data['customer'] # initiate the csv dictreader with the uploaded file temp_csv_file = self.files.get('csv_file') with open(temp_csv_file.temporary_file_path(), 'rU') as csv_file: self.reader = DictReader(csv_file) self.clean_lines() return cleaned_data def clean_lines(self): # update the fieldnames to match the ones on the model new_names = [] for fieldname in self.reader.fieldnames: new_names.append(fieldname.lower()) self.reader.fieldnames = new_names # iterate over the lines and clean the values self.clean_lines = [] for line_dict in self.reader: for key, value in line_dict.iteritems(): # strip blank spaces value = value.strip() line_dict[key] = value if key == 'consign': if value == '0': value = False else: value = True line_dict[key] = value if key == 'ipn': try: ipn = IPN.objects.get(code=value) except IPN.DoesNotExist: this_link = ( '<a href="{0}" target="_blank">{0}</a>'.format( reverse('admin:aps_bom_ipn_add'))) self.append_error(__( 'The ipn "{0}" does not exist.' ' Please create it first. {1}'.format( value, this_link))) except IPN.MultipleObjectsReturned: # TODO temporary workaround self.append_error(__( 'There are multiple entries for the IPN "{0}".' ' Please resolve this error before' ' uploading.'.format(value)), field='ipn') else: line_dict[key] = ipn if key == 'unit': try: unit = Unit.objects.get(code=value) except Unit.DoesNotExist: this_link = ( '<a href="{0}" target="_blank">{0}</a>'.format( reverse('admin:aps_bom_unit_add'))) self.append_error(__( 'The unit "{0}" does not exist.' ' Please create it first. {1}'.format( value, this_link))) else: line_dict[key] = unit if key == 'epn': try: epn = EPN.objects.get(epn=value, company=self.company) except EPN.DoesNotExist: epn = EPN.objects.create( description=line_dict.get('description'), epn=value, company=self.company) this_link = ( '<a href="{0}" target="_blank">{0}</a>'.format( reverse('admin:aps_bom_epn_change', args=(epn.id, )))) self.append_error(__( 'The EPN "{0}" does not exist.' ' Please visit {1} to update it and then' ' re-upload the file.'.format( value, this_link))) else: if epn.ipn is None or epn.cpn is None: this_link = ( '<a href="{0}" target="_blank">{0}</a>'.format( reverse('admin:aps_bom_epn_change', args=(epn.id, )))) self.append_error(__( 'The EPN "{0}" does not have all the' ' required data.' ' Please visit {1} to update it and then' ' re-upload the file.'.format( value, this_link))) else: line_dict[key] = epn if key == 'shape': pass line_dict.pop('description') if 'shape' in line_dict: line_dict.pop('shape') self.clean_lines.append(line_dict) return self.clean_lines class BOMUploadForm(BaseUploadForm): """Custom ModelForm, that handles the upload for BOM.csv files.""" def __init__(self, *args, **kwargs): super(BOMUploadForm, self).__init__(*args, **kwargs) self.fields['ipn'].required = True def save(self): instance = super(BOMUploadForm, self).save() for bomitemdict in self.clean_lines: bomitemdict.update({'bom': instance}) BOMItem.objects.create(**bomitemdict) return instance class Meta: model = BOM fields = ['description', 'ipn'] class CBOMUploadForm(BaseUploadForm): """Custom ModelForm, that handles the upload for cBOM.csv files.""" def save(self): instance = super(CBOMUploadForm, self).save() for cbomitemdict in self.clean_lines: cbomitemdict.update({'bom': instance}) CBOMItem.objects.create(**cbomitemdict) return instance class Meta: model = CBOM fields = [ 'customer', 'description', 'html_link', 'product', 'version_date']
bitmazk/django-aps-bom
aps_bom/forms.py
Python
mit
6,549
class RenameBillingPeriodReferences < ActiveRecord::Migration def up rename_column :billing_schedules, :billing_period_id, :billing_period_range_id rename_column :bills, :billing_period_id, :billing_period_range_id end def down rename_column :billing_schedules, :billing_period_range_id, :billing_period_id rename_column :bills, :billing_period_range_id, :billing_period_id end end
jbrowning/billy
db/migrate/20130305040107_rename_billing_period_references.rb
Ruby
mit
407
require "test_helper" class CrossCrusadeOverallTest < ActiveSupport::TestCase def test_recalc_with_no_series competition_count = Competition.count CrossCrusadeOverall.calculate! CrossCrusadeOverall.calculate!(2007) assert_equal(competition_count, Competition.count, "Should add no new Competition if there are no Cross Crusade events") end def test_recalc_with_one_event series = Series.create!(:name => "Cross Crusade") event = series.children.create!(:date => Date.new(2007, 10, 7), :name => "Cross Crusade #4") series.children.create!(:date => Date.new(2007, 10, 14)) series.children.create!(:date => Date.new(2007, 10, 21)) series.children.create!(:date => Date.new(2007, 10, 28)) series.children.create!(:date => Date.new(2007, 11, 5)) series.reload assert_equal(Date.new(2007, 10, 7), series.date, "Series date") cat_a = Category.find_or_create_by_name("Category A") cat_a_race = event.races.create!(:category => cat_a) cat_a_race.results.create!(:place => 1, :person => people(:weaver)) cat_a_race.results.create!(:place => 9, :person => people(:tonkin)) masters_35_plus_women = Category.find_or_create_by_name("Masters Women 35+") masters_race = event.races.create!(:category => masters_35_plus_women) masters_race.results.create!(:place => 15, :person => people(:alice)) masters_race.results.create!(:place => 19, :person => people(:molly)) # Previous year should be ignored previous_event = Series.create!(:name => "Cross Crusade").children.create!(:date => Date.new(2006), :name => "Cross Crusade #3") previous_event.races.create!(:category => cat_a).results.create!(:place => 6, :person => people(:weaver)) # Following year should be ignored following_event = Series.create!(:name => "Cross Crusade").children.create!(:date => Date.new(2008)) following_event.races.create!(:category => cat_a).results.create!(:place => 10, :person => people(:weaver)) CrossCrusadeOverall.calculate!(2007) assert_not_nil(series.overall(true), "Should add new Overall Competition child to parent Series") overall = series.overall assert_equal(18, overall.races.size, "Overall races") CrossCrusadeOverall.calculate!(2007) assert_not_nil(series.overall(true), "Should add new Overall Competition child to parent Series") overall = series.overall assert_equal(18, overall.races.size, "Overall races") assert(!overall.notes.blank?, "Should have notes about rules") cx_a_overall_race = overall.races.detect { |race| race.category == cat_a } assert_not_nil(cx_a_overall_race, "Should have Men A overall race") assert_equal(2, cx_a_overall_race.results.size, "Men A race results") cx_a_overall_race.results(true).sort! result = cx_a_overall_race.results.first assert_equal(false, result.preliminary?, "Preliminary?") assert_equal("1", result.place, "Men A first result place") assert_equal(26, result.points, "Men A first result points") assert_equal(people(:weaver), result.person, "Men A first result person") result = cx_a_overall_race.results.last assert_equal(false, result.preliminary?, "Preliminary?") assert_equal("2", result.place, "Men A second result place") assert_equal(10, result.points, "Men A second result points (double points for last result)") assert_equal(people(:tonkin), result.person, "Men A second result person") masters_35_plus_women_overall_race = overall.races.detect { |race| race.category == masters_35_plus_women } assert_not_nil(masters_35_plus_women_overall_race, "Should have Masters Women overall race") assert_equal(1, masters_35_plus_women_overall_race.results.size, "Masters Women race results") result = masters_35_plus_women_overall_race.results.first assert_equal(false, result.preliminary?, "Preliminary?") assert_equal("1", result.place, "Masters Women first result place") assert_equal(4, result.points, "Masters Women first result points (double points for last result)") assert_equal(people(:alice), result.person, "Masters Women first result person") end def test_many_results series = Series.create!(:name => "Cross Crusade") masters = Category.find_or_create_by_name("Masters 35+ A") category_a = Category.find_or_create_by_name("Category A") singlespeed = Category.find_or_create_by_name("Singlespeed") person = Person.create!(:name => "John Browning") event = series.children.create!(:date => Date.new(2008, 10, 5)) event.races.create!(:category => masters).results.create!(:place => 1, :person => person) event = series.children.create!(:date => Date.new(2008, 10, 12)) event.races.create!(:category => masters).results.create!(:place => 1, :person => person) event = series.children.create!(:date => Date.new(2008, 10, 19)) event.races.create!(:category => masters).results.create!(:place => 2, :person => person) event.races.create!(:category => category_a).results.create!(:place => 4, :person => person) event.races.create!(:category => singlespeed).results.create!(:place => 5, :person => person) event = series.children.create!(:date => Date.new(2008, 10, 26)) event.races.create!(:category => masters).results.create!(:place => 1, :person => person) event = series.children.create!(:date => Date.new(2008, 11, 2)) event.races.create!(:category => masters).results.create!(:place => 2, :person => person) event = series.children.create!(:date => Date.new(2008, 11, 9)) event.races.create!(:category => masters).results.create!(:place => 1, :person => person) event.races.create!(:category => category_a).results.create!(:place => 20, :person => person) event.races.create!(:category => singlespeed).results.create!(:place => 12, :person => person) event = series.children.create!(:date => Date.new(2008, 11, 10)) event.races.create!(:category => masters).results.create!(:place => 1, :person => person) event = series.children.create!(:date => Date.new(2008, 11, 17)) event.races.create!(:category => masters).results.create!(:place => 3, :person => person) event.races.create!(:category => category_a).results.create!(:place => 20, :person => person) CrossCrusadeOverall.calculate!(2008) masters_overall_race = series.overall.races.detect { |race| race.category == masters } assert_not_nil(masters_overall_race, "Should have Masters overall race") masters_overall_race.results(true).sort! result = masters_overall_race.results.first assert_equal(false, result.preliminary?, "Preliminary?") assert_equal("1", result.place, "place") assert_equal(6, result.scores.size, "Scores") assert_equal(26 + 26 + 0 + 26 + 0 + 26 + 26 + (16 * 2), result.points, "points") assert_equal(person, result.person, "person") category_a_overall_race = series.overall.races.detect { |race| race.category == category_a } assert_not_nil(category_a_overall_race, "Should have Category A overall race") category_a_overall_race.results(true).sort! result = category_a_overall_race.results.first assert_equal(false, result.preliminary?, "Preliminary?") assert_equal("1", result.place, "place") assert_equal(1, result.scores.size, "Scores") assert_equal(15, result.points, "points") assert_equal(person, result.person, "person") singlespeed_overall_race = series.overall.races.detect { |race| race.category == singlespeed } assert_not_nil(singlespeed_overall_race, "Should have Singlespeed overall race") assert(singlespeed_overall_race.results.empty?, "Should not have any singlespeed results") end def test_preliminary_results_after_event_minimum series = Series.create!(:name => "Cross Crusade") series.children.create!(:date => Date.new(2007, 10, 7)) series.children.create!(:date => Date.new(2007, 10, 14)) series.children.create!(:date => Date.new(2007, 10, 21)) series.children.create!(:date => Date.new(2007, 10, 28)) series.children.create!(:date => Date.new(2007, 11, 5)) cat_a = Category.find_or_create_by_name("Category A") cat_a_race = series.children[0].races.create!(:category => cat_a) cat_a_race.results.create!(:place => 1, :person => people(:weaver)) cat_a_race.results.create!(:place => 2, :person => people(:tonkin)) cat_a_race = series.children[1].races.create!(:category => cat_a) cat_a_race.results.create!(:place => 43, :person => people(:weaver)) cat_a_race = series.children[2].races.create!(:category => cat_a) cat_a_race.results.create!(:place => 1, :person => people(:weaver)) cat_a_race = series.children[3].races.create!(:category => cat_a) cat_a_race.results.create!(:place => 8, :person => people(:tonkin)) CrossCrusadeOverall.calculate!(2007) category_a_overall_race = series.overall.races.detect { |race| race.category == cat_a } assert_not_nil(category_a_overall_race, "Should have Category A overall race") category_a_overall_race.results(true).sort! result = category_a_overall_race.results.first assert_equal(false, result.preliminary?, "Weaver did three races. His result should not be preliminary") result = category_a_overall_race.results.last assert_equal(true, result.preliminary?, "Tonkin did only two races. His result should be preliminary") end def test_raced_minimum_events_boundaries series = Series.create!(:name => "Cross Crusade") cat_a = Category.find_or_create_by_name("Category A") molly = people(:molly) event = series.children.create!(:date => Date.new(2007, 10, 7)) # Molly does three races in different categories cat_a_race = event.races.create!(:category => cat_a) cat_a_race.results.create!(:place => 6, :person => molly) single_speed_race = event.races.create!(:category => categories(:single_speed)) single_speed_race.results.create!(:place => 8, :person => molly) masters_women_race = event.races.create!(:category => categories(:masters_women)) masters_women_race.results.create!(:place => 10, :person => molly) cat_a_race.results.create!(:place => 17, :person => people(:alice)) CrossCrusadeOverall.calculate!(2007) category_a_overall_race = series.overall.races.detect { |race| race.category == cat_a } assert(!series.overall.raced_minimum_events?(molly, category_a_overall_race), "One event. No people have raced minimum") assert(!series.overall.raced_minimum_events?(people(:alice), category_a_overall_race), "One event. No people have raced minimum") event = series.children.create!(:date => Date.new(2007, 10, 14)) cat_a_race = event.races.create!(:category => cat_a) cat_a_race.results.create!(:place => 14, :person => molly) cat_a_race.results.create!(:place => 6, :person => people(:alice)) CrossCrusadeOverall.calculate!(2007) category_a_overall_race = series.overall.races.detect { |race| race.category == cat_a } assert(!series.overall.raced_minimum_events?(molly, category_a_overall_race), "Two events. No people have raced minimum") assert(!series.overall.raced_minimum_events?(people(:alice), category_a_overall_race), "Two events. No people have raced minimum") event = series.children.create!(:date => Date.new(2007, 10, 21)) cat_a_race = event.races.create!(:category => cat_a) cat_a_race.results.create!(:place => "DNF", :person => molly) single_speed_race = event.races.create!(:category => categories(:single_speed)) single_speed_race.results.create!(:place => 8, :person => people(:alice)) CrossCrusadeOverall.calculate!(2007) category_a_overall_race = series.overall(true).races.detect { |race| race.category == cat_a } assert(series.overall.raced_minimum_events?(molly, category_a_overall_race), "Three events. Molly has raced minimum") assert(!series.overall.raced_minimum_events?(people(:alice), category_a_overall_race), "Three events. Alice has not raced minimum") event = series.children.create!(:date => Date.new(2007, 10, 28)) cat_a_race = event.races.create!(:category => cat_a) CrossCrusadeOverall.calculate!(2007) category_a_overall_race = series.overall.races.detect { |race| race.category == cat_a } assert(series.overall.raced_minimum_events?(molly, category_a_overall_race), "Four events. Molly has raced minimum") assert(!series.overall.raced_minimum_events?(people(:alice), category_a_overall_race), "Four events. Alice has not raced minimum") end def test_minimum_events_should_handle_results_without_person series = Series.create!(:name => "Cross Crusade") cat_a = Category.find_or_create_by_name("Category A") event = series.children.create!(:date => Date.new(2007, 10, 7)) cat_a_race = event.races.create!(:category => cat_a) cat_a_race.results.create!(:place => 17) CrossCrusadeOverall.calculate!(2007) category_a_overall_race = series.overall.races.detect { |race| race.category == cat_a } assert(!series.overall.raced_minimum_events?(nil, category_a_overall_race), "Nil person should never have mnimum events") end def test_count_six_best_results series = Series.create!(:name => "Cross Crusade") category_a = Category.find_or_create_by_name("Category A") person = Person.create!(:name => "Kevin Hulick") date = Date.new(2008, 10, 19) [8, 3, 10, 7, 8, 7, 8].each do |place| series.children.create!(:date => date).races.create!(:category => category_a).results.create!(:place => place, :person => person) date = date + 7 end # Simulate 7 of 8 events. Last, double-point event still in future series.children.create!(:date => date).races.create!(:category => category_a) CrossCrusadeOverall.calculate!(2008) category_a_overall_race = series.overall.races.detect { |race| race.category == category_a } assert_not_nil(category_a_overall_race, "Should have Category A overall race") category_a_overall_race.results(true).sort! result = category_a_overall_race.results.first assert_equal(6, result.scores.size, "Scores") assert_equal(16 + 12 + 12 + 11 + 11 + 11, result.points, "points") end def test_choose_best_results_by_points_not_place series = Series.create!(:name => "Cross Crusade") category_a = Category.find_or_create_by_name("Category A") person = Person.create!(:name => "Kevin Hulick") date = Date.new(2008, 10, 19) [8, 8, 8, 7, 6, 8, 7, 9].each do |place| series.children.create!(:date => date).races.create!(:category => category_a).results.create!(:place => place, :person => person) date = date + 7 end CrossCrusadeOverall.calculate!(2008) category_a_overall_race = series.overall.races.detect { |race| race.category == category_a } assert_not_nil(category_a_overall_race, "Should have Category A overall race") category_a_overall_race.results(true).sort! result = category_a_overall_race.results.first assert_equal(6, result.scores.size, "Scores") assert_equal(11 + 12 + 13 + 11 + 12 + 20, result.points, "points") end def test_ensure_dnf_sorted_correctly series = Series.create!(:name => "Cross Crusade") category_a = Category.find_or_create_by_name("Category A") person = Person.create!(:name => "Kevin Hulick") date = Date.new(2008, 10, 19) [8, 3, 10, "DNF", 8, 7, 8].each do |place| series.children.create!(:date => date).races.create!(:category => category_a).results.create!(:place => place, :person => person) date = date + 7 end # Simulate 7 of 8 events. Last, double-point, event, still in future series.children.create!(:date => date).races.create!(:category => category_a) CrossCrusadeOverall.calculate!(2008) category_a_overall_race = series.overall.races.detect { |race| race.category == category_a } assert_not_nil(category_a_overall_race, "Should have Category A overall race") category_a_overall_race.results(true).sort! result = category_a_overall_race.results.first assert_equal(6, result.scores.size, "Scores") assert_equal(16 + 12 + 11 + 11 + 11 + 9, result.points, "points") end def test_ignore_age_graded_bar series = Series.create!(:name => "Cross Crusade") cat_a = Category.find_or_create_by_name("Category A") series.children.create!(:date => Date.new(2007, 10, 7)) event = series.children.create!(:date => Date.new(2007, 10, 14)) cat_a_race = event.races.create!(:category => cat_a) cat_a_race.results.create!(:place => 17, :person => people(:alice)) age_graded_race = AgeGradedBar.create!(:name => "Age Graded Results for BAR/Championships").races.create!(:category => cat_a) age_graded_race.results.create!(:place => 1, :person => people(:alice)) CrossCrusadeOverall.calculate!(2007) category_a_overall_race = series.overall.races.detect { |race| race.category == cat_a } assert_equal(1, category_a_overall_race.results.size, "Cat A results") assert_equal(1, category_a_overall_race.results.first.scores.size, "Should ignore age-graded BAR") end def test_should_not_count_for_bar_nor_ironman series = Series.create!(:name => "Cross Crusade") category_a = Category.find_or_create_by_name("Category A") series.children.create!(:date => Date.new(2008)).races.create!(:category => category_a).results.create!(:place => "4", :person => people(:tonkin)) CrossCrusadeOverall.calculate!(2008) series.reload overall_results = series.overall assert(!overall_results.ironman, "Ironman") assert_equal(0, overall_results.bar_points, "BAR points") category_a_overall_race = overall_results.races.detect { |race| race.category == category_a } assert_equal(0, category_a_overall_race.bar_points, "Race BAR points") end end
alpendergrass/montanacycling-racing_on_rails
test/unit/competitions/cross_crusade_overall_test.rb
Ruby
mit
17,950
package api import ( "time" "github.com/boilingrip/boiling-api/db" ) type Release struct { ID int `json:"id"` ReleaseGroup ReleaseGroup `json:"release_group"` Edition *string `json:"edition,omitempty"` Medium string `json:"medium"` ReleaseDate time.Time `json:"release_date"` CatalogueNumber *string `json:"catalogue_number,omitempty"` //RecordLabel RecordLabel //Torrents []Torrent Added time.Time `json:"added"` AddedBy BaseUser `json:"added_by"` Original bool `json:"original"` Tags []string `json:"tags,omitempty"` // Properties lists "official" properties of releases, for example // "LossyMasterApproved", to be set by trusted users or staff. Properties map[string]string `json:"properties"` } func (a *API) releaseFromDBRelease(dbR *db.Release) Release { r := Release{ ID: dbR.ID, Medium: a.c.media.MustReverseLookUp(dbR.Medium), ReleaseDate: dbR.ReleaseDate, Added: dbR.Added, AddedBy: baseUserFromDBUser(dbR.AddedBy), Original: dbR.Original, Tags: dbR.Tags, Properties: dbR.Properties, } if dbR.Edition.Valid { r.Edition = &dbR.Edition.String } if dbR.CatalogueNumber.Valid { r.CatalogueNumber = &dbR.CatalogueNumber.String } return r } type ReleaseResponse struct { Release Release `json:"release"` }
boilingrip/boiling-api
api/release.go
GO
mit
1,389
<?php namespace SlowDB\Bundle\ApiBundle\Controller; use FOS\RestBundle\Controller\Annotations as Rest, FOS\RestBundle\Controller\FOSRestController, FOS\RestBundle\Request\ParamFetcher; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Component\HttpFoundation\JsonResponse; /** * @author Keith Kirk <keith@kmfk.io> * * @Route("/tables") */ class DatabaseController extends FOSRestController { /** * Searches the Collection for matching keys * * @Rest\Get("/search", name="database_search") * * @param Request $request The request object * @param string $collection The collection name * * @return JsonResponse */ public function queryAction(Request $request, $collection) { $slowdb = $this->get('slowdb'); $query = $request->get('q', null); if (is_null($query)) { return new JsonResponse(['error' => 'Must include a Query parameter, ex: ?q={some text}'], 400); } $collections = $slowdb->all(); $results = []; foreach ($collections as $collection) { $results[$collection] = $slowdb->{$collection}->query($query); } return new JsonResponse($results, 200); } /** * Returns a list of all available Collections * * @Rest\Get("", name="database_all") * * @return JsonResponse */ public function listAction() { $response = $this->get('slowdb')->all(); return new JsonResponse($response); } /** * Drops all the Collections * * @Rest\Delete("", name="database_drop") * * @return JsonResponse */ public function dropAllAction() { $response = $this->get('slowdb')->dropAll(); return new JsonResponse('', 204); } }
kmfk/slowdb-api
src/Controller/DatabaseController.php
PHP
mit
1,837
<?php // require composer autoloader for loading classes require realpath(__DIR__ . '/../vendor/autoload.php');
slimdash/payum-payeezy
tests/bootstrap.php
PHP
mit
112
var LinkedInStrategy = require('passport-linkedin-oauth2').Strategy, linkOAuthProfile = require('./helpers').linkOAuthProfile, OAuth2 = require('oauth').OAuth2, crypto = require('crypto'); function preprocessProfile(linkedInProfile){ var skills = []; if(linkedInProfile.skills){ skills = linkedInProfile.skills.values.map(function(value){ return value.skill.name; }); } return { educations: linkedInProfile.educations && linkedInProfile.educations.values || [], positions: linkedInProfile.positions && linkedInProfile.positions.values || [], skills: skills }; } exports.name = 'kabam-core-strategies-linkedin'; exports.strategy = function (core) { if (!core.config.PASSPORT || !core.config.PASSPORT.LINKEDIN_API_KEY || !core.config.PASSPORT.LINKEDIN_SECRET_KEY){ return; } var profileURL = 'https://api.linkedin.com/v1/people/~:(skills,educations,positions)', oauth2 = new OAuth2( core.config.PASSPORT.LINKEDIN_API_KEY, core.config.PASSPORT.LINKEDIN_SECRET_KEY, '', 'https://www.linkedin.com/uas/oauth2/authorization', 'https://www.linkedin.com/uas/oauth2/accessToken', {'x-li-format': 'json'} ); return new LinkedInStrategy({ clientID: core.config.PASSPORT.LINKEDIN_API_KEY, clientSecret: core.config.PASSPORT.LINKEDIN_SECRET_KEY, scope: ['r_fullprofile', 'r_emailaddress'], callbackURL: core.config.HOST_URL + 'auth/linkedin/callback', passReqToCallback: true, stateless: true }, function (request, accessToken, refreshToken, profile, done) { linkOAuthProfile(core, 'linkedin', request, profile, true, function(err, user, created){ if(err){return done(err);} // if we already had this user we shouldn't rewrite their profile, so we skip this step if(!created){return done(null, user);} // get required profile info and populate user profile oauth2.setAccessTokenName('oauth2_access_token'); oauth2.get(profileURL, accessToken, function(err, body/*, res*/){ if(err){return done(new Error('LinkedIn error: ' + JSON.stringify(err)));} try { user.profile = preprocessProfile(JSON.parse(body)); } catch(err) { return done(err); } user.markModified('profile'); user.save(function(err){ done(err, user); }); }); }); }); }; exports.routes = function (core) { if (!core.config.PASSPORT || !core.config.PASSPORT.LINKEDIN_API_KEY || !core.config.PASSPORT.LINKEDIN_SECRET_KEY){ return; } var state = crypto.createHash('md5').update(core.config.SECRET).digest('hex').toString(); core.app.get('/auth/linkedin', core.passport.authenticate('linkedin', {state: state})); core.app.get('/auth/linkedin/callback', core.passport.authenticate('linkedin', { successRedirect: '/auth/success', failureRedirect: '/auth/failure' })); }; // TODO: test all this stuff somehow
muhammadghazali/kabam-kernel
core/strategies/linkedin.js
JavaScript
mit
2,946
const deepCopy = require('./deep-copy'); const sorting = require('./sort'); /* Sorts an array of objects by two keys ** dir = 'asc' yields sort order A, B, C or 1, 2, 3 ** dir = 'des' yields sort order C, B, A or 3, 2, 1 ** type = 'character' for character sorting, type = 'numeric' or 'bool' ** for boolean sorting for numeric sorting. */ const arrSortByTwoKeys = (arr, key1, key2, dir = 'asc', type1 = 'character', type2 = 'character') => { /* Make sure input variable is an array of objects, and that keys are defined. ** if not, simply return whatever arr is. */ if ( !Array.isArray(arr) || typeof arr[0] !== 'object' || !key1 || !key2 ) { return arr; } const multiplier = dir === 'des' ? -1 : 1; const sortArray = deepCopy(arr); const sortFunc1 = sorting[type1]; const sortFunc2 = sorting[type2]; sortArray.sort((a, b) => { const sort1 = multiplier * sortFunc1(a[key1], b[key1]); const sort2 = multiplier * sortFunc2(a[key2], b[key2]); if (sort1 < 0) { return -1; } if ( sort1 === 0 && sort2 < 0 ) { return -1; } if ( sort1 === 0 && sort2 === 0 ) { return 0; } return 1; }); return sortArray; }; module.exports = arrSortByTwoKeys;
knightjdr/gene-info
database/helpers/arr-sort-by-two-keys.js
JavaScript
mit
1,260
require "test_helper" module RuleIo class CustomizationTest < Minitest::Test def setup stub_request(:get, /#{RuleIo.base_url}\/customizations\?apikey=*/) .to_return(status: 200, body: fixture("customizations.json")) end def test_all_returns_customizations customizations = Customization.all assert_kind_of Array, customizations assert_equal 1, customizations.length customizations.each do |c| assert_kind_of Customization, c end end def test_initialization customizations = Customization.all assert_equal 1, customizations.first.id assert_equal "Address", customizations.first.name end def test_fields customizations = Customization.all assert_kind_of Array, customizations.first.fields assert_equal 3, customizations.first.fields.length assert_kind_of Customization::Field, customizations.first.fields.first end end end
varvet/rule_io
test/rule_io/customization_test.rb
Ruby
mit
955
package es.carm.mydom.filters.utils; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.apache.naming.resources.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Dispatcher { public static void sendResourceContent(Resource resource,HttpServletResponse response){ try{ OutputStream o = response.getOutputStream(); o.write(resource.getContent()); } catch (Exception e){ e.printStackTrace(); } } public static void sendResourceStream(String fileName, Resource resource,HttpServletResponse response){ try{ //o.write(resource.getContent()); //detecto la longitud InputStream in = resource.streamContent(); System.out.println("Send resource stream: fname="+fileName+" available="+in.available()); response.setContentLength(in.available()); OutputStream o = response.getOutputStream(); int b = 1; byte[] buff = new byte[16384]; while (b>0){ b = in.read(buff); if (b>0) o.write(buff,0,b); } in.close(); } catch (Exception e){ e.printStackTrace(); } } public static void sendString(String text,String charset,HttpServletResponse response){ sendString(text,"text/html",charset,response); } public static void sendString(String text,String contentType, String charset,HttpServletResponse response){ try{ response.setContentType(contentType); response.setCharacterEncoding(charset); OutputStream o = response.getOutputStream(); o.write(text.getBytes(charset)); } catch (Exception e){ e.printStackTrace(); } } public static void sendArrayString(List<String> text,String charset,HttpServletResponse response){ sendArrayString(text,"text/html",charset,response); } public static void sendArrayString(List<String> text,String contentType, String charset,HttpServletResponse response){ try{ response.setContentType(contentType); response.setCharacterEncoding(charset); OutputStream o = response.getOutputStream(); for(String item:text) o.write(item.getBytes(charset)); } catch (Exception e){ e.printStackTrace(); } } }
maltimor/mydom-server
src/main/java/es/carm/mydom/filters/utils/Dispatcher.java
Java
mit
2,187
# coding: utf-8 from django.db import models from django.utils import timezone from .cores import OssManager _oss_manager = OssManager() class StsToken(models.Model): arn = models.CharField(max_length=500) assumed_role_id = models.CharField(max_length=500) access_key_id = models.CharField(max_length=500) access_key_secret = models.CharField(max_length=500) security_token = models.TextField() purpose = models.CharField(max_length=100) expiration = models.DateTimeField() manager = _oss_manager class Meta: db_table = 'sts_token' @property def is_effective(self): return timezone.now() <= self.expiration
zhaowenxiang/chisch
oss/models.py
Python
mit
677
/* * (C) Copyright 2015 Richard Greenlees * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * 1) The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package com.jumi.scene.objects; import com.jumi.data.Vector3; import java.util.ArrayList; /** * * @author RGreenlees */ public class JUMIBone { private int[] indices = new int[0]; private float[] weights = new float[0]; private float[] transforms = new float[0]; private float[] transformLinks = new float[0]; private JUMIBone parent; private final ArrayList<JUMIBone> children = new ArrayList(); private Vector3 localTranslation = new Vector3(); private Vector3 localRotation = new Vector3(); private Vector3 localScaling = new Vector3(); private String name; public JUMIBone() { super(); } public JUMIBone(String inName) { name = inName; } public JUMIBone(String inName, int[] inIndices, float[] inWeights, float[] inTransforms, float[] inTransformLinks, Vector3 inTranslation, Vector3 inRotation, Vector3 inScaling) { name = inName; indices = inIndices; weights = inWeights; transforms = inTransforms; transformLinks = inTransformLinks; localTranslation = inTranslation; localRotation = inRotation; localScaling = inScaling; } public Vector3 getLocalScaling() { return localScaling; } public JUMIBone(String inName, Vector3 inTranslation, Vector3 inRotation, Vector3 inScaling) { name = inName; localTranslation = inTranslation; localRotation = inRotation; localScaling = inScaling; } public Vector3 getLocalTranslation() { return localTranslation; } public Vector3 getLocalRotation() { return localRotation; } public float[] getTransforms() { return transforms; } public float[] getTransformLinks() { return transformLinks; } public void setParent(JUMIBone newParent) { parent = newParent; } public void addChild(JUMIBone newChild) { children.add(newChild); newChild.setParent(this); } public void removeChild(JUMIBone childToRemove) { children.remove(childToRemove); childToRemove.setParent(null); } public void removeChild(String childName) { int index = -1; for (JUMIBone a : children) { if (a.name.equals(childName)) { index = children.indexOf(a); break; } } if (index > -1) { children.remove(index); } } public String getName() { return name; } public void setName(String newName) { name = newName; } public int[] getVertexIndices() { return indices; } public float[] getWeights() { return weights; } public JUMIBone getParent() { return parent; } public JUMIBone[] getChildren() { return children.toArray(new JUMIBone[children.size()]); } public JUMIBone[] getDescendants() { ArrayList<JUMIBone> allBones = new ArrayList(); addDescendantsToList(allBones); JUMIBone[] result = new JUMIBone[allBones.size()]; allBones.toArray(result); return result; } public JUMIBone[] getFullSkeleton() { ArrayList<JUMIBone> allBones = new ArrayList(); JUMIBone root = getRoot(); allBones.add(root); root.addDescendantsToList(allBones); JUMIBone[] result = new JUMIBone[allBones.size()]; allBones.toArray(result); return result; } public JUMIBone getRoot() { if (parent == null) { return this; } else { return parent.getRoot(); } } private void addDescendantsToList(ArrayList<JUMIBone> boneList) { for (JUMIBone a : children) { boneList.add(a); a.addDescendantsToList(boneList); } } public JUMIBone findDescendantByName(String inName) { for (JUMIBone a : children) { if (a.getName().equals(inName)) { return a; } a.findDescendantByName(inName); } return null; } public String toString() { return "JUMIBone:\n\tName: " + name + "\n\tParent: " + ((parent != null) ? parent.name : "None") + "\n\tChildren: " + children.size() + "\n\tDescendants: " + getDescendants().length; } }
RGreenlees/JUMI-Java-Model-Importer
src/com/jumi/scene/objects/JUMIBone.java
Java
mit
5,488
import assert from 'assert'; import proxyquire from 'proxyquire'; import sinon from 'sinon'; import sinonStubPromise from 'sinon-stub-promise'; import mockMbaasClient from './mocks/fhMbaasClientMock'; sinonStubPromise(sinon); const appEnvVarsStub = sinon.stub(); const primaryNodeStub = sinon.stub().returnsPromise(); const dbConnectionStub = sinon.stub().returnsPromise(); const feedhenryMbaasType = proxyquire('../lib/mbaas/types/feedhenry', { 'fh-mbaas-client': { MbaasClient: mockMbaasClient(appEnvVarsStub, primaryNodeStub) } }); const openshiftMbaasType = proxyquire('../lib/mbaas/types/openshift', { 'fh-mbaas-client': { MbaasClient: mockMbaasClient(appEnvVarsStub, null, dbConnectionStub) } }); const MockMbaaS = proxyquire('../lib/mbaas', { './types': { feedhenry: feedhenryMbaasType, openshift: openshiftMbaasType } }).MBaaS; function getMockReq() { return { params: { domain: 'test-domain', envId: 101, appGuid: '12345' }, log: { debug: function() {} } }; } function getOptions(mbaasType) { return { mbaasType: mbaasType, auth: { secret: '123456' }, mbaas: { url: 'https://api.host.com', password: 'pass', username: 'user' }, ditch: { user: 'user', password: 'pass', host: '', port: '', database: 'dbname' } }; } export function getDedicatedDbConnectionConf(done) { var expectedUrl = 'dedicatedUrl'; appEnvVarsStub.yields(null, { env: { FH_MONGODB_CONN_URL: expectedUrl } }); new MockMbaaS(getOptions('feedhenry')) .getMongoConf(getMockReq()) .then(conf => { assert.ok(conf.__dbperapp); assert.equal(conf.connectionUrl, expectedUrl); done(); }) .catch(done); } export function getSharedDbConnectionConf(done) { var expectedUrl = 'mongodb://user:pass@primaryNodeHost:primaryNodePort/dbname'; appEnvVarsStub.yields(null, {}); primaryNodeStub.yields(null, { host: 'primaryNodeHost', port: 'primaryNodePort' }); new MockMbaaS(getOptions('feedhenry')) .getMongoConf(getMockReq()) .then(conf => { assert.ok(!conf.__dbperapp); assert.equal(conf.connectionUrl, expectedUrl); done(); }) .catch(done); } export function appEnvVarFail(done) { appEnvVarsStub.yields({}); new MockMbaaS(getOptions('feedhenry')) .getMongoConf(getMockReq()) .then(conf => { assert.ok(!conf); done(); }) .catch(err => { assert.ok(err); done(); }); } export function mongoprimaryNodeFail(done) { appEnvVarsStub.yields(null, {}); primaryNodeStub.yields({}); new MockMbaaS(getOptions('feedhenry')) .getMongoConf(getMockReq()) .then(conf => { assert.ok(!conf); done(); }) .catch(err => { assert.ok(err); done(); }); } export function mongoOpenshift(done) { var expectedUrl = 'mongodb://user:pass@openshiftmongohost:27017/dbname'; appEnvVarsStub.yields(null, { env: { FH_MBAAS_ENV_ACCESS_KEY: '12345', FH_APP_API_KEY: '12345' } }); dbConnectionStub.yields(null, {url: expectedUrl}); new MockMbaaS(getOptions('openshift')) .getMongoConf(getMockReq()) .then(conf => { assert.ok(conf.__dbperapp); assert.equal(conf.connectionUrl, expectedUrl); done(); }) .catch(done); }
feedhenry/fh-dataman
src/middleware/dbConnection/test/mbaas_test.js
JavaScript
mit
3,372
import React, { Component, PropTypes } from 'react' import { Router } from 'react-router' import { Provider } from 'react-redux' import routes from 'routes' class AppContainer extends Component { static propTypes = { store : PropTypes.object.isRequired, history : PropTypes.object.isRequired } shouldComponentUpdate() { return false } render() { const { history, store } = this.props return ( <Provider store={store}> <Router history={history} children={routes} /> </Provider> ) } } export default AppContainer
bartushk/memmi
client-side/src/containers/AppContainer.js
JavaScript
mit
639
<?php /* Safe sample input : get the field userData from the variable $_GET via an object sanitize : use of ternary condition construction : concatenation with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ class Input{ private $input; public function getInput(){ return $this->input; } public function __construct(){ $this->input = $_GET['UserData'] ; } } $temp = new Input(); $tainted = $temp->getInput(); $tainted = $tainted == 'safe1' ? 'safe1' : 'safe2'; $query = "(&(objectCategory=person)(objectClass=user)(cn='". $tainted . "'))"; $ds=ldap_connect("localhost"); $r=ldap_bind($ds); $sr=ldap_search($ds,"o=My Company, c=US", $query); ldap_close($ds); ?>
stivalet/PHP-Vulnerability-test-suite
Injection/CWE_90/safe/CWE_90__object-classicGet__ternary_white_list__userByCN-concatenation_simple_quote.php
PHP
mit
1,569
var sizes; var searchKey = ''; if(window.location.search!=''){ $("#searchKey").val(decodeURIComponent(window.location.search.substr(11))) } if (window.location.search != "") { searchKey = window.location.search.substr(11) } $.ajax({ url: '/sizes?searchKey=' + searchKey, async: false, method: 'get', success: function (data) { sizes = Math.ceil((data.data) / 8); if (sizes != 1) { $('#pages').show(); } } }); $(document).ready(function () { $.ajax({ url: "/islogin", async: false, type: "get", success: function (data) { if (!data.data) { location.href = "/login"; } } }); var hash = window.location.hash; if (!hash) { hash = "page=1" } var page = {pageSize: hash.split("=")[1], searchKey: searchKey}; $.ajax({ type: "post", data: page, url: "/lists", success: function (data) { var list = "<div class='item-list'>"; $.each(data.data, function (index, item) { list += ("<div class='item'><div class='icon'><a href='/detail#%{name}' data-url='%{url}' onclick='absUrl(this)' onmouseover='des(this)' onmouseout='_des(this)' >" + "<img src='%{icon}' alt='图片未找到'></a></div>" + "<div class='item-title'><strong>%{name}</strong></div><div>作者:%{author}</div>" + "<div class='item-info'><span class='version'>%{version}</span><span class='time'>%{date}<br/>%{time}</span></div>" + "<div class='detailed'><a href='/detail#%{name}' data-url='%{url}' onclick='absUrl(this)'>文档</a></div><div class='des'>%{detailed}</div>" + "<div class='follow'><a href='javascript:void(0)' class='%{flwed}' onclick='follow(this)' data-name='%{name}' data-follow='%{follow}' ></a></div></div>").format({ icon: '/logo/' + item.name, name: item.name, author: item.author, version: item.version, flwed: ((item.follow == true) ? 'flwed' : ''), time: item.createTime.split(" ")[1], date: item.createTime.split(" ")[0], detailed: item.description, follow: item.follow, url: item.url }) }); list += "</div>"; $("#containal").html(list).show(); userName(); //获取分页数 location.hash = "page=" + page.pageSize; if (window.location.hash.split("=")[1] == "1") { $('.firstPage').attr('disabled', true).addClass('disabled'); $('.prevPage').attr('disabled', true).addClass('disabled'); } else if (window.location.hash.split("=")[1] == sizes) { $('.lastPage').attr('disabled', true).addClass('disabled'); $('.nextPage').attr('disabled', true).addClass('disabled'); } }, error: function (data) { console.info(data); } }) followLists(); }); //读取用户名 function userName() { var userName = $.cookie("userName"); $('.user strong').text(userName) } //关注列表 function followLists() { $.ajax({ type: "GET", async: false, url: "/followList", success: function (data) { var followList = "<ul>" $.each(data.data, function (index, item) { followList += ("<li><span class='sort'><a href='javascript:void(0)' onclick='folSort(this)' class='prev'><img src='/images/up.png' alt=''></a><a href='javascript:void(0)' class='next' onclick='folSort(this)'><img src='/images/down.png' alt=''></a></span>" + "<a href='/detail#%{followName}' class='followName'>%{followName}</a><a href='javascript:void(0)' onclick='delFollow(this)' class='del-fol'>" + "<img src='/images/pro_close.png' alt=''></a></li>").format({followName: item}); }); followList += "</ul>"; $('.user-list').html(followList) }, error: function (data) { console.info(data); } }) } function user(self) { if (!$(self).hasClass('ac')) { $(self).addClass('ac'); $('.user-list').show(); followLists(); } else { $(self).removeClass('ac'); $('.user-list').hide() } } function des(_this) { $(_this).parents('.item').children('.des').show(); } function _des(_this) { $(_this).parents('.item').children('.des').hide(); } function pageBtn(self, name) { var pagination = {}; var curPage = location.hash.split("=")[1]; if (name == "first") { pagination.limit = 1; $(self).attr("disabled", true).addClass('disabled').siblings().attr("disabled", false).removeClass('disabled') $("#pages .prevPage").attr("disabled", true).addClass("disabled"); } else if (name == "prev") { pagination.limit = --curPage; $("#pages button").removeAttr("disabled").removeClass('disabled'); if (pagination.limit <= 1) { pagination.limit = 1; $("#pages .firstPage").attr("disabled", true).addClass("disabled"); $("#pages .prevPage").attr("disabled", true).addClass("disabled"); } } else if (name == "next") { pagination.limit = ++curPage; $("#pages button").removeAttr("disabled").removeClass('disabled'); if (pagination.limit >= sizes) { pagination.limit = sizes; // $("#pages button").removeAttr("disabled").removeClass('disabled'); $("#pages .lastPage").attr("disabled", true).addClass("disabled"); $("#pages .nextPage").attr("disabled", true).addClass("disabled"); } } else if (name == "end") { pagination.limit = sizes; $(self).attr("disabled", true).addClass('disabled').siblings().attr("disabled", false).removeClass('disabled'); $("#pages .nextPage").attr("disabled", true).addClass("disabled"); } $.ajax({ type: "post", url: "/pageSize", data: pagination, success: function (data) { var list = "<div class='item-list'>" $.each(data.data, function (index, item) { list += ("<div class='item'><div class='icon'><a href='/detail#%{name}' data-url='%{url}' onclick='absUrl(this)'><img src='%{icon}' alt='图片未找到'></a></div>" + "<div class='item-title'><strong>%{name}</strong></div><div>作者:%{author}</div>" + "<div class='item-info'><span class='version'>%{version}</span><span class='time'>%{date}<br/>%{time}</span></div>" + "<div class='follow'><a href='javascript:void(0)' class='%{flwed}' onclick='follow(this)' data-follow='%{follow}'></a></div>" + "<div class='detailed'><a href='/detail#%{name}' data-url='%{url}' onclick='absUrl(this)'>文档</a></div></div>").format({ icon: '/logo/' + item.name, name: item.name, author: item.author, version: item.version, time: item.createTime.split(" ")[1], date: item.createTime.split(" ")[0], flwed: ((item.follow == true) ? 'flwed' : ''), detailed: item.description, follow: item.follow, url: item.url }) }); list += "</div>"; $("#containal").html(list).fadeIn() location.hash = "page=" + pagination.limit; }, error: function (data) { console.info(data); } }) } //分页跳转 function logout() { $.ajax({ type: "get", url: "/userlogout", success: function (data) { window.location.href = "/login" }, error: function (data) { console.info(data); } }) } function follow(_this) { var data = {}; data.projectName = $(_this).parents('.item').children('.item-title').children().text(); if ($(_this).hasClass('flwed')) { $(_this).removeClass('flwed'); $.ajax({ type: "POST", url: "/delFollow", data: data, success: function (data) { console.info(data); }, error: function (data) { console.info(data); } }) } else { $(_this).addClass('flwed'); $.ajax({ type: "POST", url: "/addFollow", data: data, success: function (data) { // console.info(); }, error: function (data) { console.info(data); } }) } } function BindEnter(event) { if(event.code=='Enter'){ search() } } function search() { window.location.search = '?searchKey=' + $("#searchKey").val() } function delFollow(_this) { var data = {}; data.projectName = $(_this).siblings('.followName').text(); $.ajax({ type: "POST", url: "/delFollow", data: data, success: function (data) { var proName = $(_this).parent().children('.followName').text() $(_this).parent().remove(); $('.item-list .item .follow a[data-name=' + proName + ']').removeClass('flwed') }, error: function (data) { console.info(data); } }) } //关注排序 function folSort(self) { var name = $(self).attr("class"); var li = $(self).parents('li'); var sortData = {}; if (name == "next" && li.next()) { li.next().after(li) } else if (name == "prev" && li.prev()) { li.prev().before(li); } var listSort = []; for (var i = 0, len = $('.user-list li').length; i < len; i++) { var listName = $('.user-list li').eq(i).children('.followName').text(); listSort.push(listName) } sortData.projects = listSort.join(','); $.ajax({ type: "post", url: "/sortList", async: false, data: sortData, success: function (data) { }, error: function (data) { } }) } function absUrl(self) { var absUrl = $(self).attr("data-url"); $.cookie("absUrl", absUrl, {expires: 7}) }
dounine/japi
node/js/index.js
JavaScript
mit
10,577
import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { Polygon } from 'react-google-maps'; import {map, filter} from './../../../actions'; class Region extends React.Component { constructor(props) { super(props); this.state = { hovered: false, selected: false }; this.config = { strokeColor: '#babfc7', fillColor: '#7d899e', strokeOpacity: 0.28, strokeWeight: 1, fillOpacity: 0.1 }; } getRegionStyle() { let style = this.config; if (this.props.selected || this.state.hovered) { style = Object.assign({}, style, {fillColor: '#000'}); } return style; } onClick(event) { this.props.regionFilterClicked(this.props.region.id, !this.props.selected, { selected: this.props.selectedRegions, defaults: { routes: this.props.routes, assets: this.props.assets } }); } render() { return ( <Polygon mapHolderRef={this.props.mapHolderRef} paths={this.props.region.coordinates} options={this.getRegionStyle()} onClick={(event) => this.onClick(event)} onMouseover={(event) => {this.setState({hovered: true})}} onMouseout={(event) => {this.setState({hovered: false})}} /> ); } } const stateMap = (state, props, ownProps) => { return { selected : (state.selected.regions.indexOf(props.region.id) !== -1), selectedRegions: state.selected.regions, routes: state.data.route_options.response, assets: state.data.assets.response, }; }; function mapDispatchToProps (dispatch) { return { regionFilterClicked: bindActionCreators(filter.regionFilterClicked, dispatch), regionClick : bindActionCreators(map.regionClick, dispatch) }; } export default connect(stateMap, mapDispatchToProps)(Region);
Haaarp/geo
client/analytics/components/partials/maps/Region.js
JavaScript
mit
2,127
namespace Squirrel.Nodes { public interface INode { } }
escamilla/squirrel
src/library/Nodes/INode.cs
C#
mit
71
<?php namespace zikmont\ContabilidadBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Table(name="ctb_movimientos_resumen") * @ORM\Entity(repositoryClass="zikmont\ContabilidadBundle\Repository\CtbMovimientosResumenRepository") */ class CtbMovimientosResumen { /** * @ORM\Id * @ORM\Column(name="codigo_movimiento_resumen_pk", type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ private $codigoMovimientoResumenPk; /** * @ORM\Column(name="codigo_cierre_mes_fk", type="integer") */ private $codigoCierreMesFk; /** * @ORM\Column(name="annio", type="integer") */ private $annio; /** * @ORM\Column(name="mes", type="smallint") */ private $mes; /** * @ORM\Column(name="codigo_cuenta_fk", type="string", length=20) */ private $codigoCuentaFk; /** * @ORM\Column(name="debito", type="float") */ private $debito = 0; /** * @ORM\Column(name="credito", type="float") */ private $credito = 0; /** * @ORM\Column(name="base", type="float") */ private $base = 0; /** * @ORM\ManyToOne(targetEntity="CtbCuentasContables", inversedBy="CtbMovimientosResumen") * @ORM\JoinColumn(name="codigo_cuenta_fk", referencedColumnName="codigo_cuenta_pk") */ protected $cuentaRel; /** * @ORM\ManyToOne(targetEntity="CtbCierresMes", inversedBy="CtbMovimientosResumen") * @ORM\JoinColumn(name="codigo_cierre_mes_fk", referencedColumnName="codigo_cierre_mes_pk") */ protected $ciereMesContabilidadRel; /** * Get codigoMovimientoResumenPk * * @return integer */ public function getCodigoMovimientoResumenPk() { return $this->codigoMovimientoResumenPk; } /** * Set codigoCierreMesContabilidadFk * * @param integer $codigoCierreMesContabilidadFk */ public function setCodigoCierreMesContabilidadFk($codigoCierreMesContabilidadFk) { $this->codigoCierreMesContabilidadFk = $codigoCierreMesContabilidadFk; } /** * Get codigoCierreMesContabilidadFk * * @return integer */ public function getCodigoCierreMesContabilidadFk() { return $this->codigoCierreMesContabilidadFk; } /** * Set annio * * @param integer $annio */ public function setAnnio($annio) { $this->annio = $annio; } /** * Get annio * * @return integer */ public function getAnnio() { return $this->annio; } /** * Set mes * * @param smallint $mes */ public function setMes($mes) { $this->mes = $mes; } /** * Get mes * * @return smallint */ public function getMes() { return $this->mes; } /** * Set codigoCuentaFk * * @param string $codigoCuentaFk */ public function setCodigoCuentaFk($codigoCuentaFk) { $this->codigoCuentaFk = $codigoCuentaFk; } /** * Get codigoCuentaFk * * @return string */ public function getCodigoCuentaFk() { return $this->codigoCuentaFk; } /** * Set debito * * @param float $debito */ public function setDebito($debito) { $this->debito = $debito; } /** * Get debito * * @return float */ public function getDebito() { return $this->debito; } /** * Set credito * * @param float $credito */ public function setCredito($credito) { $this->credito = $credito; } /** * Get credito * * @return float */ public function getCredito() { return $this->credito; } /** * Set base * * @param float $base */ public function setBase($base) { $this->base = $base; } /** * Get base * * @return float */ public function getBase() { return $this->base; } /** * Set cuentaRel * * @param zikmont\ContabilidadBundle\Entity\CuentasContables $cuentaRel */ public function setCuentaRel(\zikmont\ContabilidadBundle\Entity\CuentasContables $cuentaRel) { $this->cuentaRel = $cuentaRel; } /** * Get cuentaRel * * @return zikmont\ContabilidadBundle\Entity\CuentasContables */ public function getCuentaRel() { return $this->cuentaRel; } /** * Set ciereMesContabilidadRel * * @param zikmont\ContabilidadBundle\Entity\CierresMesContabilidad $ciereMesContabilidadRel */ public function setCiereMesContabilidadRel(\zikmont\ContabilidadBundle\Entity\CierresMesContabilidad $ciereMesContabilidadRel) { $this->ciereMesContabilidadRel = $ciereMesContabilidadRel; } /** * Get ciereMesContabilidadRel * * @return zikmont\ContabilidadBundle\Entity\CierresMesContabilidad */ public function getCiereMesContabilidadRel() { return $this->ciereMesContabilidadRel; } /** * Set codigoCierreMesFk * * @param integer $codigoCierreMesFk */ public function setCodigoCierreMesFk($codigoCierreMesFk) { $this->codigoCierreMesFk = $codigoCierreMesFk; } /** * Get codigoCierreMesFk * * @return integer */ public function getCodigoCierreMesFk() { return $this->codigoCierreMesFk; } }
wariox3/zikmont
src/zikmont/ContabilidadBundle/Entity/CtbMovimientosResumen.php
PHP
mit
5,658
using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Abp.Application.Services; using Abp.Application.Services.Dto; using Abp.Authorization; using Abp.Domain.Entities; using Abp.Domain.Repositories; using Abp.Extensions; using Abp.IdentityFramework; using Abp.Linq.Extensions; using Abp.Localization; using Abp.Runtime.Session; using Abp.UI; using IdentityServerWithEfCoreDemo.Authorization; using IdentityServerWithEfCoreDemo.Authorization.Accounts; using IdentityServerWithEfCoreDemo.Authorization.Roles; using IdentityServerWithEfCoreDemo.Authorization.Users; using IdentityServerWithEfCoreDemo.Roles.Dto; using IdentityServerWithEfCoreDemo.Users.Dto; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; namespace IdentityServerWithEfCoreDemo.Users { [AbpAuthorize(PermissionNames.Pages_Users)] public class UserAppService : AsyncCrudAppService<User, UserDto, long, PagedUserResultRequestDto, CreateUserDto, UserDto>, IUserAppService { private readonly UserManager _userManager; private readonly RoleManager _roleManager; private readonly IRepository<Role> _roleRepository; private readonly IPasswordHasher<User> _passwordHasher; private readonly IAbpSession _abpSession; private readonly LogInManager _logInManager; public UserAppService( IRepository<User, long> repository, UserManager userManager, RoleManager roleManager, IRepository<Role> roleRepository, IPasswordHasher<User> passwordHasher, IAbpSession abpSession, LogInManager logInManager) : base(repository) { _userManager = userManager; _roleManager = roleManager; _roleRepository = roleRepository; _passwordHasher = passwordHasher; _abpSession = abpSession; _logInManager = logInManager; } public override async Task<UserDto> CreateAsync(CreateUserDto input) { CheckCreatePermission(); var user = ObjectMapper.Map<User>(input); user.TenantId = AbpSession.TenantId; user.IsEmailConfirmed = true; await _userManager.InitializeOptionsAsync(AbpSession.TenantId); CheckErrors(await _userManager.CreateAsync(user, input.Password)); if (input.RoleNames != null) { CheckErrors(await _userManager.SetRolesAsync(user, input.RoleNames)); } CurrentUnitOfWork.SaveChanges(); return MapToEntityDto(user); } public override async Task<UserDto> UpdateAsync(UserDto input) { CheckUpdatePermission(); var user = await _userManager.GetUserByIdAsync(input.Id); MapToEntity(input, user); CheckErrors(await _userManager.UpdateAsync(user)); if (input.RoleNames != null) { CheckErrors(await _userManager.SetRolesAsync(user, input.RoleNames)); } return await GetAsync(input); } public override async Task DeleteAsync(EntityDto<long> input) { var user = await _userManager.GetUserByIdAsync(input.Id); await _userManager.DeleteAsync(user); } public async Task<ListResultDto<RoleDto>> GetRoles() { var roles = await _roleRepository.GetAllListAsync(); return new ListResultDto<RoleDto>(ObjectMapper.Map<List<RoleDto>>(roles)); } public async Task ChangeLanguage(ChangeUserLanguageDto input) { await SettingManager.ChangeSettingForUserAsync( AbpSession.ToUserIdentifier(), LocalizationSettingNames.DefaultLanguage, input.LanguageName ); } protected override User MapToEntity(CreateUserDto createInput) { var user = ObjectMapper.Map<User>(createInput); user.SetNormalizedNames(); return user; } protected override void MapToEntity(UserDto input, User user) { ObjectMapper.Map(input, user); user.SetNormalizedNames(); } protected override UserDto MapToEntityDto(User user) { var roleIds = user.Roles.Select(x => x.RoleId).ToArray(); var roles = _roleManager.Roles.Where(r => roleIds.Contains(r.Id)).Select(r => r.NormalizedName); var userDto = base.MapToEntityDto(user); userDto.RoleNames = roles.ToArray(); return userDto; } protected override IQueryable<User> CreateFilteredQuery(PagedUserResultRequestDto input) { return Repository.GetAllIncluding(x => x.Roles) .WhereIf(!input.Keyword.IsNullOrWhiteSpace(), x => x.UserName.Contains(input.Keyword) || x.Name.Contains(input.Keyword) || x.EmailAddress.Contains(input.Keyword)) .WhereIf(input.IsActive.HasValue, x => x.IsActive == input.IsActive); } protected override async Task<User> GetEntityByIdAsync(long id) { var user = await Repository.GetAllIncluding(x => x.Roles).FirstOrDefaultAsync(x => x.Id == id); if (user == null) { throw new EntityNotFoundException(typeof(User), id); } return user; } protected override IQueryable<User> ApplySorting(IQueryable<User> query, PagedUserResultRequestDto input) { return query.OrderBy(r => r.UserName); } protected virtual void CheckErrors(IdentityResult identityResult) { identityResult.CheckErrors(LocalizationManager); } public async Task<bool> ChangePassword(ChangePasswordDto input) { if (_abpSession.UserId == null) { throw new UserFriendlyException("Please log in before attemping to change password."); } long userId = _abpSession.UserId.Value; var user = await _userManager.GetUserByIdAsync(userId); var loginAsync = await _logInManager.LoginAsync(user.UserName, input.CurrentPassword, shouldLockout: false); if (loginAsync.Result != AbpLoginResultType.Success) { throw new UserFriendlyException("Your 'Existing Password' did not match the one on record. Please try again or contact an administrator for assistance in resetting your password."); } if (!new Regex(AccountAppService.PasswordRegex).IsMatch(input.NewPassword)) { throw new UserFriendlyException("Passwords must be at least 8 characters, contain a lowercase, uppercase, and number."); } user.Password = _passwordHasher.HashPassword(user, input.NewPassword); CurrentUnitOfWork.SaveChanges(); return true; } public async Task<bool> ResetPassword(ResetPasswordDto input) { if (_abpSession.UserId == null) { throw new UserFriendlyException("Please log in before attemping to reset password."); } long currentUserId = _abpSession.UserId.Value; var currentUser = await _userManager.GetUserByIdAsync(currentUserId); var loginAsync = await _logInManager.LoginAsync(currentUser.UserName, input.AdminPassword, shouldLockout: false); if (loginAsync.Result != AbpLoginResultType.Success) { throw new UserFriendlyException("Your 'Admin Password' did not match the one on record. Please try again."); } if (currentUser.IsDeleted || !currentUser.IsActive) { return false; } var roles = await _userManager.GetRolesAsync(currentUser); if (!roles.Contains(StaticRoleNames.Tenants.Admin)) { throw new UserFriendlyException("Only administrators may reset passwords."); } var user = await _userManager.GetUserByIdAsync(input.UserId); if (user != null) { user.Password = _passwordHasher.HashPassword(user, input.NewPassword); CurrentUnitOfWork.SaveChanges(); } return true; } } }
aspnetboilerplate/aspnetboilerplate-samples
IdentityServerWithEfCoreDemo/aspnet-core/src/IdentityServerWithEfCoreDemo.Application/Users/UserAppService.cs
C#
mit
8,506
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2015 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ sap.ui.define(['jquery.sap.global', 'sap/ui/core/Renderer'], function(jQuery, Renderer) { "use strict"; /** * ObjectNumber renderer. * @namespace */ var ObjectNumberRenderer = { }; /** * Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}. * * @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the render output buffer * @param {sap.ui.core.Control} oON An object representation of the control that should be rendered */ ObjectNumberRenderer.render = function(oRm, oON) { var sTooltip = oON._getEnrichedTooltip(), sTextDir = oON.getTextDirection(), sTextAlign = oON.getTextAlign(); oRm.write("<div"); oRm.writeControlData(oON); oRm.addClass("sapMObjectNumber"); oRm.addClass(oON._sCSSPrefixObjNumberStatus + oON.getState()); if (oON.getEmphasized()) { oRm.addClass("sapMObjectNumberEmph"); } if (sTooltip) { oRm.writeAttributeEscaped("title", sTooltip); } if (sTextDir !== sap.ui.core.TextDirection.Inherit) { oRm.writeAttribute("dir", sTextDir.toLowerCase()); } sTextAlign = Renderer.getTextAlign(sTextAlign, sTextDir); if (sTextAlign) { oRm.addStyle("text-align", sTextAlign); } oRm.writeClasses(); oRm.writeStyles(); // ARIA // when the status is "None" there is nothing for reading if (oON.getState() !== sap.ui.core.ValueState.None) { oRm.writeAccessibilityState({ labelledby: oON.getId() + "-state" }); } oRm.write(">"); this.renderText(oRm, oON); oRm.write(" "); // space between the number text and unit this.renderUnit(oRm, oON); this.renderHiddenARIAElement(oRm, oON); oRm.write("</div>"); }; ObjectNumberRenderer.renderText = function(oRm, oON) { oRm.write("<span"); oRm.addClass("sapMObjectNumberText"); oRm.writeClasses(); oRm.write(">"); oRm.writeEscaped(oON.getNumber()); oRm.write("</span>"); }; ObjectNumberRenderer.renderUnit = function(oRm, oON) { var sUnit = oON.getUnit() || oON.getNumberUnit(); oRm.write("<span"); oRm.addClass("sapMObjectNumberUnit"); oRm.writeClasses(); oRm.write(">"); oRm.writeEscaped(sUnit); oRm.write("</span>"); }; ObjectNumberRenderer.renderHiddenARIAElement = function(oRm, oON) { var sARIAStateText = "", oRB = sap.ui.getCore().getLibraryResourceBundle("sap.m"); if (oON.getState() == sap.ui.core.ValueState.None) { return; } oRm.write("<span id='" + oON.getId() + "-state' class='sapUiInvisibleText' aria-hidden='true'>"); switch (oON.getState()) { case sap.ui.core.ValueState.Error: sARIAStateText = oRB.getText("OBJECTNUMBER_ARIA_VALUE_STATE_ERROR"); break; case sap.ui.core.ValueState.Warning: sARIAStateText = oRB.getText("OBJECTNUMBER_ARIA_VALUE_STATE_WARNING"); break; case sap.ui.core.ValueState.Success: sARIAStateText = oRB.getText("OBJECTNUMBER_ARIA_VALUE_STATE_SUCCESS"); break; } oRm.write(sARIAStateText); oRm.write("</span>"); }; return ObjectNumberRenderer; }, /* bExport= */ true);
marinho/german-articles
webapp/resources/sap/m/ObjectNumberRenderer-dbg.js
JavaScript
mit
3,233
<?php declare(strict_types=1); /* * The MIT License (MIT) * * Copyright (c) 2014-2017 Spomky-Labs * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ namespace OAuth2Framework\Component\Server\Tests\Stub\Event; use OAuth2Framework\Component\Server\Event\AccessToken\AccessTokenRevokedEvent; final class AccessTokenRevokedEventHandler extends EventHandler { /** * @param AccessTokenRevokedEvent $event */ public function handle(AccessTokenRevokedEvent $event) { $this->save($event); } }
OAuth2-Framework/server-library
Tests/Stub/Event/AccessTokenRevokedEventHandler.php
PHP
mit
606
"""Controller for rendering pod content.""" import datetime import mimetypes import os import sys import time from grow.common import utils from grow.documents import static_document from grow.pods import errors from grow.rendering import rendered_document from grow.templates import doc_dependency from grow.templates import tags class Error(Exception): """Base rendering pool error.""" def __init__(self, message): super(Error, self).__init__(message) self.message = message class UnknownKindError(Error): """Unknown kind of information.""" pass class IgnoredPathError(Error): """Document is being served at an ignored path.""" pass class RenderController(object): """Controls how the content is rendered and evaluated.""" def __init__(self, pod, serving_path, route_info, params=None, is_threaded=False): self.pod = pod self.serving_path = serving_path self.route_info = route_info self.params = params if params is not None else {} self.render_timer = None self.use_jinja = False self.is_threaded = is_threaded @staticmethod def clean_source_dir(source_dir): """Clean the formatting of the source dir to format correctly.""" source_dir = source_dir.strip() source_dir = source_dir.rstrip(os.path.sep) return source_dir @staticmethod def from_route_info(pod, serving_path, route_info, params=None): """Create the correct controller based on the route info.""" if params is None: params = {} if route_info.kind == 'doc': return RenderDocumentController( pod, serving_path, route_info, params=params) elif route_info.kind == 'static': return RenderStaticDocumentController( pod, serving_path, route_info, params=params) elif route_info.kind == 'sitemap': return RenderSitemapController( pod, serving_path, route_info, params=params) elif route_info.kind == 'error': return RenderErrorController( pod, serving_path, route_info, params=params) raise UnknownKindError( 'Do not have a controller for: {}'.format(route_info.kind)) @property def locale(self): """Locale to use for rendering.""" return None @property def mimetype(self): """Guess the mimetype of the content.""" return 'text/plain' def get_http_headers(self): """Determine headers to serve for https requests.""" headers = {} mimetype = self.mimetype if mimetype: headers['Content-Type'] = mimetype return headers def load(self, source_dir): """Load the pod content from file system.""" raise NotImplementedError def render(self, jinja_env, request=None): """Render the pod content.""" raise NotImplementedError def validate_path(self, *path_filters): """Validate that the path is valid against all filters.""" # Default test against the pod filter for deployment specific filtering. path_filters = list(path_filters) or [self.pod.path_filter] for path_filter in path_filters: if not path_filter.is_valid(self.serving_path): text = '{} is an ignored path.' raise errors.RouteNotFoundError(text.format(self.serving_path)) class RenderDocumentController(RenderController): """Controller for handling rendering for documents.""" def __init__(self, pod, serving_path, route_info, params=None, is_threaded=False): super(RenderDocumentController, self).__init__( pod, serving_path, route_info, params=params, is_threaded=is_threaded) self._doc = None self.use_jinja = True def __repr__(self): return '<RenderDocumentController({})>'.format(self.route_info.meta['pod_path']) @property def doc(self): """Doc for the controller.""" if not self._doc: pod_path = self.route_info.meta['pod_path'] locale = self.route_info.meta.get( 'locale', self.params.get('locale')) self._doc = self.pod.get_doc(pod_path, locale=locale) return self._doc @property def locale(self): """Locale to use for rendering.""" if 'locale' in self.route_info.meta: return self.route_info.meta['locale'] return self.doc.locale if self.doc else None @property def mimetype(self): """Determine headers to serve for https requests.""" return mimetypes.guess_type(self.doc.view)[0] @property def pod_path(self): """Locale to use for rendering.""" if 'pod_path' in self.route_info.meta: return self.route_info.meta['pod_path'] return self.doc.pod_path if self.doc else None @property def suffix(self): """Determine headers to serve for https requests.""" _, ext = os.path.splitext(self.doc.view) if ext == '.html': return 'index.html' return '' def load(self, source_dir): """Load the pod content from file system.""" timer = self.pod.profile.timer( 'RenderDocumentController.load', label='{} ({})'.format(self.pod_path, self.locale), meta={ 'path': self.pod_path, 'locale': str(self.locale)} ).start_timer() source_dir = self.clean_source_dir(source_dir) # Validate the path with the config filters. self.validate_path() try: doc = self.doc serving_path = self.serving_path if serving_path.endswith('/'): serving_path = '{}{}'.format(serving_path, self.suffix) rendered_path = '{}{}'.format(source_dir, serving_path) rendered_content = self.pod.storage.read(rendered_path) rendered_doc = rendered_document.RenderedDocument( serving_path, rendered_content) timer.stop_timer() return rendered_doc except Exception as err: exception = errors.BuildError(str(err)) exception.traceback = sys.exc_info()[2] exception.controller = self exception.exception = err raise exception def render(self, jinja_env=None, request=None): """Render the document using the render pool.""" timer = self.pod.profile.timer( 'RenderDocumentController.render', label='{} ({})'.format(self.doc.pod_path, self.doc.locale), meta={ 'path': self.doc.pod_path, 'locale': str(self.doc.locale)} ).start_timer() # Validate the path with the config filters. self.validate_path() doc = self.doc template = jinja_env['env'].get_template(doc.view.lstrip('/')) track_dependency = doc_dependency.DocDependency(doc) local_tags = tags.create_builtin_tags( self.pod, doc, track_dependency=track_dependency) # NOTE: This should be done using get_template(... globals=...) # or passed as an argument into render but # it is not available included inside macros??? # See: https://github.com/pallets/jinja/issues/688 template.globals['g'] = local_tags # Track the message stats, including untranslated strings. if self.pod.is_enabled(self.pod.FEATURE_TRANSLATION_STATS): template.globals['_'] = tags.make_doc_gettext(doc) try: doc.footnotes.reset() serving_path = doc.get_serving_path() if serving_path.endswith('/'): serving_path = '{}{}'.format(serving_path, self.suffix) content = self.pod.extensions_controller.trigger('pre_render', doc, doc.body) if content: doc.format.update(content=content) rendered_content = template.render({ 'doc': doc, 'request': request, 'env': self.pod.env, 'podspec': self.pod.podspec, '_track_dependency': track_dependency, }).lstrip() rendered_content = self.pod.extensions_controller.trigger( 'post_render', doc, rendered_content) rendered_doc = rendered_document.RenderedDocument( serving_path, rendered_content) timer.stop_timer() return rendered_doc except Exception as err: exception = errors.BuildError(str(err)) exception.traceback = sys.exc_info()[2] exception.controller = self exception.exception = err raise exception class RenderErrorController(RenderController): """Controller for handling rendering for errors.""" def __init__(self, pod, serving_path, route_info, params=None, is_threaded=False): super(RenderErrorController, self).__init__( pod, serving_path, route_info, params=params, is_threaded=is_threaded) self.use_jinja = True def __repr__(self): return '<RenderErrorController({})>'.format(self.route_info.meta['view']) def load(self, source_dir): """Load the pod content from file system.""" timer = self.pod.profile.timer( 'RenderErrorController.load', label='{} ({})'.format( self.route_info.meta['key'], self.route_info.meta['view']), meta={ 'key': self.route_info.meta['key'], 'view': self.route_info.meta['view'], } ).start_timer() source_dir = self.clean_source_dir(source_dir) # Validate the path with the config filters. self.validate_path() try: serving_path = '/{}.html'.format(self.route_info.meta['key']) rendered_path = '{}{}'.format(source_dir, serving_path) rendered_content = self.pod.storage.read(rendered_path) rendered_doc = rendered_document.RenderedDocument( serving_path, rendered_content) timer.stop_timer() return rendered_doc except Exception as err: text = 'Error building {}: {}' if self.pod: self.pod.logger.exception(text.format(self, err)) exception = errors.BuildError(text.format(self, err)) exception.traceback = sys.exc_info()[2] exception.controller = self exception.exception = err raise exception def render(self, jinja_env=None, request=None): """Render the document using the render pool.""" timer = self.pod.profile.timer( 'RenderErrorController.render', label='{} ({})'.format( self.route_info.meta['key'], self.route_info.meta['view']), meta={ 'key': self.route_info.meta['key'], 'view': self.route_info.meta['view'], } ).start_timer() # Validate the path with the config filters. self.validate_path() with jinja_env['lock']: template = jinja_env['env'].get_template( self.route_info.meta['view'].lstrip('/')) local_tags = tags.create_builtin_tags(self.pod, doc=None) # NOTE: This should be done using get_template(... globals=...) # or passed as an argument into render but # it is not available included inside macros??? # See: https://github.com/pallets/jinja/issues/688 template.globals['g'] = local_tags try: serving_path = '/{}.html'.format(self.route_info.meta['key']) rendered_doc = rendered_document.RenderedDocument( serving_path, template.render({ 'doc': None, 'env': self.pod.env, 'podspec': self.pod.podspec, }).lstrip()) timer.stop_timer() return rendered_doc except Exception as err: text = 'Error building {}: {}' if self.pod: self.pod.logger.exception(text.format(self, err)) exception = errors.BuildError(text.format(self, err)) exception.traceback = sys.exc_info()[2] exception.controller = self exception.exception = err raise exception class RenderSitemapController(RenderController): """Controller for handling rendering for sitemaps.""" @property def mimetype(self): """Determine headers to serve for https requests.""" return mimetypes.guess_type(self.serving_path)[0] def load(self, source_dir): """Load the pod content from file system.""" timer = self.pod.profile.timer( 'RenderSitemapController.load', label='{}'.format(self.serving_path), meta=self.route_info.meta, ).start_timer() source_dir = self.clean_source_dir(source_dir) # Validate the path with the config filters. self.validate_path() try: rendered_path = '{}{}'.format(source_dir, self.serving_path) rendered_content = self.pod.storage.read(rendered_path) rendered_doc = rendered_document.RenderedDocument( self.serving_path, rendered_content) timer.stop_timer() return rendered_doc except Exception as err: text = 'Error building {}: {}' if self.pod: self.pod.logger.exception(text.format(self, err)) exception = errors.BuildError(text.format(self, err)) exception.traceback = sys.exc_info()[2] exception.controller = self exception.exception = err raise exception def render(self, jinja_env=None, request=None): """Render the document using the render pool.""" timer = self.pod.profile.timer( 'RenderSitemapController.render', label='{}'.format(self.serving_path), meta=self.route_info.meta, ).start_timer() # Validate the path with the config filters. self.validate_path() # Duplicate the routes to use the filters without messing up routing. temp_router = self.pod.router.__class__(self.pod) temp_router.add_all() # Sitemaps only show documents...? temp_router.filter('whitelist', kinds=['doc']) for sitemap_filter in self.route_info.meta.get('filters') or []: temp_router.filter( sitemap_filter['type'], collection_paths=sitemap_filter.get('collections'), paths=sitemap_filter.get('paths'), locales=sitemap_filter.get('locales')) # Need a custom root for rendering sitemap. root = os.path.join(utils.get_grow_dir(), 'pods', 'templates') jinja_env = self.pod.render_pool.custom_jinja_env(root=root) with jinja_env['lock']: if self.route_info.meta.get('template'): content = self.pod.read_file(self.route_info.meta['template']) template = jinja_env['env'].from_string(content) else: template = jinja_env['env'].get_template('sitemap.xml') try: docs = [] for _, value, _ in temp_router.routes.nodes: docs.append(self.pod.get_doc(value.meta['pod_path'], locale=value.meta['locale'])) rendered_doc = rendered_document.RenderedDocument( self.serving_path, template.render({ 'pod': self.pod, 'env': self.pod.env, 'docs': docs, 'podspec': self.pod.podspec, }).lstrip()) timer.stop_timer() return rendered_doc except Exception as err: text = 'Error building {}: {}' if self.pod: self.pod.logger.exception(text.format(self, err)) exception = errors.BuildError(text.format(self, err)) exception.traceback = sys.exc_info()[2] exception.controller = self exception.exception = err raise exception class RenderStaticDocumentController(RenderController): """Controller for handling rendering for static documents.""" def __init__(self, pod, serving_path, route_info, params=None, is_threaded=False): super(RenderStaticDocumentController, self).__init__( pod, serving_path, route_info, params=params, is_threaded=is_threaded) self._static_doc = None self._pod_path = None def __repr__(self): return '<RenderStaticDocumentController({})>'.format(self.route_info.meta['pod_path']) @property def pod_path(self): """Static doc for the controller.""" if self._pod_path: return self._pod_path locale = self.route_info.meta.get( 'locale', self.params.get('locale')) if 'pod_path' in self.route_info.meta: self._pod_path = self.route_info.meta['pod_path'] else: for source_format in self.route_info.meta['source_formats']: path_format = '{}{}'.format(source_format, self.params['*']) self._pod_path = self.pod.path_format.format_static( path_format, locale=locale) # Strip the fingerprint to get to the raw static file. self._pod_path = static_document.StaticDocument.strip_fingerprint( self._pod_path) try: # Throws an error when the document doesn't exist. _ = self.pod.get_static(self._pod_path, locale=locale) break except errors.DocumentDoesNotExistError: self._pod_path = None return self._pod_path @property def static_doc(self): """Static doc for the controller.""" if not self._static_doc: locale = self.route_info.meta.get( 'locale', self.params.get('locale')) self._static_doc = self.pod.get_static(self.pod_path, locale=locale) return self._static_doc @property def mimetype(self): """Determine headers to serve for https requests.""" return mimetypes.guess_type(self.serving_path)[0] def get_http_headers(self): """Determine headers to serve for http requests.""" headers = super(RenderStaticDocumentController, self).get_http_headers() if self.pod_path is None: return headers path = self.pod.abs_path(self.static_doc.pod_path) self.pod.storage.update_headers(headers, path) modified = self.pod.storage.modified(path) time_obj = datetime.datetime.fromtimestamp(modified).timetuple() time_format = '%a, %d %b %Y %H:%M:%S GMT' headers['Last-Modified'] = time.strftime(time_format, time_obj) headers['ETag'] = '"{}"'.format(headers['Last-Modified']) headers['X-Grow-Pod-Path'] = self.static_doc.pod_path if self.static_doc.locale: headers['X-Grow-Locale'] = self.static_doc.locale return headers def load(self, source_dir): """Load the pod content from file system.""" timer = self.pod.profile.timer( 'RenderStaticDocumentController.load', label=self.serving_path, meta={'path': self.serving_path}).start_timer() source_dir = self.clean_source_dir(source_dir) # Validate the path with the static config specific filter. self.validate_path(self.route_info.meta['path_filter']) rendered_path = '{}{}'.format(source_dir, self.serving_path) rendered_content = self.pod.storage.read(rendered_path) rendered_doc = rendered_document.RenderedDocument( self.serving_path, rendered_content) timer.stop_timer() return rendered_doc def render(self, jinja_env=None, request=None): """Read the static file.""" timer = self.pod.profile.timer( 'RenderStaticDocumentController.render', label=self.serving_path, meta={'path': self.serving_path}).start_timer() if not self.pod_path or not self.pod.file_exists(self.pod_path): text = '{} was not found in static files.' raise errors.RouteNotFoundError(text.format(self.serving_path)) # Validate the path with the static config specific filter. self.validate_path(self.route_info.meta['path_filter']) rendered_content = self.pod.read_file(self.pod_path) rendered_content = self.pod.extensions_controller.trigger( 'post_render', self.static_doc, rendered_content) rendered_doc = rendered_document.RenderedDocument( self.serving_path, rendered_content) timer.stop_timer() return rendered_doc
grow/grow
grow/rendering/render_controller.py
Python
mit
21,264
class AddPublishToSiteVersion < ActiveRecord::Migration[5.0] def change remove_column :author_site_storages, :publish add_column :author_site_versions, :published, :boolean end end
teamco/anthill_layout
db/migrate/20160425125336_add_publish_to_site_version.rb
Ruby
mit
193
# Copyright (C) 2012 Andy Balaam and The Pepper Developers # Released under the MIT License. See the file COPYING.txt for details. from nose.tools import * from libpepper import builtins from libpepper.environment import PepEnvironment from libpepper.vals.all_values import * def PlusEquals_increases_int_value___test(): env = PepEnvironment( None ) builtins.add_builtins( env ) PepInit( PepSymbol('int'), PepSymbol('x'), PepInt('7') ).evaluate( env ) # Sanity assert_equal( "7", PepSymbol('x').evaluate( env ).value ) PepModification( PepSymbol('x'), PepInt('3') ).evaluate( env ) assert_equal( "10", PepSymbol('x').evaluate( env ).value ) def PlusEquals_increases_float_value___test(): env = PepEnvironment( None ) builtins.add_builtins( env ) PepInit( PepSymbol('float'), PepSymbol('x'), PepFloat('7.2') ).evaluate( env ) # Sanity assert_equal( "7.2", PepSymbol('x').evaluate( env ).value ) PepModification( PepSymbol('x'), PepFloat('0.3') ).evaluate( env ) assert_equal( "7.5", PepSymbol('x').evaluate( env ).value )
andybalaam/pepper
old/pepper1/src/test/evaluation/test_plusequals.py
Python
mit
1,124
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Search.Fluent { using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.Azure.Management.Search.Fluent.Models; /// <summary> /// The result of checking for Search service name availability. /// </summary> public interface ICheckNameAvailabilityResult : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta, Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasInner<Models.CheckNameAvailabilityOutputInner> { /// <summary> /// Gets true if the specified name is valid and available for use, otherwise false. /// </summary> bool IsAvailable { get; } /// <summary> /// Gets the reason why the user-provided name for the search service could not be used, if any. The /// Reason element is only returned if NameAvailable is false. /// </summary> string UnavailabilityReason { get; } /// <summary> /// Gets an error message explaining the Reason value in more detail. /// </summary> string UnavailabilityMessage { get; } } }
hovsepm/azure-libraries-for-net
src/ResourceManagement/Search/Domain/ICheckNameAvailabilityResult.cs
C#
mit
1,305
# -*- encoding : utf-8 -*- require 'tmail/version' require 'tmail/mail' require 'tmail/mailbox' require 'tmail/core_extensions' require 'tmail/net'
liquidware/saasy
vendor/rails/actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail.rb
Ruby
mit
148
using Newtonsoft.Json.Linq; using SolrExpress.Search; using SolrExpress.Search.Parameter; using SolrExpress.Search.Parameter.Validation; using SolrExpress.Utility; namespace SolrExpress.Solr5.Search.Parameter { [AllowMultipleInstances] public sealed class FilterParameter<TDocument> : BaseFilterParameter<TDocument>, ISearchItemExecution<JObject> where TDocument : Document { private JToken _result; public void AddResultInContainer(JObject container) { var jArray = (JArray)container["filter"] ?? new JArray(); jArray.Add(this._result); container["filter"] = jArray; } public void Execute() { this._result = ParameterUtil.GetFilterWithTag(this.Query.Execute(), this.TagName); } } }
solr-express/solr-express
src/SolrExpress.Solr5/Search/Parameter/FilterParameter.cs
C#
mit
817