code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/* * SIGMA Framework Core Library. * * This library is distributed under the MIT License. * See Copyright Notice at the end of this file. */ #if (defined __DMC__ || defined _MSC_VER) # pragma once #endif #if (!defined SIGMA_FRAMEWORK_COMMON_CORE_LIBRARY_TEMPLATE_HPP) # define SIGMA_FRAMEWORK_COMMON_CORE_LIBRARY_TEMPLATE_HPP # if (defined __GNUC__) # include <sigma/common/com_ptr.hpp> # include <sigma/common/threads/threads.safe.hpp> # include <sigma/common/threads/threads.unsafe.hpp> # include <sigma/core/core.category.hpp> # include <sigma/core/core.config.hpp> # else # include "../common/com_ptr.hpp" # include "../common/threads/threads.safe.hpp" # include "../common/threads/threads.unsafe.hpp" # include "core.category.hpp" # include "core.config.hpp" # endif # if (defined SIGMA_MANAGED) # pragma managed(push, off) # endif CORE_BEGIN template<class _CLSID, class _CATID> class Template : public Interface { private: typedef Interface _Mybase; private: typedef Template<_CLSID, _CATID> _Mytype; public: typedef typename _CLSID::guard_type guard_type; public: typedef typename _CATID::category_type category_type; public: class Lock { private: typedef Lock _Mytype; private: typedef typename guard_type::lock lock_type; public: Lock(_In_ Template<_CLSID, _CATID> const &object) :m_lock(object.m_guard) {} ~Lock() {} private: lock_type m_lock; Lock(); Lock(_In_ _Mytype const &); const _Mytype &operator = (_In_ _Mytype const &); }; friend class Lock; public: Template() :_Mybase(), m_guard() {} explicit Template(_In_ Interface &aggregate) :_Mybase(aggregate), m_guard() {} static const UID &APICALL CLSID() { return _CLSID::CLSID(); } static const UID &APICALL CATID() { return _CATID::CATID(); } template<class _type> com_ptr_t<_type> QueryInterface() { return _Mybase::QueryInterface<_type>(); } protected: virtual ~Template() {} virtual InterfacePtr APICALL QueryInterface(_In_ const UID &clsid) SIGMA_OVERRIDE { if (clsid == _CLSID::CLSID()) return InterfacePtr(this, true); return InterfacePtr(); } private: mutable guard_type m_guard; Template(_In_ _Mytype const &); const _Mytype &operator = (_In_ _Mytype const &); }; # define CORE_CLSID_DECLARATION(struct_name, guard) \ struct struct_name \ { \ typedef guard guard_type; \ \ static SIGMA_API \ const SIGMA core::UID &APICALL CLSID(); \ }; # define CORE_CLSID_IMPLEMENTATION(struct_name, uid) \ const SIGMA core::UID &APICALL struct_name::CLSID() \ { \ static SIGMA core::UID instance(uid); \ \ return instance; \ } CORE_END # if (defined SIGMA_MANAGED) # pragma managed(pop) # endif #endif /* * Copyright © 2008-2013 by Smirnov Michael. * * 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. */
cpp4ever/sigma-framework
sigma/core/core.template.hpp
C++
lgpl-3.0
6,347
/** * This file is part of the LDAP Persistence API (LPA). * * Copyright Trenton D. Adams <lpa at trentonadams daught ca> * * LPA is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * LPA is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with LPA. If not, see <http://www.gnu.org/licenses/>. * * See the COPYING file for more information. */ package ca.tnt.ldaputils.proprietary; import ca.tnt.ldaputils.ILdapOrganization; /** * Implements the tntbusiness LDAP objectClass. * <p/> * Created : 14-Apr-2006 9:24:54 PM MST * * @author Trenton D. Adams <trenta@athabascau.ca> */ public interface ILdapBusiness extends ILdapOrganization { public String getBusinessContact(); public String[] getLabeledURI(); public String getMail(); public void setBusinessContact(String businessContact, int operation); public void setLabeledURI(String labeledURI, int operation); public void setMail(String mail, int operation); /** * @return An array of all email addresses */ String[] getMails(); }
TrentonAdams/lpa
src/main/java/ca/tnt/ldaputils/proprietary/ILdapBusiness.java
Java
lgpl-3.0
1,523
#!/usr/bin/env python2 # Copyright (C) 2011-2012 by Imperial College London # Copyright (C) 2013 University of Oxford # Copyright (C) 2014 University of Edinburgh # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, version 3 of the License # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from collections import OrderedDict import copy import dolfin import ufl from caches import * from equation_solvers import * from exceptions import * from fenics_overrides import * from fenics_utils import * from pre_assembled_forms import * from statics import * from time_levels import * from time_functions import * __all__ = \ [ "AdjointVariableMap", "PAAdjointSolvers", "TimeFunctional" ] class AdjointVariableMap(object): """ A map between forward and adjoint variables. Indexing into the AdjointVariableMap with a forward Function yields an associated adjoint Function, and similarly indexing into the AdjointVariableMap with an adjoint Function yields an associated forward Function. Allocates adjoint Function s as required. """ def __init__(self): self.__a_tfns = {} self.__f_tfns = OrderedDict() self.__a_fns = {} self.__f_fns = OrderedDict() return def __getitem__(self, key): return self.__add(key) def __add(self, var): if isinstance(var, TimeFunction): if not var in self.__a_tfns: f_tfn = var a_tfn = AdjointTimeFunction(f_tfn) self.__a_tfns[f_tfn] = a_tfn self.__f_tfns[a_tfn] = f_tfn for level in f_tfn.all_levels(): self.__a_fns[f_tfn[level]] = a_tfn[level] self.__f_fns[a_tfn[level]] = f_tfn[level] return self.__a_tfns[var] elif isinstance(var, AdjointTimeFunction): if not var in self.__f_tfns: f_tfn = var.forward() a_tfn = var self.__a_tfns[f_tfn] = a_tfn self.__f_tfns[a_tfn] = f_tfn for level in f_tfn.all_levels(): self.__a_fns[f_tfn[level]] = a_tfn[level] self.__f_fns[a_tfn[level]] = f_tfn[level] return self.__f_tfns[var] elif isinstance(var, dolfin.Function): if is_static_coefficient(var): return var elif hasattr(var, "_time_level_data"): return self.__add(var._time_level_data[0])[var._time_level_data[1]] elif hasattr(var, "_adjoint_data"): if not var in self.__f_fns: self.__a_fns[var._adjoint_data[0]] = var self.__f_fns[var] = var._adjoint_data[0] return var._adjoint_data[0] else: if not var in self.__a_fns: a_fn = dolfin.Function(name = "%s_adjoint" % var.name(), *[var.function_space()]) a_fn._adjoint_data = [var] self.__a_fns[var] = a_fn self.__f_fns[a_fn] = var return self.__a_fns[var] elif isinstance(var, dolfin.Constant): return var else: raise InvalidArgumentException("Argument must be an AdjointTimeFunction, TimeFunction, Function, or Constant") def zero_adjoint(self): """ Zero all adjoint Function s, """ for a_fn in self.__f_fns: if not hasattr(a_fn, "_time_level_data"): a_fn.vector().zero() for a_tfn in self.__f_tfns: a_tfn.zero() return class TimeFunctional(object): """ A template for a functional with an explicit time dependence. """ def __init__(self): return def initialise(self, val = 0.0): """ Initialise, with an initial functional value of val. """ raise AbstractMethodException("initialise method not overridden") def addto(self, s): """ Add to the functional at the end of timestep number s. """ raise AbstractMethodException("addto method not overridden") def value(self): """ Return the functional value. """ raise AbstractMethodException("value method not overridden") def dependencies(self, s = None, non_symbolic = False): """ Return the functional dependencies at the end of timestep number s. If non_symbolic is true, also return any other dependencies on which the value of the functional could depend at the end of timestep number s. """ raise AbstractMethodException("dependencies method not overridden") def derivative(self, parameter, s): """ Return the derivative of the functional with respect to the specified Constant of Function at the end of the timestep number s. """ raise AbstractMethodException("derivative method not overridden") class PAAdjointSolvers(object): """ Defines a set of solves for adjoint equations, applying pre-assembly and linear solver caching optimisations. Expects as input a list of earlier forward equations and a list of later forward equations. If the earlier equations solve for {x_1, x_2, ...}, then the Function s on which the later equations depend should all be static or in the {x_1, x_2, ...}, although the failure of this requirement is not treated as an error. Constructor arguments: f_solves_a: Earlier time forward equations, as a list of AssignmentSolver s or EquationSolver s. f_solves_b: Later time forward equations, as a list of AssignmentSolver s or EquationSolver s. a_map: The AdjointVariableMap used to convert between forward and adjoint Function s. """ def __init__(self, f_solves_a, f_solves_b, a_map): if not isinstance(f_solves_a, list): raise InvalidArgumentException("f_solves_a must be a list of AssignmentSolver s or EquationSolver s") for f_solve in f_solves_a: if not isinstance(f_solve, (AssignmentSolver, EquationSolver)): raise InvalidArgumentException("f_solves_a must be a list of AssignmentSolver s or EquationSolver s") if not isinstance(f_solves_b, list): raise InvalidArgumentException("f_solves_b must be a list of AssignmentSolver s or EquationSolver s") for f_solve in f_solves_b: if not isinstance(f_solve, (AssignmentSolver, EquationSolver)): raise InvalidArgumentException("f_solves_b must be a list of AssignmentSolver s or EquationSolver s") if not isinstance(a_map, AdjointVariableMap): raise InvalidArgumentException("a_map must be an AdjointVariableMap") # Reverse causality f_solves_a = copy.copy(f_solves_a); f_solves_a.reverse() f_solves_b = copy.copy(f_solves_b); f_solves_b.reverse() la_a_forms = [] la_x = [] la_L_forms = [] la_L_as = [] la_bcs = [] la_solver_parameters = [] la_pre_assembly_parameters = [] la_keys = {} # Create an adjoint solve for each forward solve in f_solves_a, and add # the adjoint LHS for f_solve in f_solves_a: f_x = f_solve.x() a_x = a_map[f_x] a_space = a_x.function_space() assert(not a_x in la_keys) if isinstance(f_solve, AssignmentSolver): la_a_forms.append(None) la_bcs.append([]) la_solver_parameters.append(None) la_pre_assembly_parameters.append(dolfin.parameters["timestepping"]["pre_assembly"].copy()) else: assert(isinstance(f_solve, EquationSolver)) f_a = f_solve.tangent_linear()[0] f_a_rank = form_rank(f_a) if f_a_rank == 2: a_test, a_trial = dolfin.TestFunction(a_space), dolfin.TrialFunction(a_space) a_a = adjoint(f_a, adjoint_arguments = (a_test, a_trial)) la_a_forms.append(a_a) la_bcs.append(f_solve.hbcs()) la_solver_parameters.append(copy.deepcopy(f_solve.adjoint_solver_parameters())) else: assert(f_a_rank == 1) a_a = f_a la_a_forms.append(a_a) la_bcs.append(f_solve.hbcs()) la_solver_parameters.append(None) la_pre_assembly_parameters.append(f_solve.pre_assembly_parameters().copy()) la_x.append(a_x) la_L_forms.append(None) la_L_as.append([]) la_keys[a_x] = len(la_x) - 1 # Add adjoint RHS terms corresponding to terms in each forward solve in # f_solves_a and f_solves_b for f_solve in f_solves_a + f_solves_b: f_x = f_solve.x() a_dep = a_map[f_x] if isinstance(f_solve, AssignmentSolver): f_rhs = f_solve.rhs() if isinstance(f_rhs, ufl.expr.Expr): # Adjoin an expression assignment RHS for f_dep in ufl.algorithms.extract_coefficients(f_rhs): if isinstance(f_dep, dolfin.Function): a_x = a_map[f_dep] a_rhs = differentiate_expr(f_rhs, f_dep) * a_dep if a_x in la_keys and not isinstance(a_rhs, ufl.constantvalue.Zero): la_L_as[la_keys[a_x]].append(a_rhs) else: # Adjoin a linear combination assignment RHS for alpha, f_dep in f_rhs: a_x = a_map[f_dep] if a_x in la_keys: la_L_as[la_keys[a_x]].append((alpha, a_dep)) else: # Adjoin an equation RHS assert(isinstance(f_solve, EquationSolver)) a_trial = dolfin.TrialFunction(a_dep.function_space()) f_a_od = f_solve.tangent_linear()[1] for f_dep in f_a_od: a_x = a_map[f_dep] if a_x in la_keys: a_test = dolfin.TestFunction(a_x.function_space()) a_key = la_keys[a_x] a_form = -action(adjoint(f_a_od[f_dep], adjoint_arguments = (a_test, a_trial)), a_dep) if la_L_forms[a_key] is None: la_L_forms[a_key] = a_form else: la_L_forms[a_key] += a_form self.__a_map = a_map self.__a_a_forms = la_a_forms self.__a_x = la_x self.__a_L_forms = la_L_forms self.__a_L_as = la_L_as self.__a_bcs = la_bcs self.__a_solver_parameters = la_solver_parameters self.__a_pre_assembly_parameters = la_pre_assembly_parameters self.__a_keys = la_keys self.__functional = None self.reassemble() return def reassemble(self, *args): """ Reassemble the adjoint solvers. If no arguments are supplied then all equations are re-assembled. Otherwise, only the LHSs or RHSs which depend upon the supplied Constant s or Function s are reassembled. Note that this does not clear the assembly or linear solver caches -- hence if a static Constant, Function, or DirichletBC is modified then one should clear the caches before calling reassemble on the PAAdjointSolvers. """ def assemble_lhs(i): if self.__a_a_forms[i] is None: a_a = None a_solver = None else: a_a_rank = form_rank(self.__a_a_forms[i]) if a_a_rank == 2: static_bcs = n_non_static_bcs(self.__a_bcs[i]) == 0 static_form = is_static_form(self.__a_a_forms[i]) if len(self.__a_bcs[i]) > 0 and static_bcs and static_form: a_a = assembly_cache.assemble(self.__a_a_forms[i], bcs = self.__a_bcs[i], symmetric_bcs = self.__a_pre_assembly_parameters[i]["equations"]["symmetric_boundary_conditions"], compress = self.__a_pre_assembly_parameters[i]["bilinear_forms"]["compress_matrices"]) a_solver = linear_solver_cache.linear_solver(self.__a_a_forms[i], self.__a_solver_parameters[i], bcs = self.__a_bcs[i], symmetric_bcs = self.__a_pre_assembly_parameters[i]["equations"]["symmetric_boundary_conditions"], a = a_a) a_solver.set_operator(a_a) elif len(self.__a_bcs[i]) == 0 and static_form: a_a = assembly_cache.assemble(self.__a_a_forms[i], compress = self.__a_pre_assembly_parameters[i]["bilinear_forms"]["compress_matrices"]) a_solver = linear_solver_cache.linear_solver(self.__a_a_forms[i], self.__a_solver_parameters[i], a = a_a) a_solver.set_operator(a_a) else: a_a = PABilinearForm(self.__a_a_forms[i], pre_assembly_parameters = self.__a_pre_assembly_parameters[i]["bilinear_forms"]) a_solver = linear_solver_cache.linear_solver(self.__a_a_forms[i], self.__a_solver_parameters[i], self.__a_pre_assembly_parameters[i]["bilinear_forms"], static = a_a.is_static() and static_bcs, bcs = self.__a_bcs[i], symmetric_bcs = self.__a_pre_assembly_parameters[i]["equations"]["symmetric_boundary_conditions"]) else: assert(a_a_rank == 1) assert(self.__a_solver_parameters[i] is None) a_a = PALinearForm(self.__a_a_forms[i], pre_assembly_parameters = self.__a_pre_assembly_parameters[i]["linear_forms"]) a_solver = None return a_a, a_solver def assemble_rhs(i): if self.__a_L_forms[i] is None: return None else: return PALinearForm(self.__a_L_forms[i], pre_assembly_parameters = self.__a_pre_assembly_parameters[i]["linear_forms"]) if len(args) == 0: la_a, la_solvers = [], [] la_L = [] for i in xrange(len(self.__a_x)): a_a, a_solver = assemble_lhs(i) a_L = assemble_rhs(i) la_a.append(a_a) la_solvers.append(a_solver) la_L.append(a_L) self.set_functional(self.__functional) else: la_a, la_solvers = copy.copy(self.__a_a), copy.copy(self.__a_solvers) la_L = copy.copy(self.__a_L) for i in xrange(len(self.__a_x)): for dep in args: if not self.__a_a_forms[i] is None and dep in ufl.algorithms.extract_coefficients(self.__a_a_forms[i]): la_a[i], la_solvers[i] = assemble_lhs(i) break for dep in args: if not self.__a_L_forms[i] is None and dep in ufl.algorithms.extract_coefficients(self.__a_L_forms[i]): la_L[i] = assemble_rhs(i) break if isinstance(self.__functional, ufl.form.Form): for dep in args: if dep in ufl.algorithms.extract_coefficients(self.__functional): self.set_functional(self.__functional) break else: self.set_functional(self.__functional) self.__a_a, self.__a_solvers = la_a, la_solvers self.__a_L = la_L return def a_x(self): """ Return the adjoint Function s being solved for. """ return self.__a_x def solve(self): """ Solve all adjoint equations. """ for i in xrange(len(self.__a_x)): a_a = self.__a_a[i] a_x = self.__a_x[i] a_L = self.__a_L[i] a_L_as = self.__a_L_as[i] a_L_rhs = self.__a_L_rhs[i] a_bcs = self.__a_bcs[i] a_solver = self.__a_solvers[i] def evaluate_a_L_as(i): if isinstance(a_L_as[i], ufl.expr.Expr): if is_r0_function(a_x): L = evaluate_expr(a_L_as[i], copy = False) if isinstance(L, dolfin.GenericVector): l_L = L.sum() else: assert(isinstance(L, float)) l_L = L L = a_x.vector().copy() L[:] = l_L else: L = evaluate_expr(a_L_as[i], copy = True) if isinstance(L, float): l_L = L L = a_x.vector().copy() L[:] = l_L else: assert(isinstance(L, dolfin.GenericVector)) else: L = float(a_L_as[i][0]) * a_L_as[i][1].vector() return L def add_a_L_as(i, L): if isinstance(a_L_as[i], ufl.expr.Expr): l_L = evaluate_expr(a_L_as[i], copy = False) if is_r0_function(a_x): if isinstance(l_L, dolfin.GenericVector): l_L = l_L.sum() else: assert(isinstance(l_L, float)) if isinstance(l_L, dolfin.GenericVector): L += l_L else: L.add_local(l_L * numpy.ones(L.local_range(0)[1] - L.local_range(0)[0])) L.apply("insert") else: L.axpy(float(a_L_as[i][0]), a_L_as[i][1].vector()) return if a_L_rhs is None: if len(a_L_as) == 0: if a_L is None: if a_a is None or len(a_bcs) == 0: a_x.vector().zero() continue else: L = a_x.vector().copy() L.zero() else: L = assemble(a_L, copy = len(a_bcs) > 0) else: L = evaluate_a_L_as(0) for i in xrange(1, len(a_L_as)): add_a_L_as(i, L) if not a_L is None: L += assemble(a_L, copy = False) else: if isinstance(a_L_rhs, PAForm): L = assemble(a_L_rhs, copy = len(a_bcs) > 0 or not a_L is None or len(a_L_as) > 0) else: L = assemble(a_L_rhs) if not a_L is None: L += assemble(a_L, copy = False) for i in xrange(len(a_L_as)): add_a_L_as(i, L) if a_a is None: assert(len(a_bcs) == 0) assert(a_solver is None) a_x.vector()[:] = L elif a_solver is None: assert(a_a.rank() == 1) a_a = assemble(a_a, copy = False) assert(L.local_range() == a_a.local_range()) a_x.vector().set_local(L.array() / a_a.array()) a_x.vector().apply("insert") enforce_bcs(a_x.vector(), a_bcs) else: if isinstance(a_a, dolfin.GenericMatrix): enforce_bcs(L, a_bcs) else: a_a = assemble(a_a, copy = len(a_bcs) > 0) apply_bcs(a_a, a_bcs, L = L, symmetric_bcs = self.__a_pre_assembly_parameters[i]["equations"]["symmetric_boundary_conditions"]) a_solver.set_operator(a_a) a_solver.solve(a_x.vector(), L) return def set_functional(self, functional): """ Set a functional, defining associated adjoint RHS terms. """ if functional is None: self.__a_L_rhs = [None for i in xrange(len(self.__a_x))] self.__functional = None elif isinstance(functional, ufl.form.Form): if not form_rank(functional) == 0: raise InvalidArgumentException("functional must be rank 0") a_rhs = OrderedDict() for f_dep in ufl.algorithms.extract_coefficients(functional): if is_static_coefficient(f_dep): pass elif isinstance(f_dep, dolfin.Function): a_x = self.__a_map[f_dep] a_rhs[a_x] = derivative(functional, f_dep) elif isinstance(f_dep, (dolfin.Constant, dolfin.Expression)): pass else: raise DependencyException("Invalid dependency") self.__a_L_rhs = [None for i in xrange(len(self.__a_x))] for i, a_x in enumerate(a_rhs): if a_x in self.__a_keys: self.__a_L_rhs[self.__a_keys[a_x]] = PALinearForm(a_rhs[a_x], pre_assembly_parameters = self.__a_pre_assembly_parameters[i]["linear_forms"]) self.__functional = functional elif isinstance(functional, TimeFunctional): self.__a_L_rhs = [None for i in xrange(len(self.__a_x))] self.__functional = functional else: raise InvalidArgumentException("functional must be a Form or a TimeFunctional") return def update_functional(self, s): """ Update the adjoint RHS associated with the functional at the end of timestep s. """ if not isinstance(s, int) or s < 0: raise InvalidArgumentException("s must be a non-negative integer") if not isinstance(self.__functional, TimeFunctional): return a_rhs = OrderedDict() for f_dep in self.__functional.dependencies(s): if is_static_coefficient(f_dep): pass elif isinstance(f_dep, dolfin.Function): a_x = self.__a_map[f_dep] a_rhs[a_x] = self.__functional.derivative(f_dep, s) elif isinstance(f_dep, dolfin.Constant): pass else: raise DependencyException("Invalid dependency") self.__a_L_rhs = [None for i in xrange(len(self.__a_x))] for a_x in a_rhs: if not a_x in self.__a_keys: dolfin.warning("Missing functional dependency %s" % a_x.name()) else: self.__a_L_rhs[self.__a_keys[a_x]] = a_rhs[a_x] return
pf4d/dolfin-adjoint
timestepping/python/timestepping/pre_assembled_adjoint.py
Python
lgpl-3.0
23,635
/** ****************************************************************************** * @file stm32f4xx_it.c * @brief Interrupt Service Routines. ****************************************************************************** * * COPYRIGHT(c) 2015 STMicroelectronics * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal.h" #include "stm32f4xx.h" #include "stm32f4xx_it.h" #include "cmsis_os.h" /* USER CODE BEGIN 0 */ #include "hal.h" /* USER CODE END 0 */ /* External variables --------------------------------------------------------*/ extern void xPortSysTickHandler(void); extern ETH_HandleTypeDef heth; /******************************************************************************/ /* Cortex-M4 Processor Interruption and Exception Handlers */ /******************************************************************************/ /** * @brief This function handles System tick timer. */ void SysTick_Handler(void) { /* USER CODE BEGIN SysTick_IRQn 0 */ /* USER CODE END SysTick_IRQn 0 */ HAL_IncTick(); osSystickHandler(); /* USER CODE BEGIN SysTick_IRQn 1 */ /* USER CODE END SysTick_IRQn 1 */ } /******************************************************************************/ /* STM32F4xx Peripheral Interrupt Handlers */ /* Add here the Interrupt Handlers for the used peripherals. */ /* For the available peripheral interrupt handler names, */ /* please refer to the startup file (startup_stm32f4xx.s). */ /******************************************************************************/ /** * @brief This function handles EXTI line4 interrupt. */ void EXTI4_IRQHandler(void) { /* USER CODE BEGIN EXTI4_IRQn 0 */ /* USER CODE END EXTI4_IRQn 0 */ HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_4); /* USER CODE BEGIN EXTI4_IRQn 1 */ hal_rf230_isr(); /* USER CODE END EXTI4_IRQn 1 */ } /** * @brief This function handles Ethernet global interrupt. */ void ETH_IRQHandler(void) { /* USER CODE BEGIN ETH_IRQn 0 */ /* USER CODE END ETH_IRQn 0 */ HAL_ETH_IRQHandler(&heth); /* USER CODE BEGIN ETH_IRQn 1 */ /* USER CODE END ETH_IRQn 1 */ } /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
twischer/miniDTN
Src/stm32f4xx_it.c
C
lgpl-3.0
4,117
/* Copyright (C) 2014 Alik <aliktab@gmail.com> All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <I2C.h> #include <PCA9685.h> #define PCA9685_CHANNELS_QTY (uint8_t)16 #define PCA9685_MODE_1 (uint8_t)0x00 #define PCA9685_MODE_2 (uint8_t)0x01 #define PCA9685_SUBADR_1 (uint8_t)0x02 #define PCA9685_SUBADR_2 (uint8_t)0x03 #define PCA9685_SUBADR_3 (uint8_t)0x04 #define PCA9685_PRESCALE (uint8_t)0xfe #define PCA9685_LED0_ON_L (uint8_t)0x06 #define PCA9685_LED0_ON_H (uint8_t)0x07 #define PCA9685_LED0_OFF_L (uint8_t)0x08 #define PCA9685_LED0_OFF_H (uint8_t)0x09 #define PCA9685_ALLLED_ON_L (uint8_t)0xfa #define PCA9685_ALLLED_ON_H (uint8_t)0xfb #define PCA9685_ALLLED_OFF_L (uint8_t)0xfc #define PCA9685_ALLLED_OFF_H (uint8_t)0xfd #define PCA9685_MD1_RESTART (uint8_t)0x80 #define PCA9685_MD1_EXTCLK (uint8_t)0x40 #define PCA9685_MD1_AI (uint8_t)0x20 #define PCA9685_MD1_SLEEP (uint8_t)0x10 #define PCA9685_MD1_ALLCALL (uint8_t)0x01 #define PCA9685_WAKEUP_PAUSE (uint8_t)750 #define PCA9685_MAX_TIME (uint8_t)4095 extern I2C I2c; PCA9685::PCA9685(uint8_t _i2c_addr) { m_i2c_addr = _i2c_addr; } bool PCA9685::initialize(uint8_t _mode, float _freq) { const uint8_t prescale = floor(25000000.0 / (4096.0 * _freq) - 0.5); if (I2c.write(m_i2c_addr, PCA9685_MODE_1, (uint8_t)0x0)) return false; I2c.write(m_i2c_addr, PCA9685_MODE_1, PCA9685_MD1_SLEEP); I2c.write(m_i2c_addr, PCA9685_PRESCALE, prescale); I2c.write(m_i2c_addr, PCA9685_MODE_1, (uint8_t)0x0); delay(PCA9685_WAKEUP_PAUSE); I2c.write(m_i2c_addr, PCA9685_MODE_1, (uint8_t)(PCA9685_MD1_RESTART | PCA9685_MD1_AI | PCA9685_MD1_ALLCALL)); I2c.write(m_i2c_addr, PCA9685_MODE_2, _mode); return true; } uint8_t PCA9685::get_channels_qty() const { return PCA9685_CHANNELS_QTY; } void PCA9685::set_on_off(uint8_t _channel, uint16_t _t_on, uint16_t _t_off) { uint8_t Data[4] = { (_t_on & 0xff), (_t_on >> 8) & 0xff, (_t_off & 0xff), (_t_off >> 8) & 0xff }; I2c.write(m_i2c_addr, (uint8_t)(PCA9685_LED0_ON_L + 4 * _channel), Data, sizeof(Data)); } void PCA9685::set_PWM_8(uint8_t _channel, uint8_t _duty_cycle) { set_on_off( _channel, 0, (uint16_t)(((uint32_t)_duty_cycle * (uint32_t)PCA9685_MAX_TIME) / (uint32_t)UCHAR_MAX) ); } void PCA9685::set_PWM_16(uint8_t _channel, uint16_t _duty_cycle) { set_on_off( _channel, 0, (uint16_t)(((uint32_t)_duty_cycle * (uint32_t)PCA9685_MAX_TIME) / (uint32_t)USHRT_MAX) ); }
aliktab/PCA9685
PCA9685.cpp
C++
lgpl-3.0
3,187
lok_flit_pack_neutral_none = Lair:new { mobiles = {}, spawnLimit = 15, buildingsVeryEasy = {}, buildingsEasy = {}, buildingsMedium = {}, buildingsHard = {}, buildingsVeryHard = {}, } addLairTemplate("lok_flit_pack_neutral_none", lok_flit_pack_neutral_none)
kidaa/Awakening-Core3
bin/scripts/mobile/lair/creature_dynamic/lok_flit_pack_neutral_none.lua
Lua
lgpl-3.0
265
/* This file was generated by SableCC (http://www.sablecc.org/). */ package org.jdmp.core.script.jdmp.node; import org.jdmp.core.script.jdmp.analysis.Analysis; @SuppressWarnings("nls") public final class ADotRdivLevel3 extends PLevel3 { private PLevel3 _left_; private TDotRdiv _dotRdiv_; private PLevel2 _right_; public ADotRdivLevel3() { // Constructor } public ADotRdivLevel3(@SuppressWarnings("hiding") PLevel3 _left_, @SuppressWarnings("hiding") TDotRdiv _dotRdiv_, @SuppressWarnings("hiding") PLevel2 _right_) { // Constructor setLeft(_left_); setDotRdiv(_dotRdiv_); setRight(_right_); } public Object clone() { return new ADotRdivLevel3(cloneNode(this._left_), cloneNode(this._dotRdiv_), cloneNode(this._right_)); } public void apply(Switch sw) { ((Analysis) sw).caseADotRdivLevel3(this); } public PLevel3 getLeft() { return this._left_; } public void setLeft(PLevel3 node) { if (this._left_ != null) { this._left_.parent(null); } if (node != null) { if (node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._left_ = node; } public TDotRdiv getDotRdiv() { return this._dotRdiv_; } public void setDotRdiv(TDotRdiv node) { if (this._dotRdiv_ != null) { this._dotRdiv_.parent(null); } if (node != null) { if (node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._dotRdiv_ = node; } public PLevel2 getRight() { return this._right_; } public void setRight(PLevel2 node) { if (this._right_ != null) { this._right_.parent(null); } if (node != null) { if (node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._right_ = node; } public String toString() { return "" + toString(this._left_) + toString(this._dotRdiv_) + toString(this._right_); } void removeChild(@SuppressWarnings("unused") Node child) { // Remove child if (this._left_ == child) { this._left_ = null; return; } if (this._dotRdiv_ == child) { this._dotRdiv_ = null; return; } if (this._right_ == child) { this._right_ = null; return; } throw new RuntimeException("Not a child."); } void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild) { // Replace child if (this._left_ == oldChild) { setLeft((PLevel3) newChild); return; } if (this._dotRdiv_ == oldChild) { setDotRdiv((TDotRdiv) newChild); return; } if (this._right_ == oldChild) { setRight((PLevel2) newChild); return; } throw new RuntimeException("Not a child."); } }
jdmp/java-data-mining-package
jdmp-core/src/main/java/org/jdmp/core/script/jdmp/node/ADotRdivLevel3.java
Java
lgpl-3.0
2,678
var express = require('express'); module.exports = function(){ var menu = global.beans.menu; var obj = {}; obj.router = express.Router(); obj.router.get('/index', function (req, res) { menu.find().toArray(function(err,doc){ if(err){ throw err; } res.json(doc); }); }); return obj; };
xausky/post-bar
rest/menu.js
JavaScript
lgpl-3.0
331
/* This file is an image processing operation for GEGL * * GEGL is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * GEGL is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GEGL; if not, see <https://www.gnu.org/licenses/>. * * Copyright 2014, 2018 Øyvind Kolås <pippin@gimp.org> */ #include <math.h> #ifdef GEGL_PROPERTIES property_double (pan, _("Pan"), 0.0) description (_("Horizontal camera panning")) value_range (-360.0, 360.0) ui_meta ("unit", "degree") ui_meta ("direction", "cw") property_double (tilt, _("Tilt"), 0.0) description (_("Vertical camera panning")) value_range (-180.0, 180.0) ui_range (-180.0, 180.0) ui_meta ("unit", "degree") ui_meta ("direction", "cw") property_double (spin, _("Spin"), 0.0) description (_("Spin angle around camera axis")) value_range (-360.0, 360.0) ui_meta ("direction", "cw") property_double (zoom, _("Zoom"), 100.0) description (_("Zoom level")) value_range (0.01, 1000.0) property_int (width, _("Width"), -1) description (_("output/rendering width in pixels, -1 for input width")) value_range (-1, 10000) ui_meta ("role", "output-extent") ui_meta ("axis", "x") property_int (height, _("Height"), -1) description (_("output/rendering height in pixels, -1 for input height")) value_range (-1, 10000) ui_meta ("role", "output-extent") ui_meta ("axis", "y") property_boolean(inverse, _("Inverse transform"), FALSE) description (_("Do the inverse mapping, useful for touching up zenith, nadir or other parts of panorama.")) property_enum (sampler_type, _("Resampling method"), GeglSamplerType, gegl_sampler_type, GEGL_SAMPLER_NEAREST) description (_("Image resampling method to use, for good results with double resampling when retouching panoramas, use nearest to generate the view and cubic or better for the inverse transform back to panorama.")) #else #define GEGL_OP_FILTER #define GEGL_OP_NAME panorama_projection #define GEGL_OP_C_SOURCE panorama-projection.c #include "config.h" #include <glib/gi18n-lib.h> #include "gegl-op.h" typedef struct _Transform Transform; struct _Transform { float pan; float tilt; float sin_tilt; float cos_tilt; float sin_spin; float cos_spin; float sin_negspin; float cos_negspin; float zoom; float spin; float xoffset; float width; float height; float in_width; float in_height; void (*mapfun) (Transform *transform, float x, float y, float *lon, float *lat); int reverse; int do_spin; int do_zoom; }; /* formulas from: * http://mathworld.wolfram.com/GnomonicProjection.html */ static void inline gnomonic_xy2ll (Transform *transform, float x, float y, float *lon, float *lat) { float p, c; float longtitude, latitude; float sin_c, cos_c; y -= 0.5f; x -= transform->xoffset; if (transform->do_spin) { float tx = x, ty = y; x = tx * transform->cos_spin - ty * transform->sin_spin; y = ty * transform->cos_spin + tx * transform->sin_spin; } if (transform->do_zoom) { x /= transform->zoom; y /= transform->zoom; } p = sqrtf (x*x+y*y); c = atan2f (p, 1); sin_c = sinf(c); cos_c = cosf(c); latitude = asinf (cos_c * transform->sin_tilt + ( y * sin_c * transform->cos_tilt) / p); longtitude = transform->pan + atan2f (x * sin_c, p * transform->cos_tilt * cos_c - y * transform->sin_tilt * sin_c); if (longtitude < 0.0f) longtitude += M_PI * 2; *lon = (longtitude / (M_PI * 2)); *lat = ((latitude + M_PI/2) / M_PI); } static void inline gnomonic_ll2xy (Transform *transform, float lon, float lat, float *x, float *y) { float cos_c, sin_lat, cos_lat, cos_lon_minus_pan; lat = lat * M_PI - M_PI/2; lon = lon * (M_PI * 2); sin_lat = sinf (lat); cos_lat = cosf (lat); cos_lon_minus_pan = cosf (lon - transform->pan); cos_c = (transform->sin_tilt * sin_lat + transform->cos_tilt * cos_lat * cos_lon_minus_pan); if (cos_c <= 0.01f) { *x = -.1f; *y = -.1f; return; } *x = ((cos_lat * sin (lon - transform->pan)) / cos_c); *y = ((transform->cos_tilt * sin_lat - transform->sin_tilt * cos_lat * cos_lon_minus_pan) / cos_c); if (transform->do_zoom) { *x *= transform->zoom; *y *= transform->zoom; } if (transform->do_spin) { float tx = *x, ty = *y; *x = tx * transform->cos_negspin - ty * transform->sin_negspin; *y = ty * transform->cos_negspin + tx * transform->sin_negspin; } *x += transform->xoffset; *y += 0.5f; } static void prepare_transform (Transform *transform, float pan, float spin, float zoom, float tilt, float width, float height, float input_width, float input_height, int inverse) { float xoffset = 0.5f; transform->reverse = inverse; if (inverse) transform->mapfun = gnomonic_ll2xy; else transform->mapfun = gnomonic_xy2ll; pan = pan / 360 * M_PI * 2; spin = spin / 360 * M_PI * 2; zoom = zoom / 100.0f; tilt = tilt / 360 * M_PI * 2; while (pan > M_PI) pan -= 2 * M_PI; if (width <= 0 || height <= 0) { width = input_height; height = width; xoffset = ((input_width - height)/height) / 2 + 0.5f; } else { float orig_width = width; width = height; xoffset = ((orig_width - height)/height) / 2 + 0.5f; } transform->do_spin = fabs (spin) > 0.000001 ? 1 : 0; transform->do_zoom = fabs (zoom-1.0) > 0.000001 ? 1 : 0; transform->pan = pan; transform->tilt = tilt; transform->spin = spin; transform->zoom = zoom; transform->xoffset = xoffset; transform->sin_tilt = sinf (tilt); transform->cos_tilt = cosf (tilt); transform->sin_spin = sinf (spin); transform->cos_spin = cosf (spin); transform->sin_negspin = sinf (-spin); transform->cos_negspin = cosf (-spin); transform->width = width; transform->height = height; transform->in_width = input_width; transform->in_height = input_height; if (inverse) { float tmp; #define swap(a,b) tmp = a; a = b; b= tmp; swap(transform->width, transform->in_width); swap(transform->height, transform->in_height); #undef swap } } static void prepare (GeglOperation *operation) { const Babl *space = gegl_operation_get_source_space (operation, "input"); GeglProperties *o = GEGL_PROPERTIES (operation); const Babl *format; if (o->sampler_type == GEGL_SAMPLER_NEAREST) format = babl_format_with_space ("RGBA float", space); else format = babl_format_with_space ("RaGaBaA float", space); gegl_operation_set_format (operation, "input", format); gegl_operation_set_format (operation, "output", format); } static GeglRectangle get_bounding_box (GeglOperation *operation) { GeglProperties *o = GEGL_PROPERTIES (operation); GeglRectangle result = {0,0,0,0}; if (o->width <= 0 || o->height <= 0) { GeglRectangle *in_rect; in_rect = gegl_operation_source_get_bounding_box (operation, "input"); if (in_rect) { result = *in_rect; } else { result.width = 320; result.height = 200; } } else { result.width = o->width; result.height = o->height; } return result; } static void prepare_transform2 (Transform *transform, GeglOperation *operation, gint level) { gint factor = 1 << level; GeglProperties *o = GEGL_PROPERTIES (operation); GeglRectangle in_rect = *gegl_operation_source_get_bounding_box (operation, "input"); prepare_transform (transform, o->pan, o->spin, o->zoom, o->tilt, o->width / factor, o->height / factor, in_rect.width, in_rect.height, o->inverse); } static GeglRectangle get_required_for_output (GeglOperation *operation, const gchar *input_pad, const GeglRectangle *region) { GeglRectangle result = *gegl_operation_source_get_bounding_box (operation, "input"); return result; } static gboolean process (GeglOperation *operation, GeglBuffer *input, GeglBuffer *output, const GeglRectangle *result, gint level) { GeglProperties *o = GEGL_PROPERTIES (operation); Transform transform; GeglSampler *sampler; gint factor = 1 << level; GeglBufferIterator *it; GeglBufferMatrix2 scale_matrix; GeglBufferMatrix2 *scale = NULL; gint sampler_type = o->sampler_type; const Babl *format_io = gegl_operation_get_format (operation, "output"); GeglSamplerGetFun getfun; level = 0; factor = 1; prepare_transform2 (&transform, operation, level); if (level) sampler_type = GEGL_SAMPLER_NEAREST; if (transform.reverse) { /* artifacts have been observed with these samplers */ if (sampler_type == GEGL_SAMPLER_NOHALO || sampler_type == GEGL_SAMPLER_LOHALO) sampler_type = GEGL_SAMPLER_CUBIC; } if (sampler_type != GEGL_SAMPLER_NEAREST && !(o->inverse == FALSE && abs(o->tilt < 33))) /* skip the computation of sampler neighborhood scale matrix in cases where * we are unlikely to be scaling down */ scale = &scale_matrix; sampler = gegl_buffer_sampler_new_at_level (input, format_io, sampler_type, 0); getfun = gegl_sampler_get_fun (sampler); { float ud = ((1.0f/transform.width)*factor); float vd = ((1.0f/transform.height)*factor); int abyss_mode = transform.reverse ? GEGL_ABYSS_NONE : GEGL_ABYSS_LOOP; it = gegl_buffer_iterator_new (output, result, level, format_io, GEGL_ACCESS_WRITE, GEGL_ABYSS_NONE, 1); while (gegl_buffer_iterator_next (it)) { GeglRectangle *roi = &it->items[0].roi; gint i; gint n_pixels = it->length; gint x = roi->width; /* initial x */ float u0 = (((roi->x*factor * 1.0f)/transform.width)); float u, v; float *out = it->items[0].data; u = u0; v = ((roi->y*factor * 1.0/transform.height)); if (scale) { for (i=0; i<n_pixels; i++) { float cx, cy; /* we need our own jacobian matrix approximator, * since we do not operate on pixel values */ #define gegl_sampler_compute_scale2(matrix, x, y) \ { \ float ax, ay, bx, by; \ gegl_unmap(x + 0.5 * ud, y, ax, ay); \ gegl_unmap(x - 0.5 * ud, y, bx, by); \ matrix.coeff[0][0] = (ax - bx); \ matrix.coeff[1][0] = (ay - by); \ gegl_unmap(x, y + 0.5 * ud, ax, ay); \ gegl_unmap(x, y - 0.5 * ud, bx, by); \ matrix.coeff[0][1] = (ax - bx); \ matrix.coeff[1][1] = (ay - by); \ } #define gegl_unmap(xx,yy,ud,vd) { \ float rx, ry; \ transform.mapfun (&transform, xx, yy, &rx, &ry); \ ud = rx;vd = ry;} gegl_sampler_compute_scale2 (scale_matrix, u, v); gegl_unmap(u,v, cx, cy); #undef gegl_unmap #if 1 if (scale_matrix.coeff[0][0] > 0.5f) scale_matrix.coeff[0][0] = (scale_matrix.coeff[0][0]-1.0) * transform.in_width; else if (scale_matrix.coeff[0][0] < -0.5f) scale_matrix.coeff[0][0] = (scale_matrix.coeff[0][0]+1.0) * transform.in_width; else scale_matrix.coeff[0][0] *= transform.in_width; if (scale_matrix.coeff[0][1] > 0.5f) scale_matrix.coeff[0][1] = (scale_matrix.coeff[0][1]-1.0) * transform.in_width; else if (scale_matrix.coeff[0][1] < -0.5f) scale_matrix.coeff[0][1] = (scale_matrix.coeff[0][1]+1.0) * transform.in_width; else scale_matrix.coeff[0][1] *= transform.in_width; scale_matrix.coeff[1][1] *= transform.in_height; scale_matrix.coeff[1][0] *= transform.in_height; #endif getfun (sampler, cx * transform.in_width + 0.5f, cy * transform.in_height + 0.5f, scale, out, abyss_mode); out += 4; /* update x, y and u,v coordinates */ x--; u+=ud; if (x == 0) { x = roi->width; u = u0; v += vd; } } } else { for (i=0; i<n_pixels; i++) { float cx, cy; transform.mapfun (&transform, u, v, &cx, &cy); getfun (sampler, cx * transform.in_width + 0.5f, cy * transform.in_height + 0.5f, scale, out, abyss_mode); out += 4; /* update x, y and u,v coordinates */ x--; u+=ud; if (x <= 0) { x = roi->width; u = u0; v += vd; } } } } } g_object_unref (sampler); return TRUE; } static gchar *composition = "<?xml version='1.0' encoding='UTF-8'?>" "<gegl>" "<node operation='gegl:panorama-projection' width='200' height='200'/>" "<node operation='gegl:load'>" " <params>" " <param name='path'>standard-panorama.png</param>" " </params>" "</node>" "</gegl>"; static void gegl_op_class_init (GeglOpClass *klass) { GeglOperationClass *operation_class; GeglOperationFilterClass *filter_class; operation_class = GEGL_OPERATION_CLASS (klass); filter_class = GEGL_OPERATION_FILTER_CLASS (klass); filter_class->process = process; operation_class->prepare = prepare; operation_class->threaded = TRUE; operation_class->get_bounding_box = get_bounding_box; operation_class->get_required_for_output = get_required_for_output; gegl_operation_class_set_keys (operation_class, "name", "gegl:panorama-projection", "title", _("Panorama Projection"), "reference-composition", composition, "reference-hash", "3ab9831053ff0a9e32623ecc8a148e67", "position-dependent", "true", "categories" , "map", "description", _("Do panorama viewer rendering mapping or its inverse for an equirectangular input image. (2:1 ratio containing 360x180 degree panorama)."), NULL); } #endif
jvesely/gegl
operations/common/panorama-projection.c
C
lgpl-3.0
15,585
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Qt 4.7: wordcount.pro Example File (qtconcurrent/wordcount/wordcount.pro)</title> <link rel="stylesheet" type="text/css" href="style/offline.css" /> </head> <body> <div class="header" id="qtdocheader"> <div class="content"> <a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a> </div> <div class="breadcrumb toolblock"> <ul> <li class="first"><a href="index.html">Home</a></li> <!-- Breadcrumbs go here --> </ul> </div> </div> <div class="content mainContent"> <h1 class="title">wordcount.pro Example File</h1> <span class="small-subtitle">qtconcurrent/wordcount/wordcount.pro</span> <!-- $$$qtconcurrent/wordcount/wordcount.pro-description --> <div class="descr"> <a name="details"></a> <pre class="cpp"> TEMPLATE = app TARGET += DEPENDPATH += . INCLUDEPATH += . # Input SOURCES += main.cpp CONFIG += console # install target.path = $$[QT_INSTALL_EXAMPLES]/qtconcurrent/wordcount sources.files = $$SOURCES $$HEADERS $$FORMS $$RESOURCES *.pro *.png sources.path = $$[QT_INSTALL_EXAMPLES]/qtconcurrent/wordcount INSTALLS += target sources symbian: include($$QT_SOURCE_TREE/examples/symbianpkgrules.pri)</pre> </div> <!-- @@@qtconcurrent/wordcount/wordcount.pro --> <div class="ft"> <span></span> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2008-2011 Nokia Corporation and/or its subsidiaries. Nokia, Qt and their respective logos are trademarks of Nokia Corporation in Finland and/or other countries worldwide.</p> <p> All other trademarks are property of their respective owners. <a title="Privacy Policy" href="http://qt.nokia.com/about/privacy-policy">Privacy Policy</a></p> <br /> <p> Licensees holding valid Qt Commercial licenses may use this document in accordance with the Qt Commercial License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Nokia.</p> <p> Alternatively, this document may be used under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.</p> </div> </body> </html>
ssangkong/NVRAM_KWU
qt-everywhere-opensource-src-4.7.4/doc/html/qtconcurrent-wordcount-wordcount-pro.html
HTML
lgpl-3.0
2,575
/* Mercurium C/C++ Compiler Copyright (C) 2006-2008 - Roger Ferrer Ibanez <roger.ferrer@bsc.es> Barcelona Supercomputing Center - Centro Nacional de Supercomputacion Universitat Politecnica de Catalunya This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TL_PRAGMASUPPORT_HPP #define TL_PRAGMASUPPORT_HPP #include <string> #include "tl-compilerphase.hpp" #include "tl-langconstruct.hpp" #include "tl-handler.hpp" #include "tl-traverse.hpp" #include "tl-source.hpp" #include "cxx-attrnames.h" namespace TL { class PragmaCustomClause : public LangConstruct { private: std::string _clause_name; ObjectList<AST_t> filter_pragma_clause(); bool _parsed_expressions; ObjectList<Expression> _expressions; public: PragmaCustomClause(const std::string& src, AST_t ref, ScopeLink scope_link) : LangConstruct(ref, scope_link), _clause_name(src), _parsed_expressions(false) { } // Convenience function, it returns all the arguments parsed as expressions ObjectList<Expression> get_expression_list(); // Convenience function, it returns all the id-expressions of the arguments when // parsed as expressions ObjectList<IdExpression> id_expressions(IdExpressionCriteria criteria = VALID_SYMBOLS); // Raw clause arguments for custom parsing ObjectList<std::string> get_arguments(); // Raw clause arguments tree for custom parsing ObjectList<AST_t> get_arguments_tree(); // States whether the clause was in the pragma bool is_defined(); // return the name of the current clause std::string get_clause_name() { return _clause_name; } }; class PragmaCustomConstruct : public LangConstruct { public: PragmaCustomConstruct(AST_t ref, ScopeLink scope_link) : LangConstruct(ref, scope_link) { } std::string get_pragma(); std::string get_directive(); bool is_directive(); bool is_construct(); Statement get_statement(); AST_t get_declaration(); bool is_function_definition(); bool is_parameterized(); ObjectList<Expression> get_parameter_expressions(); ObjectList<std::string> get_parameter_arguments(); PragmaCustomClause get_clause(const std::string& name); }; typedef std::map<std::string, Signal1<PragmaCustomConstruct> > CustomFunctorMap; class PragmaCustomDispatcher : public TraverseFunctor { private: std::string _pragma_handled; CustomFunctorMap& _pre_map; CustomFunctorMap& _post_map; void dispatch_pragma_construct(CustomFunctorMap& search_map, Context ctx, AST_t node); public: PragmaCustomDispatcher(const std::string& pragma_handled, CustomFunctorMap& pre_map, CustomFunctorMap& post_map); virtual void preorder(Context ctx, AST_t node); virtual void postorder(Context ctx, AST_t node); }; //! Base class for all compiler phases working on user defined pragma lines /*! * Configuration of mcxx will require a 'pragma_prefix' line in order * to properly parse these pragma lines. In addition, the phases * will have to call register_directive and register_construct * accordingly to register specific constructs and directives. */ class PragmaCustomCompilerPhase : public CompilerPhase { private: std::string _pragma_handled; PragmaCustomDispatcher _pragma_dispatcher; public: //! Constructor /*! * \param pragma_handled The pragma prefix actually handled in this phase. */ PragmaCustomCompilerPhase(const std::string& pragma_handled); //! Entry point of the phase /*! * This function registers traverse functors to perform * a traversal on all the constructs and directives. */ virtual void run(DTO& data_flow); //! Custom functor map for directives found in preorder CustomFunctorMap on_directive_pre; //! Custom functor map for directives found in preorder CustomFunctorMap on_directive_post; //! Function to register a directive /*! * This is required for successful parsing of directives */ void register_directive(const std::string& name); //! Function to register a construct /*! * This is required for successful parsing of construct */ void register_construct(const std::string& name); }; } #endif // TL_PRAGMASUPPORT_HPP
drpicox/acotescc
src/tl/tl-pragmasupport.hpp
C++
lgpl-3.0
5,699
/* * (C) Copyright 2009-2013 CNRS. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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. * * Contributors: Luc Hogie (CNRS, I3S laboratory, University of Nice-Sophia Antipolis) Aurelien Lancin (Coati research team, Inria) Christian Glacet (LaBRi, Bordeaux) David Coudert (Coati research team, Inria) Fabien Crequis (Coati research team, Inria) Grégory Morel (Coati research team, Inria) Issam Tahiri (Coati research team, Inria) Julien Fighiera (Aoste research team, Inria) Laurent Viennot (Gang research-team, Inria) Michel Syska (I3S, University of Nice-Sophia Antipolis) Nathann Cohen (LRI, Saclay) */ package grph.algo.k_shortest_paths; import grph.Grph; import grph.path.Path; import grph.properties.NumericalProperty; import java.util.List; public abstract class KShortestPathsAlgorithm<P extends Path> { public abstract List<P> compute(Grph g, int s, int t, int k, NumericalProperty weights); }
MichaelRoeder/Grph
src/main/java/grph/algo/k_shortest_paths/KShortestPathsAlgorithm.java
Java
lgpl-3.0
1,442
/* $Id: ncbimempool.cpp 113238 2007-10-31 16:37:10Z vasilche $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: * Eugene Vasilchenko * * File Description: * Memory pool for fast allocation of memory for localized set of CObjects, * e.g. when deserializing big object tree. * Standard CObject and CRef classes for reference counter based GC * */ #include <ncbi_pch.hpp> #include <corelib/ncbimempool.hpp> #include <corelib/error_codes.hpp> //#define DEBUG_MEMORY_POOL #define NCBI_USE_ERRCODE_X Corelib_Object BEGIN_NCBI_SCOPE static const size_t kDefaultChunkSize = 8192; static const size_t kMinChunkSize = 128; static const size_t kDefaultThresholdRatio = 16; static const size_t kMinThresholdRatio = 2; static const size_t kMinThreshold = 4; #if defined(_DEBUG) && defined (DEBUG_MEMORY_POOL) namespace { static CAtomicCounter sx_chunks_counter; static CAtomicCounter::TValue sx_max_counter; static struct SPrinter { ~SPrinter() { if ( sx_max_counter ) { ERR_POST_X(9, "Max memory chunks: " << sx_max_counter); ERR_POST_X(10, "Final memory chunks: " << sx_chunks_counter.Get()); } } } sx_printer; inline void RegisterMemoryChunk(size_t /*size*/) { CAtomicCounter::TValue value = sx_chunks_counter.Add(1); if ( value > sx_max_counter ) { sx_max_counter = value; } } inline void DeregisterMemoryChunk(size_t /*size*/) { sx_chunks_counter.Add(-1); } } #else # define RegisterMemoryChunk(size) # define DeregisterMemoryChunk(size) #endif #ifdef _DEBUG # define ObjFatal Fatal #else # define ObjFatal Critical #endif class CObjectMemoryPoolChunk : public CObject { private: CObjectMemoryPoolChunk(size_t size) : m_CurPtr(m_Memory), m_EndPtr(m_Memory+size) { RegisterMemoryChunk(size); } public: static CObjectMemoryPoolChunk* CreateChunk(size_t size); ~CObjectMemoryPoolChunk(void) { DeregisterMemoryChunk(m_EndPtr-m_Memory); } struct SHeader { enum { eMagicAllocated = 0x3f6345ad, eMagicDeallocated = 0x63d83644 }; CObjectMemoryPoolChunk* m_ChunkPtr; int m_Magic; }; void IncrementObjectCount(void) { AddReference(); } void DecrementObjectCount(void) { RemoveReference(); } void* Allocate(size_t size); static CObjectMemoryPoolChunk* GetChunk(const void* ptr) { const SHeader* header = reinterpret_cast<const SHeader*>(ptr)-1; CObjectMemoryPoolChunk* chunk = header->m_ChunkPtr; if ( header->m_Magic != SHeader::eMagicAllocated ) { if ( header->m_Magic != SHeader::eMagicDeallocated ) { ERR_POST_X(11, ObjFatal << "CObjectMemoryPoolChunk::GetChunk: " "Bad chunk header magic: already freed"); } else { ERR_POST_X(12, ObjFatal << "CObjectMemoryPoolChunk::GetChunk: " "Bad chunk header magic"); } return 0; } if ( ptr <= chunk->m_Memory || ptr >= chunk->m_CurPtr ) { ERR_POST_X(13, ObjFatal << "CObjectMemoryPoolChunk::GetChunk: " "Object is beyond chunk memory"); } // now we mark header so it will not be deleted twice const_cast<SHeader*>(header)->m_Magic = SHeader::eMagicDeallocated; return chunk; } private: void* m_CurPtr; char* m_EndPtr; char m_Memory[1]; private: CObjectMemoryPoolChunk(const CObjectMemoryPoolChunk&); void operator=(const CObjectMemoryPoolChunk&); }; CObjectMemoryPoolChunk* CObjectMemoryPoolChunk::CreateChunk(size_t size) { void* ptr = CObject::operator new(sizeof(CObjectMemoryPoolChunk)+size); CObjectMemoryPoolChunk* chunk = ::new(ptr) CObjectMemoryPoolChunk(size); chunk->DoDeleteThisObject(); return chunk; } void* CObjectMemoryPoolChunk::Allocate(size_t size) { _ASSERT(size > 0); // align the size up to size header (usually 8 bytes) size += sizeof(SHeader)-1; if ( sizeof(SHeader) & (sizeof(SHeader)-1) ) { // size of header is not power of 2 size -= size % sizeof(SHeader); } else { // size of header is power of 2 -> we can use bit operation size &= ~(sizeof(SHeader)-1); } // calculate new pointers SHeader* header = reinterpret_cast<SHeader*>(m_CurPtr); char* ptr = reinterpret_cast<char*>(header + 1); char* end = ptr + size; // check if space is enough if ( end > m_EndPtr ) { return 0; } // initialize the header header->m_ChunkPtr = this; header->m_Magic = SHeader::eMagicAllocated; // all checks are done, now we update chunk _ASSERT(m_CurPtr == header); m_CurPtr = end; // increment object counter in this chunk IncrementObjectCount(); return ptr; } CObjectMemoryPool::CObjectMemoryPool(size_t chunk_size) { SetChunkSize(chunk_size); } CObjectMemoryPool::~CObjectMemoryPool(void) { } void CObjectMemoryPool::SetChunkSize(size_t chunk_size) { if ( chunk_size == 0 ) { chunk_size = kDefaultChunkSize; } if ( chunk_size < kMinChunkSize ) { chunk_size = kMinChunkSize; } m_ChunkSize = chunk_size; SetMallocThreshold(0); } void CObjectMemoryPool::SetMallocThreshold(size_t malloc_threshold) { if ( malloc_threshold == 0 ) { malloc_threshold = m_ChunkSize / kDefaultThresholdRatio; } size_t min_threshold = kMinThreshold; if ( malloc_threshold < min_threshold ) { malloc_threshold = min_threshold; } size_t max_threshold = m_ChunkSize / kMinThresholdRatio; if ( malloc_threshold > max_threshold ) { malloc_threshold = max_threshold; } m_MallocThreshold = malloc_threshold; } void* CObjectMemoryPool::Allocate(size_t size) { if ( size > m_MallocThreshold ) { return 0; } for ( int i = 0; i < 2; ++i ) { if ( !m_CurrentChunk ) { m_CurrentChunk = CObjectMemoryPoolChunk::CreateChunk(m_ChunkSize); } void* ptr = m_CurrentChunk->Allocate(size); if ( ptr ) { return ptr; } m_CurrentChunk.Reset(); } ERR_POST_X_ONCE(14, "CObjectMemoryPool::Allocate("<<size<<"): " "double fault in chunk allocator"); return 0; } void CObjectMemoryPool::Deallocate(void* ptr) { CObjectMemoryPoolChunk* chunk = CObjectMemoryPoolChunk::GetChunk(ptr); if ( chunk ) { chunk->DecrementObjectCount(); } } void CObjectMemoryPool::Delete(const CObject* object) { CObjectMemoryPoolChunk* chunk = CObjectMemoryPoolChunk::GetChunk(object); if ( chunk ) { const_cast<CObject*>(object)->~CObject(); chunk->DecrementObjectCount(); } else { ERR_POST_X(15, Critical << "CObjectMemoryPool::Delete(): " "cannot determine the chunk, memory will not be released"); const_cast<CObject*>(object)->~CObject(); } } END_NCBI_SCOPE
kyungtaekLIM/PSI-BLASTexB
src/ncbi-blast-2.5.0+/c++/src/corelib/ncbimempool.cpp
C++
lgpl-3.0
8,479
# This file is part of Libusb for Ruby. # # Libusb for Ruby is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Libusb for Ruby is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Libusb for Ruby. If not, see <http://www.gnu.org/licenses/>. require 'libusb/call' module LIBUSB class Endpoint < FFI::Struct include Comparable layout :bLength, :uint8, :bDescriptorType, :uint8, :bEndpointAddress, :uint8, :bmAttributes, :uint8, :wMaxPacketSize, :uint16, :bInterval, :uint8, :bRefresh, :uint8, :bSynchAddress, :uint8, :extra, :pointer, :extra_length, :int # Size of Descriptor in Bytes (7 bytes) def bLength self[:bLength] end # Descriptor type (0x05) def bDescriptorType self[:bDescriptorType] end # The address of the endpoint described by this descriptor. # # * Bits 0..3: Endpoint Number. # * Bits 4..6: Reserved. Set to Zero # * Bits 7: Direction 0 = Out, 1 = In (Ignored for Control Endpoints) # # @return [Integer] # # @see #endpoint_number # @see #direction def bEndpointAddress self[:bEndpointAddress] end # @return [Integer] def endpoint_number bEndpointAddress & 0b1111 end # @return [Symbol] Either +:in+ or +:out+ def direction bEndpointAddress & ENDPOINT_IN == 0 ? :out : :in end # Attributes which apply to the endpoint when it is configured using the {Configuration#bConfigurationValue}. # # * Bits 1..0: Transfer Type # * 00 = Control # * 01 = Isochronous # * 10 = Bulk # * 11 = Interrupt # * Bits 7..2: are reserved. If Isochronous endpoint, # * Bits 3..2: Synchronisation Type (Iso Mode) # * 00 = No Synchonisation # * 01 = Asynchronous # * 10 = Adaptive # * 11 = Synchronous # * Bits 5..4: Usage Type (Iso Mode) # * 00 = Data Endpoint # * 01 = Feedback Endpoint # * 10 = Explicit Feedback Data Endpoint # * 11 = Reserved # # @return [Integer] # # @see #transfer_type # @see #usage_type # @see #synchronization_type def bmAttributes self[:bmAttributes] end TransferTypes = [:control, :isochronous, :bulk, :interrupt] # @return [Symbol] One of {TransferTypes} def transfer_type TransferTypes[bmAttributes & 0b11] end SynchronizationTypes = [:no_synchronization, :asynchronous, :adaptive, :synchronous] # @return [Symbol] One of {SynchronizationTypes} def synchronization_type return unless transfer_type == :isochronous SynchronizationTypes[(bmAttributes & 0b1100) >> 2] end UsageTypes = [:data, :feedback, :implicit_feedback, :unknown] # @return [Symbol] One of {UsageTypes} def usage_type return unless transfer_type == :isochronous UsageTypes[(bmAttributes & 0b110000) >> 4] end # Maximum Packet Size this endpoint is capable of sending or receiving def wMaxPacketSize self[:wMaxPacketSize] end # Interval for polling endpoint data transfers. Value in frame counts. # Ignored for Bulk & Control Endpoints. Isochronous must equal 1 and field # may range from 1 to 255 for interrupt endpoints. # # The interval is respected by the kernel driver, so user mode processes # using libusb don't need to care about it. def bInterval self[:bInterval] end # For audio devices only: the rate at which synchronization feedback is provided. def bRefresh self[:bRefresh] end # For audio devices only: the address if the synch endpoint. def bSynchAddress self[:bSynchAddress] end # Extra descriptors. # # @return [String] def extra return if self[:extra].null? self[:extra].read_string(self[:extra_length]) end def initialize(setting, *args) @setting = setting super(*args) end # @return [Setting] the setting this endpoint belongs to. attr_reader :setting def inspect type = [transfer_type, synchronization_type, usage_type].compact "\#<#{self.class} #{endpoint_number} #{direction} #{type.join(" ")}>" end # The {Device} this Endpoint belongs to. def device() self.setting.interface.configuration.device end # The {Configuration} this Endpoint belongs to. def configuration() self.setting.interface.configuration end # The {Interface} this Endpoint belongs to. def interface() self.setting.interface end def <=>(o) t = setting<=>o.setting t = bEndpointAddress<=>o.bEndpointAddress if t==0 t end if Call.respond_to?(:libusb_get_ss_endpoint_companion_descriptor) # @method ss_companion # Get the endpoints superspeed endpoint companion descriptor (if any). # # Since libusb version 1.0.16. # # @return [SsCompanion] def ss_companion ep_comp = FFI::MemoryPointer.new :pointer res = Call.libusb_get_ss_endpoint_companion_descriptor( device.context.instance_variable_get(:@ctx), pointer, ep_comp ) LIBUSB.raise_error res, "in libusb_get_ss_endpoint_companion_descriptor" if res!=0 SsCompanion.new ep_comp.read_pointer end end end end
larskanis/libusb
lib/libusb/endpoint.rb
Ruby
lgpl-3.0
5,797
/* DO NOT EDIT THIS FILE - it is machine generated */ #include "jni.h" #include <math.h> #include "../global/functions.h" /* Header for class org_algo4j_math_Trigonometric */ #pragma clang diagnostic push #pragma ide diagnostic ignored "OCUnusedGlobalDeclarationInspection" #ifndef _Included_org_algo4j_math_Trigonometric #define _Included_org_algo4j_math_Trigonometric #ifdef __cplusplus extern "C" { #endif /// __cplusplus /** * Class: org_algo4j_math_Trigonometric * Method: sin * Signature: (D)D */ JNIEXPORT auto JNICALL Java_org_algo4j_math_Trigonometric_sin( JNIEnv *, jclass, jdouble ) -> jdouble; /** * Class: org_algo4j_math_Trigonometric * Method: cos * Signature: (D)D */ JNIEXPORT auto JNICALL Java_org_algo4j_math_Trigonometric_cos( JNIEnv *, jclass, jdouble ) -> jdouble; /** * Class: org_algo4j_math_Trigonometric * Method: tan * Signature: (D)D */ JNIEXPORT auto JNICALL Java_org_algo4j_math_Trigonometric_tan( JNIEnv *, jclass, jdouble ) -> jdouble; /** * Class: org_algo4j_math_Trigonometric * Method: cot * Signature: (D)D */ JNIEXPORT auto JNICALL Java_org_algo4j_math_Trigonometric_cot( JNIEnv *, jclass, jdouble ) -> jdouble; /** * Class: org_algo4j_math_Trigonometric * Method: csc * Signature: (D)D */ JNIEXPORT auto JNICALL Java_org_algo4j_math_Trigonometric_csc( JNIEnv *, jclass, jdouble ) -> jdouble; /** * Class: org_algo4j_math_Trigonometric * Method: sec * Signature: (D)D */ JNIEXPORT auto JNICALL Java_org_algo4j_math_Trigonometric_sec( JNIEnv *, jclass, jdouble ) -> jdouble; #ifdef __cplusplus } #endif /// __cplusplus #endif /// _Included_org_algo4j_math_Trigonometric #pragma clang diagnostic pop
ice1000/algo4j
jni/math/Trigonometric.h
C
lgpl-3.0
1,751
/*-------------------------------------------------------------------- (C) Copyright 2006-2011 Barcelona Supercomputing Center Centro Nacional de Supercomputacion This file is part of Mercurium C/C++ source-to-source compiler. See AUTHORS file in the top level directory for information regarding developers and contributors. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. Mercurium C/C++ source-to-source compiler is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Mercurium C/C++ source-to-source compiler; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. --------------------------------------------------------------------*/ /* <testinfo> test_generator=config/mercurium-ss </testinfo> */ #pragma css task input(a) void f(int a);
sdruix/AutomaticParallelization
tests/06_phases_starss.dg/success_smpss-006.c
C
lgpl-3.0
1,321
<?php /* * Copyright (c) 2012-2016, Hofmänner New Media. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This file is part of the N2N FRAMEWORK. * * The N2N FRAMEWORK is free software: you can redistribute it and/or modify it under the terms of * the GNU Lesser General Public License as published by the Free Software Foundation, either * version 2.1 of the License, or (at your option) any later version. * * N2N 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: http://www.gnu.org/licenses/ * * The following people participated in this project: * * Andreas von Burg.....: Architect, Lead Developer * Bert Hofmänner.......: Idea, Frontend UI, Community Leader, Marketing * Thomas Günther.......: Developer, Hangar */ namespace n2n\web\http\payload\impl; use n2n\web\http\payload\BufferedPayload; use n2n\web\http\Response; class HtmlPayload extends BufferedPayload { private $htmlStr; public function __construct(string $htmlStr) { $this->htmlStr = $htmlStr; } /** * {@inheritDoc} * @see \n2n\web\http\payload\BufferedPayload::getBufferedContents() */ public function getBufferedContents(): string { return $this->htmlStr; } /** * {@inheritDoc} * @see \n2n\web\http\payload\Payload::prepareForResponse() */ public function prepareForResponse(Response $response): void { $response->setHeader('Content-Type: text/html; charset=utf-8'); } /** * {@inheritDoc} * @see \n2n\web\http\payload\Payload::toKownPayloadString() */ public function toKownPayloadString(): string { return 'Html Payload'; } }
n2n/n2n-web
src/app/n2n/web/http/payload/impl/HtmlPayload.php
PHP
lgpl-3.0
1,824
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.6.0_30) on Sat Oct 11 22:51:30 UTC 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class org.encog.app.analyst.csv.basic.BasicFile (Encog Core 3.3.0 API)</title> <meta name="date" content="2014-10-11"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.encog.app.analyst.csv.basic.BasicFile (Encog Core 3.3.0 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicFile.html" title="class in org.encog.app.analyst.csv.basic">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>PREV</li> <li>NEXT</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/encog/app/analyst/csv/basic//class-useBasicFile.html" target="_top">FRAMES</a></li> <li><a href="BasicFile.html" target="_top">NO FRAMES</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.encog.app.analyst.csv.basic.BasicFile" class="title">Uses of Class<br>org.encog.app.analyst.csv.basic.BasicFile</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicFile.html" title="class in org.encog.app.analyst.csv.basic">BasicFile</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.encog.app.analyst.csv">org.encog.app.analyst.csv</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.encog.app.analyst.csv.balance">org.encog.app.analyst.csv.balance</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#org.encog.app.analyst.csv.basic">org.encog.app.analyst.csv.basic</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.encog.app.analyst.csv.filter">org.encog.app.analyst.csv.filter</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#org.encog.app.analyst.csv.normalize">org.encog.app.analyst.csv.normalize</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.encog.app.analyst.csv.process">org.encog.app.analyst.csv.process</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#org.encog.app.analyst.csv.segregate">org.encog.app.analyst.csv.segregate</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.encog.app.analyst.csv.shuffle">org.encog.app.analyst.csv.shuffle</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#org.encog.app.analyst.csv.sort">org.encog.app.analyst.csv.sort</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.encog.app.quant.indicators">org.encog.app.quant.indicators</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#org.encog.app.quant.ninja">org.encog.app.quant.ninja</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.encog.app.analyst.csv"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicFile.html" title="class in org.encog.app.analyst.csv.basic">BasicFile</a> in <a href="../../../../../../../org/encog/app/analyst/csv/package-summary.html">org.encog.app.analyst.csv</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation"> <caption><span>Subclasses of <a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicFile.html" title="class in org.encog.app.analyst.csv.basic">BasicFile</a> in <a href="../../../../../../../org/encog/app/analyst/csv/package-summary.html">org.encog.app.analyst.csv</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/encog/app/analyst/csv/AnalystClusterCSV.html" title="class in org.encog.app.analyst.csv">AnalystClusterCSV</a></strong></code> <div class="block">Used by the analyst to cluster a CSV file.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/encog/app/analyst/csv/AnalystEvaluateCSV.html" title="class in org.encog.app.analyst.csv">AnalystEvaluateCSV</a></strong></code> <div class="block">Used by the analyst to evaluate a CSV file.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/encog/app/analyst/csv/AnalystEvaluateRawCSV.html" title="class in org.encog.app.analyst.csv">AnalystEvaluateRawCSV</a></strong></code> <div class="block">Used by the analyst to evaluate a CSV file.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.encog.app.analyst.csv.balance"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicFile.html" title="class in org.encog.app.analyst.csv.basic">BasicFile</a> in <a href="../../../../../../../org/encog/app/analyst/csv/balance/package-summary.html">org.encog.app.analyst.csv.balance</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation"> <caption><span>Subclasses of <a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicFile.html" title="class in org.encog.app.analyst.csv.basic">BasicFile</a> in <a href="../../../../../../../org/encog/app/analyst/csv/balance/package-summary.html">org.encog.app.analyst.csv.balance</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/encog/app/analyst/csv/balance/BalanceCSV.html" title="class in org.encog.app.analyst.csv.balance">BalanceCSV</a></strong></code> <div class="block">Balance a CSV file.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.encog.app.analyst.csv.basic"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicFile.html" title="class in org.encog.app.analyst.csv.basic">BasicFile</a> in <a href="../../../../../../../org/encog/app/analyst/csv/basic/package-summary.html">org.encog.app.analyst.csv.basic</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation"> <caption><span>Subclasses of <a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicFile.html" title="class in org.encog.app.analyst.csv.basic">BasicFile</a> in <a href="../../../../../../../org/encog/app/analyst/csv/basic/package-summary.html">org.encog.app.analyst.csv.basic</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicCachedFile.html" title="class in org.encog.app.analyst.csv.basic">BasicCachedFile</a></strong></code> <div class="block">Forms the foundation of all of the cached files in Encog Quant.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.encog.app.analyst.csv.filter"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicFile.html" title="class in org.encog.app.analyst.csv.basic">BasicFile</a> in <a href="../../../../../../../org/encog/app/analyst/csv/filter/package-summary.html">org.encog.app.analyst.csv.filter</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation"> <caption><span>Subclasses of <a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicFile.html" title="class in org.encog.app.analyst.csv.basic">BasicFile</a> in <a href="../../../../../../../org/encog/app/analyst/csv/filter/package-summary.html">org.encog.app.analyst.csv.filter</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/encog/app/analyst/csv/filter/FilterCSV.html" title="class in org.encog.app.analyst.csv.filter">FilterCSV</a></strong></code> <div class="block">This class can be used to remove certain rows from a CSV.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.encog.app.analyst.csv.normalize"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicFile.html" title="class in org.encog.app.analyst.csv.basic">BasicFile</a> in <a href="../../../../../../../org/encog/app/analyst/csv/normalize/package-summary.html">org.encog.app.analyst.csv.normalize</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation"> <caption><span>Subclasses of <a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicFile.html" title="class in org.encog.app.analyst.csv.basic">BasicFile</a> in <a href="../../../../../../../org/encog/app/analyst/csv/normalize/package-summary.html">org.encog.app.analyst.csv.normalize</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/encog/app/analyst/csv/normalize/AnalystNormalizeCSV.html" title="class in org.encog.app.analyst.csv.normalize">AnalystNormalizeCSV</a></strong></code> <div class="block">Normalize, or denormalize, a CSV file.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/encog/app/analyst/csv/normalize/AnalystNormalizeToEGB.html" title="class in org.encog.app.analyst.csv.normalize">AnalystNormalizeToEGB</a></strong></code> <div class="block">Normalize, or denormalize, a CSV file.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.encog.app.analyst.csv.process"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicFile.html" title="class in org.encog.app.analyst.csv.basic">BasicFile</a> in <a href="../../../../../../../org/encog/app/analyst/csv/process/package-summary.html">org.encog.app.analyst.csv.process</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation"> <caption><span>Subclasses of <a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicFile.html" title="class in org.encog.app.analyst.csv.basic">BasicFile</a> in <a href="../../../../../../../org/encog/app/analyst/csv/process/package-summary.html">org.encog.app.analyst.csv.process</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/encog/app/analyst/csv/process/AnalystProcess.html" title="class in org.encog.app.analyst.csv.process">AnalystProcess</a></strong></code> <div class="block">Perform many different types of transformations on a CSV.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.encog.app.analyst.csv.segregate"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicFile.html" title="class in org.encog.app.analyst.csv.basic">BasicFile</a> in <a href="../../../../../../../org/encog/app/analyst/csv/segregate/package-summary.html">org.encog.app.analyst.csv.segregate</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation"> <caption><span>Subclasses of <a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicFile.html" title="class in org.encog.app.analyst.csv.basic">BasicFile</a> in <a href="../../../../../../../org/encog/app/analyst/csv/segregate/package-summary.html">org.encog.app.analyst.csv.segregate</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/encog/app/analyst/csv/segregate/SegregateCSV.html" title="class in org.encog.app.analyst.csv.segregate">SegregateCSV</a></strong></code> <div class="block">This class is used to segregate a CSV file into several sub-files.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.encog.app.analyst.csv.shuffle"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicFile.html" title="class in org.encog.app.analyst.csv.basic">BasicFile</a> in <a href="../../../../../../../org/encog/app/analyst/csv/shuffle/package-summary.html">org.encog.app.analyst.csv.shuffle</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation"> <caption><span>Subclasses of <a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicFile.html" title="class in org.encog.app.analyst.csv.basic">BasicFile</a> in <a href="../../../../../../../org/encog/app/analyst/csv/shuffle/package-summary.html">org.encog.app.analyst.csv.shuffle</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/encog/app/analyst/csv/shuffle/ShuffleCSV.html" title="class in org.encog.app.analyst.csv.shuffle">ShuffleCSV</a></strong></code> <div class="block">Randomly shuffle the lines of a CSV file.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.encog.app.analyst.csv.sort"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicFile.html" title="class in org.encog.app.analyst.csv.basic">BasicFile</a> in <a href="../../../../../../../org/encog/app/analyst/csv/sort/package-summary.html">org.encog.app.analyst.csv.sort</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation"> <caption><span>Subclasses of <a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicFile.html" title="class in org.encog.app.analyst.csv.basic">BasicFile</a> in <a href="../../../../../../../org/encog/app/analyst/csv/sort/package-summary.html">org.encog.app.analyst.csv.sort</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/encog/app/analyst/csv/sort/SortCSV.html" title="class in org.encog.app.analyst.csv.sort">SortCSV</a></strong></code> <div class="block">Used to sort a CSV file by one, or more, fields.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.encog.app.quant.indicators"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicFile.html" title="class in org.encog.app.analyst.csv.basic">BasicFile</a> in <a href="../../../../../../../org/encog/app/quant/indicators/package-summary.html">org.encog.app.quant.indicators</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation"> <caption><span>Subclasses of <a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicFile.html" title="class in org.encog.app.analyst.csv.basic">BasicFile</a> in <a href="../../../../../../../org/encog/app/quant/indicators/package-summary.html">org.encog.app.quant.indicators</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/encog/app/quant/indicators/ProcessIndicators.html" title="class in org.encog.app.quant.indicators">ProcessIndicators</a></strong></code> <div class="block">Process indicators and generate output.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.encog.app.quant.ninja"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicFile.html" title="class in org.encog.app.analyst.csv.basic">BasicFile</a> in <a href="../../../../../../../org/encog/app/quant/ninja/package-summary.html">org.encog.app.quant.ninja</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation"> <caption><span>Subclasses of <a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicFile.html" title="class in org.encog.app.analyst.csv.basic">BasicFile</a> in <a href="../../../../../../../org/encog/app/quant/ninja/package-summary.html">org.encog.app.quant.ninja</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/encog/app/quant/ninja/NinjaFileConvert.html" title="class in org.encog.app.quant.ninja">NinjaFileConvert</a></strong></code> <div class="block">A simple class that shows how to convert financial data into the form that NinjaTrader can recognize.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/encog/app/analyst/csv/basic/BasicFile.html" title="class in org.encog.app.analyst.csv.basic">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>PREV</li> <li>NEXT</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/encog/app/analyst/csv/basic//class-useBasicFile.html" target="_top">FRAMES</a></li> <li><a href="BasicFile.html" target="_top">NO FRAMES</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2014. All Rights Reserved.</small></p> </body> </html>
ars22/WorkflowScheduling
lib/encog-core-3.3.0/apidocs/org/encog/app/analyst/csv/basic/class-use/BasicFile.html
HTML
lgpl-3.0
22,612
package org.molgenis.data.mapper.service.impl; import com.google.common.collect.Lists; import org.mockito.Mock; import org.molgenis.data.Entity; import org.molgenis.data.EntityManager; import org.molgenis.data.mapper.algorithmgenerator.service.AlgorithmGeneratorService; import org.molgenis.data.mapper.mapping.model.AttributeMapping; import org.molgenis.data.meta.AttributeType; import org.molgenis.data.meta.model.Attribute; import org.molgenis.data.semanticsearch.service.OntologyTagService; import org.molgenis.data.semanticsearch.service.SemanticSearchService; import org.molgenis.js.magma.JsMagmaScriptEvaluator; import org.molgenis.test.AbstractMockitoTest; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.molgenis.data.meta.AttributeType.*; public class AlgorithmServiceImplTest extends AbstractMockitoTest { @Mock private OntologyTagService ontologyTagService; @Mock private SemanticSearchService semanticSearhService; @Mock private AlgorithmGeneratorService algorithmGeneratorService; @Mock private EntityManager entityManager; @Mock private JsMagmaScriptEvaluator jsMagmaScriptEvaluator; private AlgorithmServiceImpl algorithmServiceImpl; @BeforeMethod public void setUpBeforeMethod() { algorithmServiceImpl = new AlgorithmServiceImpl(ontologyTagService, semanticSearhService, algorithmGeneratorService, entityManager, jsMagmaScriptEvaluator); } @Test(expectedExceptions = NullPointerException.class) public void testAlgorithmServiceImpl() { new AlgorithmServiceImpl(null, null, null, null, null); } @Test(expectedExceptions = AlgorithmException.class, expectedExceptionsMessageRegExp = "'invalidDate' can't be converted to type 'DATE'") public void testApplyConvertDateNumberFormatException() { testApplyConvertException("invalidDate", DATE); } @Test(expectedExceptions = AlgorithmException.class, expectedExceptionsMessageRegExp = "'invalidDateTime' can't be converted to type 'DATE_TIME'") public void testApplyConvertDateTimeNumberFormatException() { testApplyConvertException("invalidDateTime", DATE_TIME); } @Test(expectedExceptions = AlgorithmException.class, expectedExceptionsMessageRegExp = "'invalidDouble' can't be converted to type 'DECIMAL'") public void testApplyConvertDoubleNumberFormatException() { testApplyConvertException("invalidDouble", DECIMAL); } @Test(expectedExceptions = AlgorithmException.class, expectedExceptionsMessageRegExp = "'invalidInt' can't be converted to type 'INT'") public void testApplyConvertIntNumberFormatException() { testApplyConvertException("invalidInt", INT); } @Test(expectedExceptions = AlgorithmException.class, expectedExceptionsMessageRegExp = "'9007199254740991' is larger than the maximum allowed value for type 'INT'") public void testApplyConvertIntArithmeticException() { testApplyConvertException("9007199254740991", INT); } @Test(expectedExceptions = AlgorithmException.class, expectedExceptionsMessageRegExp = "'invalidLong' can't be converted to type 'LONG'") public void testApplyConvertLongNumberFormatException() { testApplyConvertException("invalidLong", LONG); } @Test public void testApplyAlgorithm() { Attribute attribute = mock(Attribute.class); String algorithm = "algorithm"; Entity entity = mock(Entity.class); when(jsMagmaScriptEvaluator.eval(algorithm, entity)).thenThrow(new NullPointerException()); Iterable<AlgorithmEvaluation> result = algorithmServiceImpl .applyAlgorithm(attribute, algorithm, Lists.newArrayList(entity)); AlgorithmEvaluation eval = result.iterator().next(); Assert.assertEquals(eval.getErrorMessage(), "Applying an algorithm on a null source value caused an exception. Is the target attribute required?"); } private void testApplyConvertException(String algorithmResult, AttributeType attributeType) { AttributeMapping attributeMapping = mock(AttributeMapping.class); String algorithm = "algorithm"; when(attributeMapping.getAlgorithm()).thenReturn(algorithm); Attribute targetAttribute = when(mock(Attribute.class).getDataType()).thenReturn(attributeType).getMock(); when(attributeMapping.getTargetAttribute()).thenReturn(targetAttribute); Entity sourceEntity = mock(Entity.class); when(jsMagmaScriptEvaluator.eval(algorithm, sourceEntity)).thenReturn(algorithmResult); algorithmServiceImpl.apply(attributeMapping, sourceEntity, null); } }
npklein/molgenis
molgenis-semantic-mapper/src/test/java/org/molgenis/data/mapper/service/impl/AlgorithmServiceImplTest.java
Java
lgpl-3.0
4,535
// 2016-01-30T15:09+08:00 // By myd using System; using System.Collections.Generic; using System.Text; using Microsoft.Win32; namespace SysAdminApp { public sealed class SysAdmin { private static readonly string key; private static readonly string explorerSubKey; private static readonly string systemSubKey; private static readonly Dictionary<string, Int32> noDrivesDict; static SysAdmin() { key = @"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies"; explorerSubKey = key + @"\Explorer"; systemSubKey = key + @"\System"; Int32 mask = 1; noDrivesDict = new Dictionary<string, Int32>(); for (char name = 'A'; name <= 'Z'; name++) { noDrivesDict[name+@":\"] = mask; mask <<= 1; } noDrivesDict["All"] = 0x03FFFFFF; } public static bool IsWinVistaOrHigher() { OperatingSystem os = Environment.OSVersion; return os.Platform == PlatformID.Win32NT && os.Version.Major >= 6; } public static SortedDictionary<string, bool> GetDriveVisibilityDict() { Int32 noDrivesValue = GetInt32Value(explorerSubKey, "NoDrives", 0); var dict = new SortedDictionary<string, bool>(); foreach (var driveInfo in System.IO.DriveInfo.GetDrives()) { string driveName = driveInfo.Name; dict[driveName] = !noDrivesDict.ContainsKey(driveName) || (noDrivesValue & noDrivesDict[driveName]) == 0; } return dict; } public static void SetDriveVisibility(SortedDictionary<string, bool> driveVisibilityDict) { Registry.SetValue(explorerSubKey, "NoDrives", GetNoDrivesValue(driveVisibilityDict), RegistryValueKind.DWord); } public static void SetNoDispCPL(bool noDispCPL) { OpenOption(systemSubKey, "NoDispCPL", noDispCPL); } public static bool GetNoDispCPL() { return IsOptionOpened(systemSubKey, "NoDispCPL"); } public static bool GetNoSetFolders() { return IsOptionOpened(explorerSubKey, "NoSetFolders"); } public static void SetNoSetFolders(bool noSetFolders) { OpenOption(explorerSubKey, "NoSetFolders", noSetFolders); } public static bool GetDisableRegistryTools() { return IsOptionOpened(systemSubKey, "DisableRegistryTools"); } public static void SetDisableRegistryTools(bool disableRegistryTools) { OpenOption(systemSubKey, "DisableRegistryTools", disableRegistryTools); } private static Int32 GetNoDrivesValue(SortedDictionary<string, bool> driveVisibilityDict) { Int32 value = 0; foreach (var item in driveVisibilityDict) { if (noDrivesDict.ContainsKey(item.Key)) { IntUtil.TriggleBits(ref value, noDrivesDict[item.Key], !item.Value); } } return value; } private static Int32 GetInt32Value(string keyName, string valueName, Int32 defaultValue) { try { object value = Registry.GetValue(keyName, valueName, defaultValue); return value != null ? (Int32)value : defaultValue; } catch (Exception) { return defaultValue; } } private static bool IsOptionOpened(string keyName, string valueName) { Int32 value = GetInt32Value(keyName, valueName, 0); return IntUtil.IsBitsSet(value, 0x00000001); } private static void OpenOption(string keyName, string valueName, bool open) { Int32 value = GetInt32Value(keyName, valueName, 0); IntUtil.TriggleBits(ref value, 0x00000001, open); Registry.SetValue(keyName, valueName, value, RegistryValueKind.DWord); } } }
myd7349/Ongoing-Study
c#/SysAdminApp/SysAdmin.cs
C#
lgpl-3.0
4,243
# Try to find allegro 5 # # ALLEGRO5_FOUND - system has allegro5 # ALLEGRO5_INCLUDE_DIR - the allrgo5 include directory # ALLEGRO5_LIBRARIES - Link these to use allegro5 # # Code taken from: https://github.com/dos1/Allegro5-CMake-Modules/blob/master/FindAllegro5.cmake FIND_PATH(ALLEGRO5_INCLUDE_DIR allegro5/allegro.h) SET(ALLEGRO5_NAMES ${ALLEGRO5_NAMES} allegro allegro_static liballegro liballegro_static) FIND_LIBRARY(ALLEGRO5_LIBRARY NAMES ${ALLEGRO5_NAMES} ) # handle the QUIETLY and REQUIRED arguments and set ALLEGRO5_FOUND to TRUE if # all listed variables are TRUE INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(ALLEGRO5 DEFAULT_MSG ALLEGRO5_LIBRARY ALLEGRO5_INCLUDE_DIR) IF(ALLEGRO5_FOUND) SET(ALLEGRO5_LIBRARIES ${ALLEGRO5_LIBRARY}) ENDIF(ALLEGRO5_FOUND) MARK_AS_ADVANCED(ALLEGRO5_LIBRARY ALLEGRO5_INCLUDE_DIR )
gilzoide/lallegro
src/FindAllegro5.cmake
CMake
lgpl-3.0
861
/* * Copyright 2010-2014 Bastian Eicher * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System.Collections.Generic; using Moq; using NanoByte.Common.Storage; using NUnit.Framework; using ZeroInstall.Services.Feeds; using ZeroInstall.Store.Model; using ZeroInstall.Store.Model.Preferences; using ZeroInstall.Store.Model.Selection; namespace ZeroInstall.Services.Solvers { /// <summary> /// Contains common code for testing specific <see cref="ISolver"/> implementations. /// </summary> public abstract class SolverTest<T> : TestWithContainer<T> where T : class, ISolver { [Test] public void Minimal() { RunAndAssert( feeds: new Dictionary<string, string> { {"http://test/app.xml", "<implementation version='1.0' id='app1'><command name='run' path='test-app' /></implementation>"} }, requirements: new Requirements {InterfaceID = "http://test/app.xml", Command = Command.NameRun}, expectedSelections: "<selection interface='http://test/app.xml' version='1.0' id='app1'><command name='run' path='test-app' /></selection>"); } [Test] public void SimpleDependency() { RunAndAssert( feeds: new Dictionary<string, string> { {"http://test/app.xml", "<implementation version='1.0' id='app1'><command name='run' path='test-app' /><requires interface='http://test/lib.xml' /></implementation>"}, {"http://test/lib.xml", "<implementation version='1.0' id='lib1' />"} }, requirements: new Requirements {InterfaceID = "http://test/app.xml", Command = Command.NameRun}, expectedSelections: "<selection interface='http://test/app.xml' version='1.0' id='app1'><command name='run' path='test-app' /><requires interface='http://test/lib.xml' /></selection>" + "<selection interface='http://test/lib.xml' version='1.0' id='lib1' />"); } [Test] public void OptionalDependency() { // satisfiable RunAndAssert( feeds: new Dictionary<string, string> { {"http://test/app.xml", "<implementation version='1.0' id='app1'><command name='run' path='test-app' /><requires interface='http://test/lib.xml' importance='recommended' /></implementation>"}, {"http://test/lib.xml", "<implementation version='1.0' id='lib1' />"} }, requirements: new Requirements {InterfaceID = "http://test/app.xml", Command = Command.NameRun}, expectedSelections: "<selection interface='http://test/app.xml' version='1.0' id='app1'><command name='run' path='test-app' /><requires interface='http://test/lib.xml' importance='recommended' /></selection>" + "<selection interface='http://test/lib.xml' version='1.0' id='lib1' />"); // not satisfiable RunAndAssert( feeds: new Dictionary<string, string> { {"http://test/app.xml", "<implementation version='1.0' id='app1'><command name='run' path='test-app' /><requires interface='http://test/lib.xml' importance='recommended' /></implementation>"}, {"http://test/lib.xml", ""} }, requirements: new Requirements {InterfaceID = "http://test/app.xml", Command = Command.NameRun}, expectedSelections: "<selection interface='http://test/app.xml' version='1.0' id='app1'><command name='run' path='test-app' /><requires interface='http://test/lib.xml' importance='recommended' /></selection>"); } [Test] public void CyclicDependency() { RunAndAssert( feeds: new Dictionary<string, string> { {"http://test/app.xml", "<implementation version='1.0' id='app1'><requires interface='http://test/lib.xml' /><command name='run' path='test-app' /></implementation>"}, {"http://test/lib.xml", "<implementation version='1.0' id='lib1'><requires interface='http://test/app.xml' /></implementation>"} }, requirements: new Requirements {InterfaceID = "http://test/app.xml", Command = Command.NameRun}, expectedSelections: "<selection interface='http://test/app.xml' version='1.0' id='app1'><requires interface='http://test/lib.xml' /><command name='run' path='test-app' /></selection>" + "<selection interface='http://test/lib.xml' version='1.0' id='lib1'><requires interface='http://test/app.xml' /></selection>"); } [Test] public void RunnerDependency() { RunAndAssert( feeds: new Dictionary<string, string> { {"http://test/app.xml", "<implementation version='1.0' id='app1'><command name='run' path='test-app'><runner interface='http://test/runner.xml' /></command></implementation>"}, {"http://test/runner.xml", "<implementation version='1.0' id='runner1'><command name='run' path='test-runner' /></implementation>"} }, requirements: new Requirements {InterfaceID = "http://test/app.xml", Command = Command.NameRun}, expectedSelections: "<selection interface='http://test/app.xml' version='1.0' id='app1'><command name='run' path='test-app'><runner interface='http://test/runner.xml' /></command></selection>" + "<selection interface='http://test/runner.xml' version='1.0' id='runner1'><command name='run' path='test-runner' /></selection>"); } [Test] public void ExecutableInDependency() { RunAndAssert( feeds: new Dictionary<string, string> { {"http://test/app.xml", "<implementation version='1.0' id='app1'><command name='run' path='test-app' /><requires interface='http://test/helper.xml'><executable-in-path/></requires></implementation>"}, {"http://test/helper.xml", "<implementation version='1.0' id='helper1'><command name='run' path='test-helper' /></implementation>"} }, requirements: new Requirements {InterfaceID = "http://test/app.xml", Command = Command.NameRun}, expectedSelections: "<selection interface='http://test/app.xml' version='1.0' id='app1'><command name='run' path='test-app' /><requires interface='http://test/helper.xml'><executable-in-path/></requires></selection>" + "<selection interface='http://test/helper.xml' version='1.0' id='helper1'><command name='run' path='test-helper' /></selection>"); } [Test] public void MultipleCommandDependencies() { RunAndAssert( feeds: new Dictionary<string, string> { {"http://test/app.xml", "<implementation version='1.0' id='app1'><command name='run' path='test-app' /><requires interface='http://test/helper.xml'><executable-in-path name='helperA' command='commandA'/><executable-in-path name='helperB' command='commandB'/></requires></implementation>"}, { "http://test/helper.xml", "<implementation version='1.0' id='helper1'>" + " <command name='commandA' path='helperA' />" + " <command name='commandB' path='helperB'><runner interface='http://test/runner.xml' /></command>" + " <command name='commandC' path='helperC' />" + "</implementation>" }, {"http://test/runner.xml", "<implementation version='1.0' id='runner1'><command name='run' path='test-runner' /></implementation>"} }, requirements: new Requirements {InterfaceID = "http://test/app.xml", Command = Command.NameRun}, expectedSelections: "<selection interface='http://test/app.xml' version='1.0' id='app1'><command name='run' path='test-app' /><requires interface='http://test/helper.xml'><executable-in-path name='helperA' command='commandA'/><executable-in-path name='helperB' command='commandB'/></requires></selection>" + "<selection interface='http://test/helper.xml' version='1.0' id='helper1'><command name='commandA' path='helperA' /><command name='commandB' path='helperB'><runner interface='http://test/runner.xml' /></command></selection>" + "<selection interface='http://test/runner.xml' version='1.0' id='runner1'><command name='run' path='test-runner' /></selection>"); } [Test] public void SimpleFeedReference() { RunAndAssert( feeds: new Dictionary<string, string> { {"http://test/app1.xml", "<implementation version='1.0' id='app1'><command name='run' path='test-app1' /></implementation><feed src='http://test/app2.xml' />"}, {"http://test/app2.xml", "<implementation version='2.0' id='app2'><command name='run' path='test-app2' /></implementation>"} }, requirements: new Requirements {InterfaceID = "http://test/app1.xml", Command = Command.NameRun}, expectedSelections: "<selection interface='http://test/app1.xml' from-feed='http://test/app2.xml' version='2.0' id='app2'><command name='run' path='test-app2' /></selection>"); } [Test] public void CyclicFeedReference() { RunAndAssert( feeds: new Dictionary<string, string> { {"http://test/app1.xml", "<implementation version='1.0' id='app1'><command name='run' path='test-app1' /></implementation><feed src='http://test/app2.xml' />"}, {"http://test/app2.xml", "<implementation version='2.0' id='app2'><command name='run' path='test-app2' /></implementation><feed src='http://test/app1.xml' />"} }, requirements: new Requirements {InterfaceID = "http://test/app1.xml", Command = Command.NameRun}, expectedSelections: "<selection interface='http://test/app1.xml' from-feed='http://test/app2.xml' version='2.0' id='app2'><command name='run' path='test-app2' /></selection>"); } [Test] public void CustomFeedReference() { new InterfacePreferences {Feeds = {new FeedReference {Source = "http://test/app2.xml"}}}.SaveFor("http://test/app1.xml"); RunAndAssert( feeds: new Dictionary<string, string> { {"http://test/app1.xml", "<implementation version='1.0' id='app1'><command name='run' path='test-app1' /></implementation>"}, {"http://test/app2.xml", "<implementation version='2.0' id='app2'><command name='run' path='test-app2' /></implementation>"} }, requirements: new Requirements {InterfaceID = "http://test/app1.xml", Command = Command.NameRun}, expectedSelections: "<selection interface='http://test/app1.xml' from-feed='http://test/app2.xml' version='2.0' id='app2'><command name='run' path='test-app2' /></selection>"); } [Test] public void Restriction() { // without restriction RunAndAssert( feeds: new Dictionary<string, string> { {"http://test/app.xml", "<implementation version='1.0' id='app1'><command name='run' path='test-app' /><requires interface='http://test/liba.xml' /><requires interface='http://test/libb.xml' /></implementation>"}, {"http://test/liba.xml", "<implementation version='1.0' id='liba1' />"}, {"http://test/libb.xml", "<implementation version='1.0' id='libb1' /><implementation version='2.0' id='libb2' />"} }, requirements: new Requirements {InterfaceID = "http://test/app.xml", Command = Command.NameRun}, expectedSelections: "<selection interface='http://test/app.xml' version='1.0' id='app1'><command name='run' path='test-app' /><requires interface='http://test/liba.xml' /><requires interface='http://test/libb.xml' /></selection>" + "<selection interface='http://test/liba.xml' version='1.0' id='liba1' />" + "<selection interface='http://test/libb.xml' version='2.0' id='libb2' />"); // with restriction RunAndAssert( feeds: new Dictionary<string, string> { {"http://test/app.xml", "<implementation version='1.0' id='app1'><command name='run' path='test-app' /><requires interface='http://test/liba.xml' /><requires interface='http://test/libb.xml' /></implementation>"}, {"http://test/liba.xml", "<implementation version='1.0' id='liba1'><restricts interface='http://test/libb.xml' version='1.0' /></implementation>"}, {"http://test/libb.xml", "<implementation version='1.0' id='libb1' /><implementation version='2.0' id='libb2' />"} }, requirements: new Requirements {InterfaceID = "http://test/app.xml", Command = Command.NameRun}, expectedSelections: "<selection interface='http://test/app.xml' version='1.0' id='app1'><command name='run' path='test-app' /><requires interface='http://test/liba.xml' /><requires interface='http://test/libb.xml' /></selection>" + "<selection interface='http://test/liba.xml' version='1.0' id='liba1' />" + "<selection interface='http://test/libb.xml' version='1.0' id='libb1' />"); } [Test] public void ExtraRestrictions() { RunAndAssert( feeds: new Dictionary<string, string> { {"http://test/app.xml", "<implementation version='1.0' id='app1'><command name='run' path='test-app' /></implementation><implementation version='2.0' id='app2'><command name='run' path='test-app' /></implementation>"} }, requirements: new Requirements { InterfaceID = "http://test/app.xml", Command = Command.NameRun, ExtraRestrictions = {{"http://test/app.xml", new VersionRange("..!2.0")}} }, expectedSelections: "<selection interface='http://test/app.xml' version='1.0' id='app1'><command name='run' path='test-app' /></selection>"); } [Test] public void X86OnX64() { if (Architecture.CurrentSystem.Cpu != Cpu.X64) Assert.Ignore("Can only test on X64 systems"); // Prefer x64 when possible RunAndAssert( feeds: new Dictionary<string, string> { { "http://test/app.xml", "<group version='1.0'><command name='run' path='test-app' /><requires interface='http://test/lib.xml' />" + "<implementation arch='*-i686' id='app32'/><implementation arch='*-x86_64' id='app64'/>" + "</group>" }, {"http://test/lib.xml", "<implementation version='1.0' id='lib' />"} }, requirements: new Requirements {InterfaceID = "http://test/app.xml", Command = Command.NameRun}, expectedSelections: "<selection interface='http://test/app.xml' version='1.0' arch='*-x86_64' id='app64'><command name='run' path='test-app' /><requires interface='http://test/lib.xml' /></selection>" + "<selection interface='http://test/lib.xml' version='1.0' id='lib' />"); // Fall back to x86 to avoid 32bit/64bit mixing RunAndAssert( feeds: new Dictionary<string, string> { { "http://test/app.xml", "<group version='1.0'><command name='run' path='test-app' /><requires interface='http://test/lib.xml' />" + "<implementation arch='*-i686' id='app32'/><implementation arch='*-x86_64' id='app64'/>" + "</group>" }, {"http://test/lib.xml", "<implementation version='1.0' arch='*-i486' id='lib' />"} }, requirements: new Requirements {InterfaceID = "http://test/app.xml", Command = Command.NameRun}, expectedSelections: "<selection interface='http://test/app.xml' version='1.0' arch='*-i686' id='app32'><command name='run' path='test-app' /><requires interface='http://test/lib.xml' /></selection>" + "<selection interface='http://test/lib.xml' version='1.0' arch='*-i486' id='lib' />"); } #region Helpers protected void RunAndAssert(IEnumerable<KeyValuePair<string, string>> feeds, Requirements requirements, string expectedSelections) { var feedManagerMock = Container.GetMock<IFeedManager>(); var parsedFeeds = ParseFeeds(feeds); feedManagerMock.Setup(x => x.GetFeed(It.IsAny<string>())).Returns((string feedID) => parsedFeeds[feedID]); var expected = ParseExpectedSelections(expectedSelections, requirements); var actual = Target.Solve(requirements); Assert.AreEqual(expected, actual, message: string.Format("Selections mismatch.\nExpected: {0}\nActual: {1}", expected.ToXmlString(), actual.ToXmlString())); } private static Selections ParseExpectedSelections(string expectedSelections, Requirements requirements) { var expectedSelectionsParsed = XmlStorage.FromXmlString<Selections>(string.Format( "<?xml version='1.0'?><selections interface='{0}' command='{1}' xmlns='http://zero-install.sourceforge.net/2004/injector/interface'>{2}</selections>", requirements.InterfaceID, requirements.Command, expectedSelections)); return expectedSelectionsParsed; } private static IDictionary<string, Feed> ParseFeeds(IEnumerable<KeyValuePair<string, string>> feeds) { var feedsParsed = new Dictionary<string, Feed>(); foreach (var feedXml in feeds) { var feed = XmlStorage.FromXmlString<Feed>(string.Format( "<?xml version='1.0'?><interface xmlns='http://zero-install.sourceforge.net/2004/injector/interface' uri='{0}'>{1}</interface>", feedXml.Key, feedXml.Value)); feed.Normalize(feedXml.Key); feedsParsed.Add(feedXml.Key, feed); } return feedsParsed; } #endregion } }
clawplach/0install-win
src/Backend/UnitTests/Services/Solvers/SolverTest.cs
C#
lgpl-3.0
20,211
<?php /** * Contao Open Source CMS * * Copyright (c) 2005-2013 Leo Feyer * * @package ReadSpeaker * @author Johannes Pichler * @license LGPL * @copyright webpixels Johannes Pichler 2013 */ /** * Namespace */ namespace ReadSpeaker; /** * Class FE_ReadSpeaker * * @copyright webpixels Johannes Pichler 2013 * @author Johannes Pichler * @package Devtools */ class FE_ReadSpeaker extends \Module { /** * Template * @var string */ protected $strTemplate = 'mod_readspeaker'; /** * Generate the module */ protected function compile() { $dc = \Contao\Database::getInstance(); $row = $dc->prepare('SELECT * FROM tl_rs_settings WHERE id = ?')->limit(1)->execute($this->rs_setting)->fetchAssoc(); $href = ''; if ($row) { $customerid = '6857'; $lang = $row['language_demo']; $speed = $row['speed']; $readid = ($this->rs_readid ? $this->rs_readid : $this->strColumn); $stattype = \Contao\Environment::get('host'); $url = \Contao\Environment::get('base'); $url2 = \Contao\Environment::get('requestUri'); if ($url2 != '/') $url .= substr($url2, 1); if ($row['have_license']) { $customerid = $row['customer_id']; $lang = $row['language']; } $protocol = \Contao\Environment::get('https'); $ssl = false; if (isset($protocol)) { if ('on' == strtolower($protocol)) $ssl = true; if ('1' == $protocol) $ssl = true; } if (!$GLOBALS['RS_IN_HEAD']) { $GLOBALS['RS_IN_HEAD'] = true; if ($ssl) { $GLOBALS['TL_HEAD'][] = '<script src="system/modules/readspeaker/assets/rs_ssl/ReadSpeaker.js?pids=embhl" type="text/javascript"></script>'; } else { $GLOBALS['TL_HEAD'][] = '<script src="http://f1.eu.readspeaker.com/script/' . $customerid . '/ReadSpeaker.js?pids=embhl" type="text/javascript"></script>'; } } $GLOBALS['TL_HEAD'][] = '<script src="system/modules/readspeaker/assets/readspeaker.js"></script>'; $GLOBALS['TL_HEAD'][] = '<script type="text/javascript"> <!-- window.rsConf = {general: {usePost: true}}; //--> </script>'; $href = ''; if ($ssl) { $href .= "https://app.readspeaker.com/cgi-bin/rsent?"; } else { $href .= "http://app.eu.readspeaker.com/cgi-bin/rsent?"; } $href .= "customerid=" . $customerid; $href .= "&amp;lang=" . $lang; $href .= "&amp;readid=" . $readid; $href .= "&amp;url=" . urlencode($url); $href .= "&amp;stattype=" . $stattype; } $this->Template->href = $href; $this->Template->button_title = $this->rs_player_title; } }
joeherold/readspeaker
TL_ROOT/system/modules/readspeaker/classes/FE_ReadSpeaker.php
PHP
lgpl-3.0
3,253
import datetime from django.db import models from django.core import validators from django.utils.translation import ugettext_lazy as _ from nmadb_contacts.models import Municipality, Human class School(models.Model): """ Information about school. School types retrieved from `AIKOS <http://www.aikos.smm.lt/aikos/svietimo_ir_mokslo_institucijos.htm>`_ """ SCHOOL_TYPES = ( (1, _(u'primary')), (2, _(u'basic')), (3, _(u'secondary')), (4, _(u'gymnasium')), (5, _(u'progymnasium')), ) title = models.CharField( max_length=80, unique=True, verbose_name=_(u'title'), ) school_type = models.PositiveSmallIntegerField( choices=SCHOOL_TYPES, blank=True, null=True, verbose_name=_(u'type'), ) email = models.EmailField( max_length=128, unique=True, blank=True, null=True, verbose_name=_(u'email'), ) municipality = models.ForeignKey( Municipality, blank=True, null=True, verbose_name=_(u'municipality'), ) class Meta(object): ordering = [u'title',] verbose_name=_(u'school') verbose_name_plural=_(u'schools') def __unicode__(self): return unicode(self.title) class Student(Human): """ Information about student. """ school_class = models.PositiveSmallIntegerField( validators=[ validators.MinValueValidator(6), validators.MaxValueValidator(12), ], verbose_name=_(u'class'), ) school_year = models.IntegerField( validators=[ validators.MinValueValidator(2005), validators.MaxValueValidator(2015), ], verbose_name=_(u'class update year'), help_text=_( u'This field value shows, at which year January 3 day ' u'student was in school_class.' ), ) comment = models.TextField( blank=True, null=True, verbose_name=_(u'comment'), ) schools = models.ManyToManyField( School, through='StudyRelation', ) parents = models.ManyToManyField( Human, through='ParentRelation', related_name='children', ) def current_school_class(self): """ Returns current school class or 13 if finished. """ today = datetime.date.today() school_class = self.school_class + today.year - self.school_year if today.month >= 9: school_class += 1 if school_class > 12: return 13 else: return school_class current_school_class.short_description = _(u'current class') def current_school(self): """ Returns current school. """ study = StudyRelation.objects.filter( student=self).order_by('entered')[0] return study.school current_school.short_description = _(u'current school') def change_school(self, school, date=None): """ Marks, that student from ``date`` study in ``school``. .. note:: Automatically saves changes. ``date`` defaults to ``today()``. If student already studies in some school, than marks, that he had finished it day before ``date``. """ if date is None: date = datetime.date.today() try: old_study = StudyRelation.objects.filter( student=self).order_by('entered')[0] except IndexError: pass else: if not old_study.finished: old_study.finished = date - datetime.timedelta(1) old_study.save() study = StudyRelation() study.student = self study.school = school study.entered = date study.save() class Meta(object): verbose_name=_(u'student') verbose_name_plural=_(u'students') class StudyRelation(models.Model): """ Relationship between student and school. """ student = models.ForeignKey( Student, verbose_name=_(u'student'), ) school = models.ForeignKey( School, verbose_name=_(u'school'), ) entered = models.DateField( verbose_name=_(u'entered'), ) finished = models.DateField( blank=True, null=True, verbose_name=_(u'finished'), ) class Meta(object): ordering = [u'student', u'entered',] verbose_name=_(u'study relation') verbose_name_plural=_(u'study relations') def __unicode__(self): return u'{0.school} ({0.entered}; {0.finished})'.format(self) # FIXME: Diploma should belong to academic, not student. class Diploma(models.Model): """ Information about the diploma that the student has received, when he finished, if any. """ DIPLOMA_TYPE = ( (u'N', _(u'nothing')), (u'P', _(u'certificate')), (u'D', _(u'diploma')), (u'DP', _(u'diploma with honour')), ) student = models.OneToOneField( Student, verbose_name=_(u'student'), ) tasks_solved = models.PositiveSmallIntegerField( blank=True, null=True, verbose_name=_(u'how many tasks solved'), ) hours = models.DecimalField( blank=True, null=True, max_digits=6, decimal_places=2, verbose_name=_(u'hours'), ) diploma_type = models.CharField( max_length=3, choices=DIPLOMA_TYPE, verbose_name=_(u'type'), ) number = models.PositiveSmallIntegerField( verbose_name=_(u'number'), ) class Meta(object): verbose_name=_(u'diploma') verbose_name_plural=_(u'diplomas') class Alumni(models.Model): """ Information about alumni. """ INTEREST_LEVEL = ( # Not tried to contact. ( 0, _(u'not tried to contact')), # Tried to contact, no response. (11, _(u'no response')), # Tried to contact, responded. (21, _(u'not interested')), (22, _(u'friend')), (23, _(u'helpmate')), (24, _(u'regular helpmate')), ) student = models.OneToOneField( Student, verbose_name=_(u'student'), ) activity_fields = models.TextField( blank=True, null=True, verbose_name=_(u'fields'), help_text=_( u'Alumni reported that he can help in these activity ' u'fields.' ), ) interest_level = models.PositiveSmallIntegerField( blank=True, null=True, choices=INTEREST_LEVEL, verbose_name=_(u'interest level'), ) abilities = models.TextField( blank=True, null=True, verbose_name=_(u'abilities'), help_text=_(u'Main abilities and interests.') ) university = models.CharField( max_length=128, blank=True, null=True, verbose_name=_(u'university'), help_text=_(u'Or work place.'), ) study_field = models.CharField( max_length=64, blank=True, null=True, verbose_name=_(u'study field'), help_text=_(u'Or employment field.'), ) info_change_year = models.IntegerField( blank=True, null=True, verbose_name=_(u'info change year'), help_text=_( u'Year when the information about studies ' u'will become invalid.' ), ) notes = models.TextField( blank=True, null=True, verbose_name=_(u'notes'), ) information_received_timestamp = models.DateTimeField( blank=True, null=True, verbose_name=_(u'information received timestamp'), ) class Meta(object): verbose_name=_(u'alumni') verbose_name_plural=_(u'alumnis') def contactable(self): """ If the alumni agreed to receive information. """ return self.interest_level >= 22; class StudentMark(models.Model): """ Mark student with some mark. """ student = models.ForeignKey( Student, verbose_name=_(u'student'), ) start = models.DateField( verbose_name=_(u'start'), ) end = models.DateField( blank=True, null=True, verbose_name=_(u'end'), ) def __unicode__(self): return unicode(self.student) class Meta(object): abstract = True class SocialDisadvantageMark(StudentMark): """ Mark student as socially disadvantaged. """ class Meta(object): verbose_name=_(u'social disadvantage mark') verbose_name_plural=_(u'social disadvantage marks') class DisabilityMark(StudentMark): """ Mark student as having disability. """ disability = models.CharField( max_length=128, verbose_name=_(u'disability'), ) class Meta(object): verbose_name=_(u'disability mark') verbose_name_plural=_(u'disability marks') class ParentRelation(models.Model): """ Relationship between student and his parent. """ RELATION_TYPE = ( (u'P', _(u'parent')), (u'T', _(u'tutor')), ) child = models.ForeignKey( Student, related_name='+', verbose_name=_(u'child'), ) parent = models.ForeignKey( Human, verbose_name=_(u'parent'), ) relation_type = models.CharField( max_length=2, choices=RELATION_TYPE, verbose_name=_(u'type'), ) def __unicode__(self): return u'{0.parent} -> {0.child}'.format(self) class Meta(object): verbose_name=_(u'parent relation') verbose_name_plural=_(u'parent relations')
vakaras/nmadb-students
src/nmadb_students/models.py
Python
lgpl-3.0
10,676
/* * picotm - A system-level transaction manager * Copyright (c) 2018 Thomas Zimmermann <contact@tzimmermann.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * SPDX-License-Identifier: LGPL-3.0-or-later */ #pragma once #include "file_tx_ops.h" /** * \cond impl || libc_impl || libc_impl_fd * \ingroup libc_impl * \ingroup libc_impl_fd * \file * \endcond */ extern const struct file_tx_ops socket_tx_ops;
picotm/picotm
modules/libc/src/fildes/socket_tx_ops.h
C
lgpl-3.0
1,050
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <head> <title>Reference</title> <link rel="stylesheet" href="../ldoc.css" type="text/css" /> </head> <body> <div id="container"> <div id="product"> <div id="product_logo"></div> <div id="product_name"><big><b></b></big></div> <div id="product_description"></div> </div> <!-- id="product" --> <div id="main"> <!-- Menu --> <div id="navigation"> <br/> <h1>Lua Blowfish</h1> <ul> <li><a href="../index.html">Index</a></li> </ul> <h2>Contents</h2> <ul> <li><a href="#Functions">Functions</a></li> </ul> <h2>Modules</h2> <ul class="$(kind=='Topics' and '' or 'nowrap'"> <li><strong>blowfish</strong></li> </ul> <h2>Classes</h2> <ul class="$(kind=='Topics' and '' or 'nowrap'"> <li><a href="../classes/BFContext.html">BFContext</a></li> </ul> <h2>Examples</h2> <ul class="$(kind=='Topics' and '' or 'nowrap'"> <li><a href="../examples/example.lua.html">example.lua</a></li> </ul> </div> <div id="content"> <h1>Module <code>blowfish</code></h1> <p>Blowfish main module.</p> <p></p> <h2><a href="#Functions">Functions</a></h2> <table class="function_list"> <tr> <td class="name" nowrap><a href="#create">create (key)</a></td> <td class="summary">Creates a new instance˙of a blowfish cypher.</td> </tr> </table> <br/> <br/> <h2 class="section-header "><a name="Functions"></a>Functions</h2> <dl class="function"> <dt> <a name = "create"></a> <strong>create (key)</strong> </dt> <dd> Creates a new instance˙of a blowfish cypher. </ul> </ul> <h3>Parameters:</h3> <ul> <li><span class="parameter">key</span> <span class="types"><a class="type" href="http://www.lua.org/manual/5.1/manual.html#5.4">string</a></span> the key to be used. It is from 4 to 112 bytes (or chars). </li> </ul> <h3>Returns:</h3> <ol> <span class="types"><a class="type" href="../classes/BFContext.html#">BFContext</a></span> a context to be used for encrypting/decrypting blocks </ol> </dd> </dl> </div> <!-- id="content" --> </div> <!-- id="main" --> <div id="about"> <i>generated by <a href="http://github.com/stevedonovan/LDoc">LDoc 1.4.3</a></i> <i style="float:right;">Last updated 2016-03-26 23:19:14 </i> </div> <!-- id="about" --> </div> <!-- id="container" --> </body> </html>
leoagomes/lua-blowfish
doc/modules/blowfish.html
HTML
lgpl-3.0
2,512
using System.Collections.Generic; namespace AntSimComplexAlgorithms { internal interface IAnt { /// <summary> /// The ant's unique integer Id. /// </summary> int Id { get; } /// <summary> /// The index of the node the ant is currently on. /// </summary> int CurrentNode { get; } /// <summary> /// Length of the ant's completed tour. /// </summary> double TourLength { get; } /// <summary> /// The node indices corresponding to the ant's tour. /// </summary> IReadOnlyList<int> Tour { get; } /// <summary> /// Indices of visited nodes are set to "true", e.g. node x /// has not been visited if Visited[x] is "false". /// </summary> IReadOnlyList<bool> Visited { get; } /// <summary> /// Initialises (or resets) the internal state of the Ant. /// </summary> /// <param name="startNode">The node the ant starts its tour on.</param> void Initialise(int startNode); /// <summary> /// Move to the next node selected by the current node selection strategy. /// </summary> /// <param name="i">The current step</param> void Step(int i); } }
goblincoding/ant-system-complex-pheromone
AntSimComplex/AntSimComplexAlgorithms/IAnt.cs
C#
lgpl-3.0
1,168
/* * Copyright (C) 2005-2017 ManyDesigns srl. All rights reserved. * http://www.manydesigns.com/ * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package com.manydesigns.portofino.interceptors; import com.manydesigns.elements.ElementsThreadLocals; import com.manydesigns.elements.messages.SessionMessages; import com.manydesigns.portofino.RequestAttributes; import com.manydesigns.portofino.dispatcher.*; import com.manydesigns.portofino.i18n.TextProviderBean; import com.manydesigns.portofino.pageactions.PageActionLogic; import com.manydesigns.portofino.shiro.SecurityUtilsBean; import net.sourceforge.stripes.action.ActionBeanContext; import net.sourceforge.stripes.action.ForwardResolution; import net.sourceforge.stripes.action.Resolution; import net.sourceforge.stripes.controller.ExecutionContext; import net.sourceforge.stripes.controller.Interceptor; import net.sourceforge.stripes.controller.Intercepts; import net.sourceforge.stripes.controller.LifecycleStage; import ognl.OgnlContext; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.lang.time.StopWatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.DispatcherType; import javax.servlet.http.HttpServletRequest; import java.text.MessageFormat; /* * @author Paolo Predonzani - paolo.predonzani@manydesigns.com * @author Angelo Lupo - angelo.lupo@manydesigns.com * @author Giampiero Granatella - giampiero.granatella@manydesigns.com * @author Alessio Stalla - alessio.stalla@manydesigns.com */ @Intercepts(LifecycleStage.CustomValidation) public class ApplicationInterceptor implements Interceptor { public static final String copyright = "Copyright (C) 2005-2017 ManyDesigns srl"; public final static Logger logger = LoggerFactory.getLogger(ApplicationInterceptor.class); public static Resolution dispatch(ActionBeanContext actionContext) throws Exception { logger.debug("Publishing textProvider in OGNL context"); OgnlContext ognlContext = ElementsThreadLocals.getOgnlContext(); ognlContext.put("textProvider", new TextProviderBean(ElementsThreadLocals.getTextProvider())); Dispatch dispatch = DispatcherUtil.getDispatch(actionContext); if (dispatch != null) { HttpServletRequest request = actionContext.getRequest(); logger.debug("Preparing PageActions"); for(PageInstance page : dispatch.getPageInstancePath()) { if(page.getParent() == null) { logger.debug("Not preparing root"); continue; } if(page.isPrepared()) { continue; } logger.debug("Preparing PageAction {}", page); PageAction actionBean = page.getActionBean(); try { actionBean.setContext(actionContext); Resolution resolution = actionBean.preparePage(); if(resolution != null) { logger.debug("PageAction prepare returned a resolution: {}", resolution); request.setAttribute(DispatcherLogic.INVALID_PAGE_INSTANCE, page); return resolution; } page.setPrepared(true); } catch (Throwable t) { request.setAttribute(DispatcherLogic.INVALID_PAGE_INSTANCE, page); logger.error("PageAction prepare failed for " + page, t); if(!PageActionLogic.isEmbedded(actionBean)) { String msg = MessageFormat.format (ElementsThreadLocals.getText("this.page.has.thrown.an.exception.during.execution"), ExceptionUtils.getRootCause(t)); SessionMessages.addErrorMessage(msg); } request.setAttribute("http-error-code", 500); return new ForwardResolution("/m/pageactions/redirect-to-last-working-page.jsp"); } } PageInstance pageInstance = dispatch.getLastPageInstance(); request.setAttribute(RequestAttributes.PAGE_INSTANCE, pageInstance); } return null; } public Resolution intercept(ExecutionContext context) throws Exception { logger.debug("Retrieving Stripes objects"); ActionBeanContext actionContext = context.getActionBeanContext(); logger.debug("Retrieving Servlet API objects"); HttpServletRequest request = actionContext.getRequest(); if (request.getDispatcherType() == DispatcherType.REQUEST) { logger.debug("Starting page response timer"); StopWatch stopWatch = new StopWatch(); // There is no need to stop this timer. stopWatch.start(); request.setAttribute(RequestAttributes.STOP_WATCH, stopWatch); } Resolution resolution = dispatch(actionContext); return resolution != null ? resolution : context.proceed(); } }
denarie/Portofino
portofino-pageactions/src/main/java/com/manydesigns/portofino/interceptors/ApplicationInterceptor.java
Java
lgpl-3.0
5,832
using System; using System.Collections.Generic; using System.Windows.Forms; namespace ActiveUp.MailSystem.CtsdClient { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new ctasdClientForm()); } } }
DavidS/MailSystem.NET
Samples/CS/ActiveUp.MailSystem.CtsdClient/Program.cs
C#
lgpl-3.0
507
using System; using Bosphorus.Library.Dao.Core.Dao; using Bosphorus.Library.Dao.Facade.Facade.Loader.Repository.Base; namespace Bosphorus.Library.Dao.Facade.Facade.Loader.Repository.Domain { public class Live : AbstractRepositoryContainerConfigurator { public Live(string assemblyName, string @namespace) : this(assemblyName, @namespace, "Dao") { } public Live(string assemblyName, string @namespace, string endsWith) : base(typeof(IDao<>), typeof(NullDao<>), assemblyName, @namespace, endsWith) { } } }
BosphorusTeam/bosphorus.dao
Source/Projects/Bosphorus.Dao.Facade/Facade.Loader/Repository.Domain/Live.cs
C#
lgpl-3.0
593
// // (C) Copyright by Victor Derks // // See README.TXT for the details of the software licence. // #include "stdafx.h" #include "testcom.h" //#include "../include/infotipptr.h" //#include "../include/util.h" #include "../include/macros.h" #include "../vvvsample/infotipclsid.h" //CString GetInprocServer32() //{ //} void CallDllFunction(const CString& strDllname, const char* pszFunction) { typedef HRESULT (STDAPICALLTYPE* LPFNDLL)(); HINSTANCE hLib = LoadLibrary(strDllname); if (hLib == NULL) RaiseException(); try { LPFNDLL lpDllEntryPoint; lpDllEntryPoint = (LPFNDLL)GetProcAddress(hLib, pszFunction); if (lpDllEntryPoint == NULL) RaiseException(); HRESULT hr = (*lpDllEntryPoint)(); if (FAILED(hr)) RaiseException(); } catch (const _com_error&) { ATLVERIFY(FreeLibrary(hLib)); throw; } } void RegisterServer(const CString& strDllname) { CallDllFunction(strDllname, "DllRegisterServer"); } void UnregisterServer(const CString& strDllname) { CallDllFunction(strDllname, "DllUnregisterServer"); } void TestCOM::RegisterAndUnregister() { // TODO // Get regserver // Register // Unregister // Unregister // Register }
vbaderks/msf
samples/vvvtest/testcom.cpp
C++
lgpl-3.0
1,181
#pragma sw require header org.sw.demo.lexxmark.winflexbison.bison void build(Solution &s) { auto &DataManager = s.addLibrary("Polygon4.DataManager", "master"); DataManager += Git("https://github.com/aimrebirth/DataManager", "", "{v}"); auto &memory = DataManager.addStaticLibrary("memory"); { memory += cpp20; memory += "include/Polygon4/Memory.h", "src/memory/Memory.cpp"; if (memory.getOptions()["alligned-allocator"] == "1") { memory.getOptions()["alligned-allocator"].use(); memory += "DATA_MANAGER_ALIGNED_ALLOCATOR"_def; } } auto &schema = DataManager.addLibrary("schema"); { schema += cpp20; schema.ApiName = "SCHEMA_API"; schema += "include/.*"_rr; schema += "src/schema/.*\\.h"_rr; schema += "src/schema/.*\\.cpp"_rr; schema.Public += "include"_idir; schema += "include/Polygon4/DataManager/Schema"_idir; schema += "src/schema"_idir; schema.Public += "pub.egorpugin.primitives.filesystem-master"_dep; schema.Public += "pub.egorpugin.primitives.templates-master"_dep; schema.Public += "pub.egorpugin.primitives.emitter-master"_dep; schema.Public += "org.sw.demo.boost.algorithm"_dep; schema.Public += "org.sw.demo.boost.variant"_dep; schema.Public += memory; gen_flex_bison_pair("org.sw.demo.lexxmark.winflexbison"_dep, schema, "LALR1_CPP_VARIANT_PARSER", "src/schema/schema"); } auto &generator = DataManager.addExecutable("tools.generator"); generator += cpp20; generator += "src/generator/main.cpp"; generator += schema; generator += "pub.egorpugin.primitives.sw.main-master"_dep; // DataManager { DataManager += cpp20; DataManager.ApiName = "DATA_MANAGER_API"; DataManager += "include/.*"_rr; DataManager += "src/manager/.*\\.cpp"_rr; DataManager.Public += "include"_idir; DataManager += "src/manager"_idir; DataManager.Public += schema; DataManager.Public += "org.sw.demo.sqlite3-3"_dep; DataManager.Public += "pub.egorpugin.primitives.log-master"_dep; { auto c = DataManager.addCommand(); c << cmd::prog(generator) << cmd::in("data/schema.txt") << DataManager.BinaryDir << cmd::end() ; for (path o : { "include/detail/ForwardDeclarations.h", "include/detail/Types.h", "include/detail/Storage.h", "include/detail/StorageImpl.h", "include/detail/ObjectInterfaces.h", "include/detail/Enums.h", }) { c << cmd::out(o); } for (path o : { "src/detail/Types.cpp", "src/detail/Storage.cpp", "src/detail/StorageImpl.cpp", "src/detail/schema/Tokens.cpp", "src/detail/Enums.cpp", }) { c << cmd::out(o); DataManager[o].skip = true; } DataManager.Public += IncludeDirectory(DataManager.BinaryDir / "include"); DataManager += IncludeDirectory(DataManager.BinaryDir / "src"); } if (DataManager.getCompilerType() == CompilerType::MSVC) DataManager.CompileOptions.push_back("-bigobj"); } }
aimrebirth/DataManager
sw.cpp
C++
lgpl-3.0
3,570
package co.edu.uniandes.csw.item.master.logic.ejb; import co.edu.uniandes.csw.documento.logic.dto.DocumentoDTO; import co.edu.uniandes.csw.documento.persistence.api.IDocumentoPersistence; import co.edu.uniandes.csw.item.logic.dto.ItemDTO; import co.edu.uniandes.csw.item.master.logic.api._IItemMasterLogicService; import co.edu.uniandes.csw.item.master.logic.dto.ItemMasterDTO; import co.edu.uniandes.csw.item.master.persistence.api.IItemMasterPersistence; import co.edu.uniandes.csw.item.master.persistence.entity.ItemDocumentoEntity; import co.edu.uniandes.csw.item.persistence.api.IItemPersistence; import javax.inject.Inject; public abstract class _ItemMasterLogicService implements _IItemMasterLogicService { @Inject protected IItemPersistence itemPersistance; @Inject protected IItemMasterPersistence itemMasterPersistance; @Inject protected IDocumentoPersistence documentoPersistance; public ItemMasterDTO createMasterItem(ItemMasterDTO item) { ItemDTO persistedItemDTO = itemPersistance.createItem(item.getItemEntity()); if (item.getCreateDocumento() != null) { for (DocumentoDTO documentoDTO : item.getCreateDocumento()) { DocumentoDTO persistedDocumentoDTO = documentoPersistance.createDocumento(documentoDTO); ItemDocumentoEntity itemDocumentoEntity = new ItemDocumentoEntity(persistedItemDTO.getId(), persistedDocumentoDTO.getId()); itemMasterPersistance.createItemDocumento(itemDocumentoEntity); } } return item; } public ItemMasterDTO getMasterItem(Long id) { return itemMasterPersistance.getItem(id); } public void deleteMasterItem(Long id) { itemPersistance.deleteItem(id); } public void updateMasterItem(ItemMasterDTO item) { itemPersistance.updateItem(item.getItemEntity()); //---- FOR RELATIONSHIP // persist new documento if (item.getCreateDocumento() != null) { for (DocumentoDTO documentoDTO : item.getCreateDocumento()) { DocumentoDTO persistedDocumentoDTO = documentoPersistance.createDocumento(documentoDTO); ItemDocumentoEntity itemDocumentoEntity = new ItemDocumentoEntity(item.getItemEntity().getId(), persistedDocumentoDTO.getId()); itemMasterPersistance.createItemDocumento(itemDocumentoEntity); } } // update documento if (item.getUpdateDocumento() != null) { for (DocumentoDTO documentoDTO : item.getUpdateDocumento()) { documentoPersistance.updateDocumento(documentoDTO); } } // delete documento if (item.getDeleteDocumento() != null) { for (DocumentoDTO documentoDTO : item.getDeleteDocumento()) { itemMasterPersistance.deleteItemDocumento(item.getItemEntity().getId(), documentoDTO.getId()); documentoPersistance.deleteDocumento(documentoDTO.getId()); } } } }
jachaparro914/ciclo4-repo
item.master.service.subsystem/src/main/java/co/edu/uniandes/csw/item/master/logic/ejb/_ItemMasterLogicService.java
Java
lgpl-3.0
3,035
/** * */ package org.sinnlabs.dbvim.ui; import org.zkoss.zk.ui.Executions; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zk.ui.event.Events; import org.zkoss.zk.ui.event.MouseEvent; import org.zkoss.zk.ui.select.Selectors; import org.zkoss.zk.ui.select.annotation.Wire; import org.zkoss.zul.Button; import org.zkoss.zul.Textbox; import org.zkoss.zul.Window; /** * @author peter.liverovsky * */ public class FormNameDialog extends Window { /** * */ private static final long serialVersionUID = 8597870870382427612L; @Wire protected Button btnOK; @Wire protected Textbox txtName; public FormNameDialog(String name) { super(); /* create the ui */ Executions.createComponents("/components/formname.zul", this, null); Selectors.wireVariables(this, this, null); Selectors.wireComponents(this, this, false); Selectors.wireEventListeners(this, this); setBorder("normal"); setWidth("50%"); setClosable(false); setTitle("Form name"); txtName.setText(name); final Window t = this; btnOK.addEventListener(Events.ON_CLICK, new EventListener<MouseEvent>() { @Override public void onEvent(MouseEvent e) throws Exception { Event closeEvent = new Event(Events.ON_CLOSE, t); Events.postEvent(closeEvent); detach(); } }); } public String getName() { return txtName.getText(); } }
sinnlabs/dbvim
src/org/sinnlabs/dbvim/ui/FormNameDialog.java
Java
lgpl-3.0
1,423
// keves/kev/string-inl.hpp - strings for Keves // Keves will be an R6RS Scheme implementation. // // Copyright (C) 2014 Yasuhiro Yamakawa <kawatab@yahoo.co.jp> // // This program is free software: you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or any // later version. // // This program is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public // License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #pragma once template<class ZONE> StringCoreKev* StringCoreKev::make(ZONE* zone, const QString& str) { auto ctor = [&str](void* ptr) { StringCoreKev* string(new(ptr) StringCoreKev(str.size())); string->set(str); return string; }; return zone->make(ctor, alloc_size(str.size())); } template<class ZONE> StringCoreKev* StringCoreKev::make(ZONE* zone, int size) { auto ctor = [size](void* ptr) { return new(ptr) StringCoreKev(size); }; return zone->make(ctor, alloc_size(size)); } template<class ZONE> StringKev* StringKev::make(ZONE* zone, int size) { return zone->make(ctor(zone, size), alloc_size(nullptr)); } template<class ZONE> StringKev* StringKev::make(ZONE* zone, const QString& str) { return zone->make(ctor(zone, str), alloc_size(nullptr)); } template<class ZONE> StringKev* StringKev::makeSubstring(ZONE* zone, const StringKev* str, int start, int end) { auto ctor = [str, start, end](void* ptr) { return new(ptr) StringKev(str->mid(start, end - start)); }; return zone->make(ctor, alloc_size(nullptr)); } template<class ZONE> StringKev* StringKev::make(ZONE* zone, StringCoreKev* core, int idx, int len) { auto ctor = [core, idx, len](void* ptr) { return new(ptr) StringKev(core, idx, len); }; return zone->make(ctor, alloc_size(nullptr)); }
kawatab/keves
kev/string-inl.hpp
C++
lgpl-3.0
2,145
""" This test illustrate how to generate an XML Mapnik style sheet from a pycnik style sheet written in Python. """ import os from pycnik import pycnik import artefact actual_xml_style_sheet = 'artefacts/style_sheet.xml' expected_xml_style_sheet = 'style_sheet.xml' class TestPycnik(artefact.TestCaseWithArtefacts): def test_pycnik(self): python_style_sheet = pycnik.import_style('style_sheet.py') pycnik.translate(python_style_sheet, actual_xml_style_sheet) with open(actual_xml_style_sheet) as actual, \ open(expected_xml_style_sheet) as expected: self.assertEquals(actual.read(), expected.read())
Mappy/pycnikr
tests/test_pycnik.py
Python
lgpl-3.0
660
# copyright 2003-2013 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of astroid. # # astroid is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # astroid is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with astroid. If not, see <http://www.gnu.org/licenses/>. """This module contains some mixins for the different nodes. """ from .exceptions import (AstroidBuildingException, InferenceError, NotFoundError) class BlockRangeMixIn(object): """override block range """ def set_line_info(self, lastchild): self.fromlineno = self.lineno self.tolineno = lastchild.tolineno self.blockstart_tolineno = self._blockstart_toline() def _elsed_block_range(self, lineno, orelse, last=None): """handle block line numbers range for try/finally, for, if and while statements """ if lineno == self.fromlineno: return lineno, lineno if orelse: if lineno >= orelse[0].fromlineno: return lineno, orelse[-1].tolineno return lineno, orelse[0].fromlineno - 1 return lineno, last or self.tolineno class FilterStmtsMixin(object): """Mixin for statement filtering and assignment type""" def _get_filtered_stmts(self, _, node, _stmts, mystmt): """method used in _filter_stmts to get statemtents and trigger break""" if self.statement() is mystmt: # original node's statement is the assignment, only keep # current node (gen exp, list comp) return [node], True return _stmts, False def ass_type(self): return self class AssignTypeMixin(object): def ass_type(self): return self def _get_filtered_stmts(self, lookup_node, node, _stmts, mystmt): """method used in filter_stmts""" if self is mystmt: return _stmts, True if self.statement() is mystmt: # original node's statement is the assignment, only keep # current node (gen exp, list comp) return [node], True return _stmts, False class ParentAssignTypeMixin(AssignTypeMixin): def ass_type(self): return self.parent.ass_type() class FromImportMixIn(FilterStmtsMixin): """MixIn for From and Import Nodes""" def _infer_name(self, frame, name): return name def do_import_module(self, modname): """return the ast for a module whose name is <modname> imported by <self> """ # handle special case where we are on a package node importing a module # using the same name as the package, which may end in an infinite loop # on relative imports # XXX: no more needed ? mymodule = self.root() level = getattr(self, 'level', None) # Import as no level # XXX we should investigate deeper if we really want to check # importing itself: modname and mymodule.name be relative or absolute if mymodule.relative_to_absolute_name(modname, level) == mymodule.name: # FIXME: we used to raise InferenceError here, but why ? return mymodule try: return mymodule.import_module(modname, level=level) except AstroidBuildingException: raise InferenceError(modname) except SyntaxError, ex: raise InferenceError(str(ex)) def real_name(self, asname): """get name from 'as' name""" for name, _asname in self.names: if name == '*': return asname if not _asname: name = name.split('.', 1)[0] _asname = name if asname == _asname: return name raise NotFoundError(asname)
lukaszpiotr/pylama_with_gjslint
pylama/checkers/pylint/astroid/mixins.py
Python
lgpl-3.0
4,313
<?php /** * PHPCompatibility, an external standard for PHP_CodeSniffer. * * @package PHPCompatibility * @copyright 2012-2020 PHPCompatibility Contributors * @license https://opensource.org/licenses/LGPL-3.0 LGPL3 * @link https://github.com/PHPCompatibility/PHPCompatibility */ namespace PHPCompatibility\Tests\ParameterValues; use PHPCompatibility\Tests\BaseSniffTest; /** * Test the NewNegativeStringOffset sniff. * * @group newNegativeStringOffset * @group parameterValues * * @covers \PHPCompatibility\Sniffs\ParameterValues\NewNegativeStringOffsetSniff * * @since 9.0.0 */ class NewNegativeStringOffsetUnitTest extends BaseSniffTest { /** * testNegativeStringOffset * * @dataProvider dataNegativeStringOffset * * @param int $line Line number where the error should occur. * @param string $paramName The name of the parameter being passed a negative offset. * @param string $functionName The name of the function which was called. * * @return void */ public function testNegativeStringOffset($line, $paramName, $functionName) { $file = $this->sniffFile(__FILE__, '7.0'); $error = \sprintf( 'Negative string offsets were not supported for the $%1$s parameter in %2$s() in PHP 7.0 or lower.', $paramName, $functionName ); $this->assertError($file, $line, $error); } /** * dataNegativeStringOffset * * @see testNegativeStringOffset() * * @return array */ public function dataNegativeStringOffset() { return [ [28, 'position', 'mb_ereg_search_setpos'], [34, 'position', 'MB_ereg_search_setpos'], [36, 'offset', 'file_get_contents'], [37, 'start', 'grapheme_extract'], [38, 'offset', 'grapheme_stripos'], [39, 'offset', 'grapheme_strpos'], [40, 'offset', 'iconv_strpos'], [41, 'start', 'mb_strimwidth'], [41, 'width', 'mb_strimwidth'], [42, 'offset', 'mb_stripos'], [43, 'offset', 'mb_strpos'], [44, 'offset', 'stripos'], [45, 'offset', 'strpos'], [46, 'offset', 'substr_count'], [46, 'length', 'substr_count'], [47, 'offset', 'Substr_Count'], [48, 'length', 'substr_count'], ]; } /** * testNoFalsePositives * * @return void */ public function testNoFalsePositives() { $file = $this->sniffFile(__FILE__, '7.0'); // No errors expected on the first 26 lines. for ($line = 1; $line <= 26; $line++) { $this->assertNoViolation($file, $line); } } /** * Verify no notices are thrown at all. * * @return void */ public function testNoViolationsInFileOnValidVersion() { $file = $this->sniffFile(__FILE__, '7.1'); $this->assertNoViolation($file); } }
jrfnl/PHPCompatibility
PHPCompatibility/Tests/ParameterValues/NewNegativeStringOffsetUnitTest.php
PHP
lgpl-3.0
3,021
/* * Copyright (c) 2007 - 2008 by Damien Di Fede <ddf@compartmental.net> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package ddf.minim.javasound; import java.io.BufferedInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map; import javax.sound.sampled.AudioFileFormat; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.Mixer; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.TargetDataLine; import javax.sound.sampled.UnsupportedAudioFileException; import org.tritonus.share.sampled.AudioUtils; import org.tritonus.share.sampled.file.TAudioFileFormat; import ddf.minim.AudioMetaData; import ddf.minim.AudioSample; import ddf.minim.Minim; import ddf.minim.Recordable; import ddf.minim.spi.AudioOut; import ddf.minim.spi.AudioRecording; import ddf.minim.spi.AudioRecordingStream; import ddf.minim.spi.AudioStream; import ddf.minim.spi.MinimServiceProvider; import ddf.minim.spi.SampleRecorder; import javazoom.spi.mpeg.sampled.file.MpegAudioFormat; /** * JSMinim is an implementation of the {@link MinimServiceProvider} interface that use * Javasound to provide all audio functionality. That's about all you really need to know about it. * * @author Damien Di Fede * */ public class JSMinim implements MinimServiceProvider { private boolean debug; private Object fileLoader; private Method sketchPath; private Method createInput; private Mixer inputMixer; private Mixer outputMixer; public JSMinim(Object parent) { debug = false; fileLoader = parent; inputMixer = null; outputMixer = null; String error = ""; try { sketchPath = parent.getClass().getMethod( "sketchPath", String.class ); if ( sketchPath.getReturnType() != String.class ) { error += "The method sketchPath in the file loading object provided does not return a String!\n"; sketchPath = null; } } catch( NoSuchMethodException ex ) { error += "Couldn't find a sketchPath method on the file loading object provided!\n"; } catch( Exception ex ) { error += "Failed to get method sketchPath from file loading object provided!\n" + ex.getMessage() + "\n"; } if ( error.length() > 0 ) { error += "File recording will be disabled."; error( error ); } error = ""; try { createInput = parent.getClass().getMethod( "createInput", String.class ); if ( createInput.getReturnType() != InputStream.class ) { error += "The method createInput in the file loading object provided does not return an InputStream!\n"; createInput = null; } } catch( NoSuchMethodException ex ) { error += "Couldn't find a createInput method in the file loading object provided!\n"; } catch( Exception ex ) { error += "Failed to get method createInput from the file loading object provided!\n" + ex.getMessage() + "\n"; } if ( error.length() > 0 ) { error += "File loading will be disabled."; error( error ); } } public void setInputMixer(Mixer mix) { inputMixer = mix; } public Mixer getInputMixer() { return inputMixer; } public void setOutputMixer(Mixer mix) { outputMixer = mix; } public Mixer getOutputMixer() { return outputMixer; } public void start() { } public void stop() { } public void debugOn() { debug = true; } public void debugOff() { debug = false; } void debug(String s) { if ( debug ) { System.out.println("==== JavaSound Minim Debug ===="); String[] lines = s.split("\n"); for(int i = 0; i < lines.length; i++) { System.out.println("==== " + lines[i]); } System.out.println(); } } void error(String s) { System.out.println("==== JavaSound Minim Error ===="); String[] lines = s.split("\n"); for(int i = 0; i < lines.length; i++) { System.out.println("==== " + lines[i]); } System.out.println(); } public SampleRecorder getSampleRecorder(Recordable source, String fileName, boolean buffered) { // do nothing if we can't generate a place to put the file if ( sketchPath == null ) return null; String ext = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase(); debug("createRecorder: file extension is " + ext + "."); AudioFileFormat.Type fileType = null; if (ext.equals(Minim.WAV.getExtension())) { fileType = Minim.WAV; } else if (ext.equals(Minim.AIFF.getExtension()) || ext.equals("aif")) { fileType = Minim.AIFF; } else if (ext.equals(Minim.AIFC.getExtension())) { fileType = Minim.AIFC; } else if (ext.equals(Minim.AU.getExtension())) { fileType = Minim.AU; } else if (ext.equals(Minim.SND.getExtension())) { fileType = Minim.SND; } else { error("The extension " + ext + " is not a recognized audio file type."); return null; } SampleRecorder recorder = null; try { String destPath = (String)sketchPath.invoke( fileLoader, fileName ); if (buffered) { recorder = new JSBufferedSampleRecorder(this, destPath, fileType, source.getFormat(), source.bufferSize()); } else { recorder = new JSStreamingSampleRecorder(this, destPath, fileType, source.getFormat(), source.bufferSize()); } } catch( Exception ex ) { Minim.error( "Couldn't invoke the sketchPath method: " + ex.getMessage() ); } return recorder; } public AudioRecordingStream getAudioRecordingStream(String filename, int bufferSize, boolean inMemory) { // TODO: deal with the case of wanting to have the file fully in memory AudioRecordingStream mstream = null; AudioInputStream ais = getAudioInputStream(filename); if (ais != null) { if ( inMemory && ais.markSupported() ) { ais.mark( (int)ais.getFrameLength() * ais.getFormat().getFrameSize() ); } debug("Reading from " + ais.getClass().toString()); debug("File format is: " + ais.getFormat().toString()); AudioFormat format = ais.getFormat(); // special handling for mp3 files because // they need to be converted to PCM if (format instanceof MpegAudioFormat) { AudioFormat baseFormat = format; format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16, baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false); // converts the stream to PCM audio from mp3 audio AudioInputStream decAis = getAudioInputStream(format, ais); // source data line is for sending the file audio out to the // speakers SourceDataLine line = getSourceDataLine(format, bufferSize); if (decAis != null && line != null) { Map<String, Object> props = getID3Tags(filename); long lengthInMillis = -1; if (props.containsKey("duration")) { Long dur = (Long)props.get("duration"); if ( dur.longValue() > 0 ) { lengthInMillis = dur.longValue() / 1000; } } MP3MetaData meta = new MP3MetaData(filename, lengthInMillis, props); mstream = new JSMPEGAudioRecordingStream(this, meta, ais, decAis, line, bufferSize); } } // format instanceof MpegAudioFormat else { // source data line is for sending the file audio out to the // speakers SourceDataLine line = getSourceDataLine(format, bufferSize); if (line != null) { long length = AudioUtils.frames2Millis(ais.getFrameLength(), format); BasicMetaData meta = new BasicMetaData(filename, length, ais.getFrameLength()); mstream = new JSPCMAudioRecordingStream(this, meta, ais, line, bufferSize); } } // else } // ais != null return mstream; } @SuppressWarnings("unchecked") private Map<String, Object> getID3Tags(String filename) { debug("Getting the properties."); Map<String, Object> props = new HashMap<String, Object>(); try { MpegAudioFileReader reader = new MpegAudioFileReader(this); InputStream stream = (InputStream)createInput.invoke(fileLoader, filename); if ( stream != null ) { AudioFileFormat baseFileFormat = reader.getAudioFileFormat( stream, stream.available()); stream.close(); if (baseFileFormat instanceof TAudioFileFormat) { TAudioFileFormat fileFormat = (TAudioFileFormat)baseFileFormat; props = (Map<String, Object>)fileFormat.properties(); if (props.size() == 0) { error("No file properties available for " + filename + "."); } else { debug("File properties: " + props.toString()); } } } } catch (UnsupportedAudioFileException e) { error("Couldn't get the file format for " + filename + ": " + e.getMessage()); } catch (IOException e) { error("Couldn't access " + filename + ": " + e.getMessage()); } catch( Exception e ) { error("Error invoking createInput on the file loader object: " + e.getMessage()); } return props; } public AudioStream getAudioInput(int type, int bufferSize, float sampleRate, int bitDepth) { if (bitDepth != 8 && bitDepth != 16) { throw new IllegalArgumentException("Unsupported bit depth, use either 8 or 16."); } AudioFormat format = new AudioFormat(sampleRate, bitDepth, type, true, false); TargetDataLine line = getTargetDataLine(format, bufferSize * 4); if (line != null) { return new JSAudioInput(line, bufferSize); } return null; } public AudioSample getAudioSample(String filename, int bufferSize) { AudioInputStream ais = getAudioInputStream(filename); if (ais != null) { AudioMetaData meta = null; AudioFormat format = ais.getFormat(); FloatSampleBuffer samples = null; if (format instanceof MpegAudioFormat) { AudioFormat baseFormat = format; format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16, baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false); // converts the stream to PCM audio from mp3 audio ais = getAudioInputStream(format, ais); // get a map of properties so we can find out how long it is Map<String, Object> props = getID3Tags(filename); // there is a property called mp3.length.bytes, but that is // the length in bytes of the mp3 file, which will of course // be much shorter than the decoded version. so we use the // duration of the file to figure out how many bytes the // decoded file will be. long dur = ((Long)props.get("duration")).longValue(); int toRead = (int)AudioUtils.millis2Bytes(dur / 1000, format); samples = loadFloatAudio(ais, toRead); meta = new MP3MetaData(filename, dur / 1000, props); } else { samples = loadFloatAudio(ais, (int)ais.getFrameLength() * format.getFrameSize()); long length = AudioUtils.frames2Millis(samples.getSampleCount(), format); meta = new BasicMetaData(filename, length, samples.getSampleCount()); } AudioOut out = getAudioOutput(format.getChannels(), bufferSize, format.getSampleRate(), format.getSampleSizeInBits()); if (out != null) { SampleSignal ssig = new SampleSignal(samples); out.setAudioSignal(ssig); return new JSAudioSample(meta, ssig, out); } else { error("Couldn't acquire an output."); } } return null; } public AudioSample getAudioSample(float[] samples, AudioFormat format, int bufferSize) { FloatSampleBuffer sample = new FloatSampleBuffer(1, samples.length, format.getSampleRate()); System.arraycopy(samples, 0, sample.getChannel(0), 0, samples.length); return getAudioSampleImp(sample, format, bufferSize); } public AudioSample getAudioSample(float[] left, float[] right, AudioFormat format, int bufferSize) { FloatSampleBuffer sample = new FloatSampleBuffer(2, left.length, format.getSampleRate()); System.arraycopy(left, 0, sample.getChannel(0), 0, left.length); System.arraycopy(right, 0, sample.getChannel(1), 0, right.length); return getAudioSampleImp(sample, format, bufferSize); } private JSAudioSample getAudioSampleImp(FloatSampleBuffer samples, AudioFormat format, int bufferSize) { AudioOut out = getAudioOutput( samples.getChannelCount(), bufferSize, format.getSampleRate(), format.getSampleSizeInBits() ); if (out != null) { SampleSignal ssig = new SampleSignal(samples); out.setAudioSignal(ssig); long length = AudioUtils.frames2Millis(samples.getSampleCount(), format); BasicMetaData meta = new BasicMetaData(samples.toString(), length, samples.getSampleCount()); return new JSAudioSample(meta, ssig, out); } else { error("Couldn't acquire an output."); } return null; } public AudioOut getAudioOutput(int type, int bufferSize, float sampleRate, int bitDepth) { if (bitDepth != 8 && bitDepth != 16) { throw new IllegalArgumentException("Unsupported bit depth, use either 8 or 16."); } AudioFormat format = new AudioFormat(sampleRate, bitDepth, type, true, false); SourceDataLine sdl = getSourceDataLine(format, bufferSize); if (sdl != null) { return new JSAudioOutput(sdl, bufferSize); } return null; } /** @deprecated */ public AudioRecording getAudioRecordingClip(String filename) { Clip clip = null; AudioMetaData meta = null; AudioInputStream ais = getAudioInputStream(filename); if (ais != null) { AudioFormat format = ais.getFormat(); if (format instanceof MpegAudioFormat) { AudioFormat baseFormat = format; format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16, baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false); // converts the stream to PCM audio from mp3 audio ais = getAudioInputStream(format, ais); } DataLine.Info info = new DataLine.Info(Clip.class, ais.getFormat()); if (AudioSystem.isLineSupported(info)) { // Obtain and open the line. try { clip = (Clip)AudioSystem.getLine(info); clip.open(ais); } catch (Exception e) { error("Error obtaining Javasound Clip: " + e.getMessage()); return null; } Map<String, Object> props = getID3Tags(filename); long lengthInMillis = -1; if (props.containsKey("duration")) { Long dur = (Long)props.get("duration"); lengthInMillis = dur.longValue() / 1000; } meta = new MP3MetaData(filename, lengthInMillis, props); } else { error("File format not supported."); return null; } } if (meta == null) { // this means we're dealing with not-an-mp3 meta = new BasicMetaData(filename, clip.getMicrosecondLength() / 1000, -1); } return new JSAudioRecordingClip(clip, meta); } /** @deprecated */ public AudioRecording getAudioRecording(String filename) { AudioMetaData meta = null; AudioInputStream ais = getAudioInputStream(filename); byte[] samples; if (ais != null) { AudioFormat format = ais.getFormat(); if (format instanceof MpegAudioFormat) { AudioFormat baseFormat = format; format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16, baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false); // converts the stream to PCM audio from mp3 audio ais = getAudioInputStream(format, ais); // get a map of properties so we can find out how long it is Map<String, Object> props = getID3Tags(filename); // there is a property called mp3.length.bytes, but that is // the length in bytes of the mp3 file, which will of course // be much shorter than the decoded version. so we use the // duration of the file to figure out how many bytes the // decoded file will be. long dur = ((Long)props.get("duration")).longValue(); int toRead = (int)AudioUtils.millis2Bytes(dur / 1000, format); samples = loadByteAudio(ais, toRead); meta = new MP3MetaData(filename, dur / 1000, props); } else { samples = loadByteAudio(ais, (int)ais.getFrameLength() * format.getFrameSize()); long length = AudioUtils.bytes2Millis(samples.length, format); meta = new BasicMetaData(filename, length, samples.length); } SourceDataLine line = getSourceDataLine(format, 2048); if ( line != null ) { return new JSAudioRecording(this, samples, line, meta); } } return null; } private FloatSampleBuffer loadFloatAudio(AudioInputStream ais, int toRead) { FloatSampleBuffer samples = new FloatSampleBuffer(); int totalRead = 0; byte[] rawBytes = new byte[toRead]; try { // we have to read in chunks because the decoded stream won't // read more than about 2000 bytes at a time while (totalRead < toRead) { int actualRead = ais.read(rawBytes, totalRead, toRead - totalRead); if (actualRead < 1) { break; } totalRead += actualRead; } ais.close(); } catch (Exception ioe) { error("Error loading file into memory: " + ioe.getMessage()); } debug("Needed to read " + toRead + " actually read " + totalRead); samples.initFromByteArray(rawBytes, 0, totalRead, ais.getFormat()); return samples; } private byte[] loadByteAudio(AudioInputStream ais, int toRead) { int totalRead = 0; byte[] rawBytes = new byte[toRead]; try { // we have to read in chunks because the decoded stream won't // read more than about 2000 bytes at a time while (totalRead < toRead) { int actualRead = ais.read(rawBytes, totalRead, toRead - totalRead); if (actualRead < 1) break; totalRead += actualRead; } ais.close(); } catch (Exception ioe) { error("Error loading file into memory: " + ioe.getMessage()); } debug("Needed to read " + toRead + " actually read " + totalRead); return rawBytes; } /** * * @param filename the * @param is * @return */ AudioInputStream getAudioInputStream(String filename) { AudioInputStream ais = null; BufferedInputStream bis = null; if (filename.startsWith("http")) { try { ais = getAudioInputStream(new URL(filename)); } catch (MalformedURLException e) { error("Bad URL: " + e.getMessage()); } catch (UnsupportedAudioFileException e) { error("URL is in an unsupported audio file format: " + e.getMessage()); } catch (IOException e) { Minim.error("Error reading the URL: " + e.getMessage()); } } else { try { InputStream is = (InputStream)createInput.invoke(fileLoader, filename); if ( is != null ) { debug("Base input stream is: " + is.toString()); bis = new BufferedInputStream(is); ais = getAudioInputStream(bis); if ( ais != null ) { // don't mark it like this because it means the entire // file will be loaded into memory as it plays. this // will cause out-of-memory problems with very large files. // ais.mark((int)ais.available()); debug("Acquired AudioInputStream.\n" + "It is " + ais.getFrameLength() + " frames long.\n" + "Marking support: " + ais.markSupported()); } } else { throw new FileNotFoundException(filename); } } catch( Exception e ) { error( e.toString() ); } } return ais; } /** * This method is also part of AppletMpegSPIWorkaround, which uses yet * another workaround to load an internet radio stream. * * @param url * the URL of the stream * @return an AudioInputStream of the streaming audio * @throws UnsupportedAudioFileException * @throws IOException */ AudioInputStream getAudioInputStream(URL url) throws UnsupportedAudioFileException, IOException { // alexey fix: we use MpegAudioFileReaderWorkaround with URL and user // agent return new MpegAudioFileReaderWorkaround(this).getAudioInputStream(url, null); } /** * This method is a replacement for * AudioSystem.getAudioInputStream(InputStream), which includes workaround * for getting an mp3 AudioInputStream when sketch is running in an applet. * The workaround was developed by the Tritonus team and originally comes * from the package javazoom.jlgui.basicplayer * * @param is * The stream to convert to an AudioInputStream * @return an AudioInputStream that will read from is * @throws UnsupportedAudioFileException * @throws IOException */ AudioInputStream getAudioInputStream(InputStream is) throws UnsupportedAudioFileException, IOException { try { return AudioSystem.getAudioInputStream(is); } catch (Exception iae) { debug("Using AppletMpegSPIWorkaround to get codec"); return new MpegAudioFileReader(this).getAudioInputStream(is); } } /** * This method is a replacement for * AudioSystem.getAudioInputStream(AudioFormat, AudioInputStream), which is * used for audio format conversion at the stream level. This method includes * a workaround for converting from an mp3 AudioInputStream when the sketch * is running in an applet. The workaround was developed by the Tritonus team * and originally comes from the package javazoom.jlgui.basicplayer * * @param targetFormat * the AudioFormat to convert the stream to * @param sourceStream * the stream containing the unconverted audio * @return an AudioInputStream in the target format */ AudioInputStream getAudioInputStream(AudioFormat targetFormat, AudioInputStream sourceStream) { try { return AudioSystem.getAudioInputStream(targetFormat, sourceStream); } catch (IllegalArgumentException iae) { debug("Using AppletMpegSPIWorkaround to get codec"); try { Class.forName("javazoom.spi.mpeg.sampled.convert.MpegFormatConversionProvider"); return new javazoom.spi.mpeg.sampled.convert.MpegFormatConversionProvider().getAudioInputStream( targetFormat, sourceStream); } catch (ClassNotFoundException cnfe) { throw new IllegalArgumentException("Mpeg codec not properly installed"); } } } SourceDataLine getSourceDataLine(AudioFormat format, int bufferSize) { SourceDataLine line = null; DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); if ( AudioSystem.isLineSupported(info) ) { try { if ( outputMixer == null ) { line = (SourceDataLine)AudioSystem.getLine(info); } else { line = (SourceDataLine)outputMixer.getLine(info); } // remember that time you spent, like, an entire afternoon fussing // with this buffer size to try to get the latency decent on Linux? // Yah, don't fuss with this anymore, ok? line.open(format, bufferSize * format.getFrameSize() * 4); if ( line.isOpen() ) { debug("SourceDataLine is " + line.getClass().toString() + "\n" + "Buffer size is " + line.getBufferSize() + " bytes.\n" + "Format is " + line.getFormat().toString() + "."); return line; } } catch (Exception e) { error("Couldn't open the line: " + e.getMessage()); } } error("Unable to return a SourceDataLine: unsupported format - " + format.toString()); return line; } TargetDataLine getTargetDataLine(AudioFormat format, int bufferSize) { TargetDataLine line = null; DataLine.Info info = new DataLine.Info(TargetDataLine.class, format); if (AudioSystem.isLineSupported(info)) { try { if ( inputMixer == null ) { line = (TargetDataLine)AudioSystem.getLine(info); } else { line = (TargetDataLine)inputMixer.getLine(info); } line.open(format, bufferSize * format.getFrameSize()); debug("TargetDataLine buffer size is " + line.getBufferSize() + "\n" + "TargetDataLine format is " + line.getFormat().toString() + "\n" + "TargetDataLine info is " + line.getLineInfo().toString()); } catch (Exception e) { error("Error acquiring TargetDataLine: " + e.getMessage()); } } else { error("Unable to return a TargetDataLine: unsupported format - " + format.toString()); } return line; } }
xpy/Minim
src/ddf/minim/javasound/JSMinim.java
Java
lgpl-3.0
25,962
'use strict'; System.register(['./persistent-object', './persistent-data', './symbols'], function (_export, _context) { "use strict"; var PersistentObject, PersistentData, VERSION, _createClass, _get, configMap, Collection, CollectionFactory; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function _extendableBuiltin(cls) { function ExtendableBuiltin() { var instance = Reflect.construct(cls, Array.from(arguments)); Object.setPrototypeOf(instance, Object.getPrototypeOf(this)); return instance; } ExtendableBuiltin.prototype = Object.create(cls.prototype, { constructor: { value: cls, enumerable: false, writable: true, configurable: true } }); if (Object.setPrototypeOf) { Object.setPrototypeOf(ExtendableBuiltin, cls); } else { ExtendableBuiltin.__proto__ = cls; } return ExtendableBuiltin; } function setCollectionData(collection, array) { var config = configMap.get(collection); config.silent = true; if (config.array) { if (config.array === array) { return; } collection.clear(); } config.array = array; array.splice(0, array.length).forEach(function (data) { var item = new config.Type(); PersistentData.inject(item, data); collection.add(item); }); config.silent = false; } _export('setCollectionData', setCollectionData); function versionUp(target) { if (target) { target[VERSION]++; } } function getArrayForTesting(collection) { var config = configMap.get(collection); return config ? config.array : undefined; } _export('getArrayForTesting', getArrayForTesting); return { setters: [function (_persistentObject) { PersistentObject = _persistentObject.PersistentObject; }, function (_persistentData) { PersistentData = _persistentData.PersistentData; }, function (_symbols) { VERSION = _symbols.VERSION; }], execute: function () { _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; configMap = new WeakMap(); Collection = function (_extendableBuiltin2) { _inherits(Collection, _extendableBuiltin2); function Collection() { _classCallCheck(this, Collection); return _possibleConstructorReturn(this, (Collection.__proto__ || Object.getPrototypeOf(Collection)).apply(this, arguments)); } _createClass(Collection, [{ key: 'newItem', value: function newItem() { var config = configMap.get(this); var item = new config.Type(); this.add(item); return item; } }, { key: 'add', value: function add(item) { var config = configMap.get(this); if (!(item instanceof config.Type)) { throw new TypeError('collection item must be of type \'' + config.Type.name + '\''); } var data = PersistentData.extract(item) || {}; config.array.push(data); PersistentObject.apply(item, data, config.target); _get(Collection.prototype.__proto__ || Object.getPrototypeOf(Collection.prototype), 'add', this).call(this, item); if (!config.silent) { versionUp(config.target); } return this; } }, { key: 'clear', value: function clear() { var config = configMap.get(this); config.array.splice(0, config.array.length); _get(Collection.prototype.__proto__ || Object.getPrototypeOf(Collection.prototype), 'clear', this).call(this); if (!config.silent) { versionUp(config.target); } } }, { key: 'delete', value: function _delete(item) { var config = configMap.get(this); var data = PersistentData.extract(item); var index = config.array.indexOf(data); config.array.splice(index, 1); var deleted = _get(Collection.prototype.__proto__ || Object.getPrototypeOf(Collection.prototype), 'delete', this).call(this, item); versionUp(config.target); return deleted; } }]); return Collection; }(_extendableBuiltin(Set)); _export('CollectionFactory', CollectionFactory = function () { function CollectionFactory() { _classCallCheck(this, CollectionFactory); } _createClass(CollectionFactory, null, [{ key: 'create', value: function create(Type, array, target) { if (!Type.isCollectible) { throw new TypeError('collection type must be @Collectible'); } var collection = new Collection(); configMap.set(collection, { Type: Type, silent: false, target: target }); setCollectionData(collection, array); return collection; } }]); return CollectionFactory; }()); _export('CollectionFactory', CollectionFactory); } }; });
trenneman/persistence
dist/system/collection.js
JavaScript
lgpl-3.0
7,498
// Copyright 2017 The go-ethereum Authors // This file is part of go-ethereum. // // go-ethereum is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // go-ethereum is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>. package main import ( "fmt" "github.com/energicryptocurrency/energi/log" ) // ensureVirtualHost checks whether a reverse-proxy is running on the specified // host machine, and if yes requests a virtual host from the user to host a // specific web service on. If no proxy exists, the method will offer to deploy // one. // // If the user elects not to use a reverse proxy, an empty hostname is returned! func (w *wizard) ensureVirtualHost(client *sshClient, port int, def string) (string, error) { proxy, _ := checkNginx(client, w.network) if proxy != nil { // Reverse proxy is running, if ports match, we need a virtual host if proxy.port == port { fmt.Println() fmt.Printf("Shared port, which domain to assign? (default = %s)\n", def) return w.readDefaultString(def), nil } } // Reverse proxy is not running, offer to deploy a new one fmt.Println() fmt.Println("Allow sharing the port with other services (y/n)? (default = yes)") if w.readDefaultYesNo(true) { nocache := false if proxy != nil { fmt.Println() fmt.Printf("Should the reverse-proxy be rebuilt from scratch (y/n)? (default = no)\n") nocache = w.readDefaultYesNo(false) } if out, err := deployNginx(client, w.network, port, nocache); err != nil { log.Error("Failed to deploy reverse-proxy", "err", err) if len(out) > 0 { fmt.Printf("%s\n", out) } return "", err } // Reverse proxy deployed, ask again for the virtual-host fmt.Println() fmt.Printf("Proxy deployed, which domain to assign? (default = %s)\n", def) return w.readDefaultString(def), nil } // Reverse proxy not requested, deploy as a standalone service return "", nil }
energicryptocurrency/energi
cmd/puppeth/wizard_nginx.go
GO
lgpl-3.0
2,391
; PROLOGUE(sumdiff_n) ; ; Copyright 2011 The Code Cavern ; ; Windows Conversion Copyright 2008 Brian Gladman ; ; This file is part of the MPIR Library. ; ; The MPIR Library is free software; you can redistribute it and/or modify ; it under the terms of the GNU Lesser General Public License as published ; by the Free Software Foundation; either version 2.1 of the License, or (at ; your option) any later version. ; ; The MPIR Library is distributed in the hope that it will be useful, but ; WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY ; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public ; License for more details. ; ; You should have received a copy of the GNU Lesser General Public License ; along with the MPIR Library; see the file COPYING.LIB. If not, write ; to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, ; Boston, MA 02110-1301, USA. ; ; mp_limb_t mpn_sumdiff_n(mp_ptr, mp_ptr, mp_ptr, mp_ptr, mp_size_t) ; rax rdi rsi rdx rcx r8 ; rax rcx rdx r8 r9 [rsp+40] %include "yasm_mac.inc" %define reg_save_list rbx, rbp, rsi, rdi, r12, r13, r14, r15 CPU Core2 BITS 64 FRAME_PROC mpn_sumdiff_n, 0, reg_save_list mov rbx, [rsp+stack_use+40] xor rax, rax mov r10d, 3 lea rdi, [rcx+rbx*8-24] lea rsi, [rdx+rbx*8-24] sub r10, rbx lea rdx, [r8+rbx*8-24] lea rcx, [r9+rbx*8-24] mov r9, rax jnc .2 align 16 .1: sahf mov r8, [rdx+r10*8] mov r11, r8 adc r8, [rcx+r10*8] mov rbx, [rdx+r10*8+8] mov r13, rbx adc rbx, [rcx+r10*8+8] mov rbp, [rdx+r10*8+16] mov r12, [rdx+r10*8+24] mov r14, rbp mov r15, r12 adc rbp, [rcx+r10*8+16] adc r12, [rcx+r10*8+24] lahf add r9b, 255 sbb r11, [rcx+r10*8] mov [rdi+r10*8], r8 sbb r13, [rcx+r10*8+8] sbb r14, [rcx+r10*8+16] mov [rdi+r10*8+8], rbx sbb r15, [rcx+r10*8+24] mov [rdi+r10*8+16], rbp mov [rdi+r10*8+24], r12 mov [rsi+r10*8+8], r13 setc r9b add r10, 4 mov [rsi+r10*8+16-32], r14 mov [rsi+r10*8+24-32], r15 mov [rsi+r10*8-32], r11 jnc .1 .2: cmp r10, 2 jg .6 je .5 jp .4 .3: sahf mov r8, [rdx] mov r11, r8 adc r8, [rcx] mov rbx, [rdx+8] mov r13, rbx adc rbx, [rcx+8] mov rbp, [rdx+16] mov r14, rbp adc rbp, [rcx+16] lahf add r9b, 255 sbb r11, [rcx] mov [rdi], r8 sbb r13, [rcx+8] sbb r14, [rcx+16] mov [rdi+8], rbx mov [rdi+16], rbp mov [rsi+8], r13 setc r9b mov [rsi+16], r14 mov [rsi], r11 sahf mov rax, 0 adc rax, 0 add r9b, 255 rcl rax, 1 EXIT_PROC reg_save_list .4: sahf mov r8, [rdx+8] mov r11, r8 adc r8, [rcx+8] mov rbx, [rdx+8+8] mov r13, rbx adc rbx, [rcx+8+8] lahf add r9b, 255 sbb r11, [rcx+8] mov [rdi+8], r8 sbb r13, [rcx+8+8] mov [rdi+8+8], rbx mov [rsi+8+8], r13 setc r9b mov [rsi+8], r11 sahf mov rax, 0 adc rax, 0 add r9b, 255 rcl rax, 1 EXIT_PROC reg_save_list .5: sahf mov r8, [rdx+16] mov r11, r8 adc r8, [rcx+16] lahf add r9b, 255 sbb r11, [rcx+16] mov [rdi+16], r8 setc r9b mov [rsi+16], r11 .6: sahf mov rax, 0 adc rax, 0 add r9b, 255 rcl rax, 1 END_PROC reg_save_list end
cloudcompare/cork
contrib/mpir-2.6.0/mpn/x86_64w/core2/penryn/sumdiff_n.asm
Assembly
lgpl-3.0
4,383
#ifndef _B_UNITTEST_H_ #define _B_UNITTEST_H_ #include <B/Core/Common.h> namespace B { class UnitTest { public: UnitTest(); virtual ~UnitTest(); virtual INT32 doTest() = 0; }; } /* namespace B */ #endif /* _B_UNITTEST_H_ */
WadeHsiao/B
include/B/Test/UnitTest.h
C
lgpl-3.0
233
/* * * This file is part of three4g. * * three4g is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesse General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * three4g is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with three4g. If not, see <http://www.gnu.org/licenses/>. * * (c) 2012 by Oliver Damm, Am Wasserberg 8, 22869 Schenefeld * * mail: oliver [dot] damm [at] gmx [dot] de * web: http://www.blimster.net */ package net.blimster.gwt.threejs.materials; import net.blimster.gwt.threejs.materials.Material; /** * This file is generated, do not edit. */ public final class LineBasicMaterial extends Material { protected LineBasicMaterial() { super(); } public static native LineBasicMaterial create(int _color) /*-{ return new $wnd.THREE.LineBasicMaterial({ color : _color }); }-*/; }
Blimster/three4g
net.blimster.gwt.threejs/src-gen/net/blimster/gwt/threejs/materials/LineBasicMaterial.java
Java
lgpl-3.0
1,281
/* radare - LGPL - Copyright 2009-2018 - pancake */ #include "r_cons.h" #include "r_core.h" #include "r_types.h" #include "r_io.h" static const char *help_msg_S[] = { "Usage:","S[?-.*=adlr] [...]","", "S","","list sections", "S"," paddr va sz [vsz] name rwx","add new section (if(!vsz)vsz=sz)", "S.","","show current section name", "S.-*","","remove all sections in current offset", "S*","","list sections (in radare commands)", "S-[id]","","remove section identified by id", "S-.","","remove section at core->offset (can be changed with @)", "S=","","list sections (ascii-art bars) (io.va to display paddr or vaddr)", "Sa","[-] [A] [B] [[off]]","Specify arch and bits for given section", "Sf"," [baddr]","Alias for S 0 0 $s $s foo rwx", "Sl"," [file]","load contents of file into current section (see dml)", "Sr"," [name]","rename section on current seek", "SR", "[?]", "Remap sections with different mode of operation", NULL }; static const char *help_msg_Sl[] = { "Usage:", "Sl", "[file]", NULL }; static const char *help_msg_Sr[] = { "Usage:", "Sr", "[name] ([offset])", NULL }; static const char* help_msg_SR[] = { "Usage:","SR[b|s][a|p|e] [id]","", "SRb", "[a|p|e] binid", "Remap sections of binid for Analysis, Patch or Emulation", "SRs","[a|p|e] secid","Remap section with sectid for Analysis, Patch or Emulation", NULL }; static void cmd_section_init(RCore *core) { DEFINE_CMD_DESCRIPTOR (core, S); DEFINE_CMD_DESCRIPTOR (core, Sl); DEFINE_CMD_DESCRIPTOR (core, Sr); } #define PRINT_CURRENT_SEEK \ if (i > 0 && len != 0) { \ if (seek == UT64_MAX) seek = 0; \ io->cb_printf ("=> 0x%08"PFMT64x" |", seek); \ for (j = 0; j < width; j++) { \ io->cb_printf ( \ ((j*mul) + min >= seek && \ (j*mul) + min <= seek + len) \ ? "^" : "-"); \ } \ io->cb_printf ("| 0x%08"PFMT64x"\n", seek+len); \ } static void list_section_visual(RIO *io, ut64 seek, ut64 len, int use_color, int cols) { ut64 mul, min = -1, max = -1; SdbListIter *iter; RIOSection *s; int j, i = 0; int width = cols - 70; if (width < 1) { width = 30; } // seek = r_io_section_vaddr_to_maddr_try (io, seek); // seek = r_io_section_vaddr_to_maddr_try (io, seek); ls_foreach (io->sections, iter, s) { if (min == -1 || s->paddr < min) { min = s->paddr; } if (max == -1 || s->paddr+s->size > max) { max = s->paddr + s->size; } } mul = (max-min) / width; if (min != -1 && mul != 0) { const char * color = "", *color_end = ""; char buf[128]; i = 0; ls_foreach (io->sections, iter, s) { r_num_units (buf, s->size); if (use_color) { color_end = Color_RESET; if (s->flags & 1) { // exec bit color = Color_GREEN; } else if (s->flags & 2) { // write bit color = Color_RED; } else { color = ""; color_end = ""; } } else { color = ""; color_end = ""; } if (io->va) { io->cb_printf ("%02d%c %s0x%08"PFMT64x"%s |", s->id, (seek >= s->vaddr && seek < s->vaddr + s->vsize) ? '*' : ' ', color, s->vaddr, color_end); } else { io->cb_printf ("%02d%c %s0x%08"PFMT64x"%s |", s->id, (seek >= s->paddr && seek < s->paddr + s->size) ? '*' : ' ', color, s->paddr, color_end); } for (j = 0; j < width; j++) { ut64 pos = min + (j * mul); ut64 npos = min + ((j + 1) * mul); if (s->paddr < npos && (s->paddr + s->size) > pos) io->cb_printf ("#"); else io->cb_printf ("-"); } if (io->va) { io->cb_printf ("| %s0x%08"PFMT64x"%s %5s %s %04s\n", color, s->vaddr + s->vsize, color_end, buf, r_str_rwx_i (s->flags), s->name); } else { io->cb_printf ("| %s0x%08"PFMT64x"%s %5s %s %04s\n", color, s->paddr+s->size, color_end, buf, r_str_rwx_i (s->flags), s->name); } i++; } PRINT_CURRENT_SEEK; } } static void __section_list (RIO *io, ut64 offset, RPrint *print, int rad) { SdbListIter *iter; RIOSection *s; if (!io || !io->sections || !print || !print->cb_printf) { return; } if (rad == '=') { // "S=" int cols = r_cons_get_size (NULL); list_section_visual (io, offset, -1, print->flags & R_PRINT_FLAGS_COLOR, cols); } else if (rad) { ls_foreach (io->sections, iter, s) { char *n = strdup (s->name); r_name_filter (n, strlen (n)); print->cb_printf ("f section.%s %"PFMT64d" 0x%"PFMT64x"\n", n, s->size, s->vaddr); print->cb_printf ("S 0x%08"PFMT64x" 0x%08"PFMT64x" 0x%08" PFMT64x" 0x%08"PFMT64x" %s %s\n", s->paddr, s->vaddr, s->size, s->vsize, n, r_str_rwx_i (s->flags)); free (n); } } else { ls_foreach (io->sections, iter, s) { print->cb_printf ("[%02d:%02d]", s->bin_id, s->id); if (io->va) { if ((s->vaddr <= offset) && ((offset - s->vaddr) < s->vsize)) { print->cb_printf (" * "); } else { print->cb_printf (" . "); } } else { if ((s->paddr <= offset) && ((offset - s->paddr) < s->size)) { print->cb_printf (" * "); } else { print->cb_printf (" . "); } } print->cb_printf ("pa=0x%08"PFMT64x" %s va=0x%08"PFMT64x " sz=0x%04"PFMT64x" vsz=0x%04"PFMT64x" %s", s->paddr, r_str_rwx_i (s->flags), s->vaddr, s->size, s->vsize, s->name); if (s->arch && s->bits) { print->cb_printf (" ; %s %d", r_sys_arch_str (s->arch), s->bits); } print->cb_printf ("\n"); } } } static void update_section_flag_at_with_oldname(RIOSection *s, RFlag *flags, ut64 off, char *oldname) { RFlagItem *item = NULL; RListIter *iter; const RList *list = NULL; int len = 0; char *secname = NULL; list = r_flag_get_list (flags, s->vaddr); secname = sdb_fmt ("section.%s", oldname); len = strlen (secname); r_list_foreach (list, iter, item) { if (!item->name) { continue; } if (!strncmp (item->name, secname, R_MIN (strlen (item->name), len))) { free (item->realname); item->name = strdup (sdb_fmt ("section.%s", s->name)); r_str_trim (item->name); r_name_filter (item->name, 0); item->realname = item->name; break; } } list = r_flag_get_list (flags, s->vaddr + s->size); secname = sdb_fmt ("section_end.%s", oldname); len = strlen (secname); r_list_foreach (list, iter, item) { if (!item->name) { continue; } if (!strncmp (item->name, secname, R_MIN (strlen (item->name), len))) { free (item->realname); item->name = strdup (sdb_fmt ("section_end.%s", s->name)); r_str_trim (item->name); r_name_filter (item->name, 0); item->realname = item->name; break; } } } static int cmd_section_reapply(RCore *core, const char *input) { int mode = 0; ut32 id; switch (*input) { case '?': r_core_cmd_help (core, help_msg_SR); break; case 'b': case 's': switch (input[1]) { case 'e': mode = R_IO_SECTION_APPLY_FOR_EMULATOR; break; case 'p': mode = R_IO_SECTION_APPLY_FOR_PATCH; break; case 'a': mode = R_IO_SECTION_APPLY_FOR_ANALYSIS; break; default: r_core_cmd_help (core, help_msg_SR); return 0; } if (*input == 'b') { id = (ut32)r_num_math (core->num, input + 2); if (!r_io_section_reapply_bin (core->io, id, mode)) { eprintf ("Cannot reapply section with binid %d\n", id); } } else { id = (ut32)r_num_math (core->num, input + 2); if (!r_io_section_reapply (core->io, id, mode)) { eprintf ("Cannot reapply section with secid %d\n", id); } } break; default: r_core_cmd_help (core, help_msg_SR); break; } return 0; } static int cmd_section(void *data, const char *input) { RCore *core = (RCore *)data; switch (*input) { case '?': // "S?" r_core_cmd_help (core, help_msg_S); // TODO: add command to resize current section break; case 'R' : // "SR" return cmd_section_reapply (core, input + 1); case 'f': // "Sf" if (input[1] == ' ') { ut64 n = r_num_math (core->num, input + 1); r_core_cmdf (core, "S 0x%"PFMT64x" 0x%"PFMT64x" $s $s foo rwx", n, n); } else { r_core_cmd0 (core, "S 0 0 $s $s foo rwx"); } break; case 'a': // "Sa" switch (input[1]) { case '\0': { int b = 0; const char *n = r_io_section_get_archbits (core->io, core->offset, &b); if (n) { r_cons_printf ("%s %d\n", n, b); } } break; case '-': // "Sa-" r_io_section_set_archbits (core->io, core->offset, NULL, 0); break; case '?': // "Sa?" default: eprintf ("Usage: Sa[-][arch] [bits] [[off]]\n"); break; case ' ': // "Sa " { int i; char *ptr = strdup (input+2); const char *arch = NULL; char bits = 0; ut64 offset = core->offset; i = r_str_word_set0 (ptr); if (i < 2) { eprintf ("Missing argument\n"); free (ptr); break; } if (i == 3) { offset = r_num_math (core->num, r_str_word_get0 (ptr, 2)); } bits = r_num_math (core->num, r_str_word_get0 (ptr, 1)); arch = r_str_word_get0 (ptr, 0); if (r_io_section_set_archbits (core->io, offset, arch, bits)) { core->section = NULL; r_core_seek (core, core->offset, 0); } else { eprintf ("Cannot set arch/bits at 0x%08"PFMT64x"\n",offset); } free (ptr); break; } } break; case 'r': // "Sr" if (input[1] == ' ') { RIOSection *s; // int len = 0; ut64 vaddr; char *p = strchr (input + 2, ' '); if (p) { *p = 0; vaddr = r_num_math (core->num, p + 1); // len = (int)(size_t)(p-input + 2); } else { vaddr = core->offset; } s = r_io_section_vget (core->io, vaddr); if (s) { char *oldname = s->name; s->name = strdup (input + 2); //update flag space for the given section update_section_flag_at_with_oldname (s, core->flags, s->vaddr, oldname); free (oldname); } else { eprintf ("No section found in 0x%08"PFMT64x"\n", core->offset); } } else { r_core_cmd_help (core, help_msg_Sr); } break; case 'l': // "Sl" { ut64 o = core->offset; SdbListIter *iter; RIOSection *s; if (input[1] != ' ') { r_core_cmd_help (core, help_msg_Sl); return false; } if (core->io->va || core->io->debug) { s = r_io_section_vget (core->io, core->offset); o = s ? core->offset - s->vaddr + s->paddr : core->offset; } ls_foreach (core->io->sections, iter, s) { if (o >= s->paddr && o < s->paddr + s->size) { int sz; char *buf = r_file_slurp (input + 2, &sz); // TODO: use mmap here. we need a portable implementation if (!buf) { eprintf ("Cannot allocate 0x%08"PFMT64x"" " bytes\n", s->size); return false; } r_io_write_at (core->io, s->vaddr, (const ut8*)buf, sz); eprintf ("Loaded %d byte(s) into the map region " " at 0x%08"PFMT64x"\n", sz, s->vaddr); free (buf); return true; } } eprintf ("No debug region found here\n"); return false; } break; case '-': // "S-" // remove all sections if (input[1] == '*') { r_io_section_init (core->io); } if (input[1] == '.') { RIOSection *s = r_io_section_vget (core->io, core->offset); if (!s) { return 0; } // use offset r_io_section_rm (core->io, s->id); } if (input[1]) { r_io_section_rm (core->io, atoi (input + 1)); } break; case ' ': // "S " switch (input[1]) { case '-': // "S -" remove if (input[2] == '?' || input[2] == '\0') { eprintf ("Usage: S -N # where N is the " " section index\n"); } else { r_io_section_rm (core->io, atoi (input + 1)); } break; default: { int i, rwx = 7; char *ptr = strdup (input + 1); const char *name = NULL; char vname[64]; ut64 vaddr = 0LL; ut64 paddr = 0LL; ut64 size = 0LL; ut64 vsize = 0LL; int bin_id = -1; int fd = r_core_file_cur_fd (core); i = r_str_word_set0 (ptr); switch (i) { case 7: //get bin id bin_id = r_num_math (core->num, r_str_word_get0 (ptr, 6)); case 6: // get rwx rwx = r_str_rwx (r_str_word_get0 (ptr, 5)); case 5: // get name name = r_str_word_get0 (ptr, 4); case 4: // get vsize vsize = r_num_math (core->num, r_str_word_get0 (ptr, 3)); case 3: // get size size = r_num_math (core->num, r_str_word_get0 (ptr, 2)); case 2: // get vaddr vaddr = r_num_math (core->num, r_str_word_get0 (ptr, 1)); case 1: // get paddr paddr = r_num_math (core->num, r_str_word_get0 (ptr, 0)); } if (!vsize) { vsize = size; if (i > 3) { name = r_str_word_get0 (ptr, 3); } if (i > 4) { rwx = r_str_rwx (r_str_word_get0 (ptr, 4)); } } if (!name || !*name) { sprintf (vname, "area%d", (int)ls_length (core->io->sections)); name = vname; } RIOSection *sec = r_io_section_add (core->io, paddr, vaddr, size, vsize, rwx, name, bin_id, fd); r_io_create_mem_for_section (core->io, sec); free (ptr); } break; } break; case '.': // "S." if (input[1] == '-') { // "S.-" ut64 o = core->offset; SdbListIter *iter, *iter2; RIOSection *s; if (core->io->va || core->io->debug) { s = r_io_section_vget (core->io, o); o = s ? o - s->vaddr + s->paddr : o; } ls_foreach_safe (core->io->sections, iter, iter2, s) { if (o >= s->paddr && o < s->paddr + s->size) { r_io_section_rm (core->io, s->id); if (input[2] != '*') { break; } } } } else { ut64 o = core->offset; SdbListIter *iter; RIOSection *s; if (core->io->va || core->io->debug) { s = r_io_section_vget (core->io, o); o = s ? o - s->vaddr + s->paddr : o; } if (input[1] == 'j') { // "S.j" r_cons_printf ("["); ls_foreach (core->io->sections, iter, s) { if (o >= s->paddr && o < s->paddr + s->size) { char *name = r_str_escape (s->name); r_cons_printf ("{\"start\":%" PFMT64u ",\"end\":%" PFMT64u ",\"name\":\"%s\"}", s->paddr + s->vaddr, s->paddr + s->vaddr + s->size, name); free (name); } } r_cons_printf ("]"); } else { ls_foreach (core->io->sections, iter, s) { if (o >= s->paddr && o < s->paddr + s->size) { r_cons_printf ("0x%08"PFMT64x" 0x%08"PFMT64x" %s\n", s->paddr + s->vaddr, s->paddr + s->vaddr + s->size, s->name); break; } } } } break; case '\0': // "S" case '=': // "S=" case '*': // "S*" __section_list (core->io, core->offset, core->print, *input); break; } return 0; }
jroimartin/radare2
libr/core/cmd_section.c
C
lgpl-3.0
14,373
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns='http://www.w3.org/1999/xhtml' lang='he' dir='rtl'> <head> <meta http-equiv='Content-Type' content='text/html; charset=windows-1255' /> <meta http-equiv='Content-Script-Type' content='text/javascript' /> <meta http-equiv='revisit-after' content='15 days' /> <link rel='stylesheet' href='../../../_script/klli.css' /> <link rel='stylesheet' href='../../_themes/klli.css' /> <link rel='canonical' href='http://tora.us.fm/tnk1/ktuv/mj/24-24.html' /> <title>äîöãé÷ àú äøùò éæëä ìáøëú äøùò åì÷ììú ëì ùàø äöéáåø</title> <meta name='author' content='àøàì' /> <meta name='receiver' content='' /> <meta name='jmQovc' content='tnk1/ktuv/mj/24-24.html' /> <meta name='tvnit' content='' /> </head> <body lang='he' class='sgulot'><div class='pnim'> <!--NiwutElyon0--> <div class='NiwutElyon'> <div class='NiwutElyon'><a class='link_to_homepage' href='../../index.html'>øàùé</a>&gt;<a href='../../ktuv/mj/24-24.html'></a>&gt;</div> </div> <!--NiwutElyon1--> <h1 id='h1'>äîöãé÷ àú äøùò éæëä ìáøëú äøùò åì÷ììú ëì ùàø äöéáåø</h1> <div id='idfields'> <p>îàú: àøàì</p> </div> <script type='text/javascript' src='../../../_script/vars.js'></script> <script type='text/javascript'>kotrt()</script> <div id='tokn'> <table class='inner_navigation'> <tr><td> <a href='00-00.html'><b>ñôø îùìé</b></a> &nbsp;&nbsp;&nbsp;ôø÷&nbsp;&nbsp; &nbsp;<a href='01-00.html'>à</a>&nbsp; &nbsp;<a href='02-00.html'>á</a>&nbsp; &nbsp;<a href='03-00.html'>â</a>&nbsp; &nbsp;<a href='04-00.html'>ã</a>&nbsp; &nbsp;<a href='05-00.html'>ä</a>&nbsp; &nbsp;<a href='06-00.html'>å</a>&nbsp; &nbsp;<a href='07-00.html'>æ</a>&nbsp; &nbsp;<a href='08-00.html'>ç</a>&nbsp; &nbsp;<a href='09-00.html'>è</a>&nbsp; &nbsp;<a href='10-00.html'>é</a>&nbsp; &nbsp;<a href='11-00.html'>éà</a>&nbsp; &nbsp;<a href='12-00.html'>éá</a>&nbsp; &nbsp;<a href='13-00.html'>éâ</a>&nbsp; &nbsp;<a href='14-00.html'>éã</a>&nbsp; &nbsp;<a href='15-00.html'>èå</a>&nbsp; &nbsp;<a href='16-00.html'>èæ</a>&nbsp; &nbsp;<a href='17-00.html'>éæ</a>&nbsp; &nbsp;<a href='18-00.html'>éç</a>&nbsp; &nbsp;<a href='19-00.html'>éè</a>&nbsp; &nbsp;<a href='20-00.html'>ë</a>&nbsp; &nbsp;<a href='21-00.html'>ëà</a>&nbsp; &nbsp;<a href='22-00.html'>ëá</a>&nbsp; &nbsp;<a href='23-00.html'>ëâ</a>&nbsp; &nbsp;<b>ëã</b>&nbsp; &nbsp;<a href='25-00.html'>ëä</a>&nbsp; &nbsp;<a href='26-00.html'>ëå</a>&nbsp; &nbsp;<a href='27-00.html'>ëæ</a>&nbsp; &nbsp;<a href='28-00.html'>ëç</a>&nbsp; &nbsp;<a href='29-00.html'>ëè</a>&nbsp; &nbsp;<a href='30-00.html'>ì</a>&nbsp; &nbsp;<a href='31-00.html'>ìà</a>&nbsp; </td></tr> <tr><td> &nbsp;<a href='24-00.html'>ôø÷ ëã</a>&nbsp;&nbsp;&nbsp;&nbsp;ôñå÷&nbsp;&nbsp; &nbsp;<a href='24-01.html'>1</a>&nbsp; &nbsp;<a href='24-02.html'>2</a>&nbsp; &nbsp;<a href='24-03.html'>3</a>&nbsp; &nbsp;<a href='24-04.html'>4</a>&nbsp; &nbsp;<a href='24-05.html'>5</a>&nbsp; &nbsp;<a href='24-06.html'>6</a>&nbsp; &nbsp;<a href='24-07.html'>7</a>&nbsp; &nbsp;<a href='24-08.html'>8</a>&nbsp; &nbsp;<a href='24-09.html'>9</a>&nbsp; &nbsp;<a href='24-10.html'>10</a>&nbsp; &nbsp;<a href='24-11.html'>11</a>&nbsp; &nbsp;<a href='24-12.html'>12</a>&nbsp; &nbsp;<a href='24-13.html'>13</a>&nbsp; &nbsp;<a href='24-14.html'>14</a>&nbsp; &nbsp;<a href='24-15.html'>15</a>&nbsp; &nbsp;<a href='24-16.html'>16</a>&nbsp; &nbsp;<a href='24-17.html'>17</a>&nbsp; &nbsp;<a href='24-18.html'>18</a>&nbsp; &nbsp;<a href='24-19.html'>19</a>&nbsp; &nbsp;<a href='24-20.html'>20</a>&nbsp; &nbsp;<a href='24-21.html'>21</a>&nbsp; &nbsp;<a href='24-22.html'>22</a>&nbsp; &nbsp;<a href='24-23.html'>23</a>&nbsp; &nbsp;<b>24</b>&nbsp; &nbsp;<a href='24-25.html'>25</a>&nbsp; &nbsp;<a href='24-26.html'>26</a>&nbsp; &nbsp;<a href='24-27.html'>27</a>&nbsp; &nbsp;<a href='24-28.html'>28</a>&nbsp; &nbsp;<a href='24-29.html'>29</a>&nbsp; &nbsp;<a href='24-30.html'>30</a>&nbsp; &nbsp;<a href='24-31.html'>31</a>&nbsp; &nbsp;<a href='24-32.html'>32</a>&nbsp; &nbsp;<a href='24-33.html'>33</a>&nbsp; &nbsp;<a href='24-34.html'>34</a>&nbsp; &nbsp;<a href='24-99.html'>ñéëåí</a>&nbsp; </td></tr> </table><!-- inner_navigation --> <div class='page single_height'> <div class='verse_and_tirgumim'> <div class='verse'> <span class='verse_number'> ëã24</span> <span class='verse_text'>àÉîÅø ìÀøÈùÑÈò 'öÇãÌÄé÷ àÈúÌÈä', éÄ÷ÌÀáËäåÌ òÇîÌÄéí, éÄæÀòÈîåÌäåÌ ìÀàËîÌÄéí -</span> </div> <div class='short'> <div class='cell tirgum longcell'> <h2 class='subtitle'> &nbsp;ñâåìåú </h2> <div class='cellcontent'> <p>- ùåôè àùø <strong>àåîø ìøùò</strong> (äàîåø ìäéåú îåøùò áîùôè) "<strong>àúä öãé÷</strong>" (æëàé) - äøùò àîðí éáøê àåúå, àáì <strong>äòí</strong> ëåìå <strong>éé÷åá</strong> àú ùîå åé÷ìì àåúå, <strong>äìàåí</strong> ëåìå <strong>éæòí</strong> òìéå -</p> </div><!--cellcontent--> </div> <div class='cell mcudot longcell'> <h2 class='subtitle'> &nbsp;îöåãåú </h2> <div class='cellcontent'> <p><strong>àåîø ìøùò 'öãé÷ àúä' - é÷áåäå</strong> (é÷ììåäå) <strong>òîéí</strong>; ëé ëàùø éøàä äøùò ù÷åøàéí àåúå öãé÷, éúô÷ø òåã éåúø ìòùåú øòä ìëì äàåîä áëìì, åìæä é÷ììå ëåìí àú ä÷åøàå öãé÷.&#160;&#160; åëï <strong>éæòîåäå </strong>(éëòñå òìéå)<strong> ìàåîéí</strong> (àåîåú); <small class="small">ëôì äãáø áîéìéí ùåðåú</small>. </p> </div><!--cellcontent--> </div> </div><!--short--> </div><!--verse_and_tirgumim--> <br style='clear:both; line-height:0' /> <div class='long'> <div class='cell hqblot longcell'> <h2 class='subtitle'> &nbsp;ä÷áìåú </h2> <div class='cellcontent'> <p>ëùáðé éùøàì ðëðñå ìàøõ éùøàì, äí ÷ééîå è÷ñ ùì áøëåú å÷ììåú, <a class="psuq" href="/tnk1/prqim/t0527.htm#26">ãáøéí ëæ26</a>: "<q class="psuq">àÈøåÌø àÂùÑÆø ìÉà éÈ÷Äéí àÆú ãÌÄáÀøÅé äÇúÌåÉøÈä äÇæÌÉàú ìÇòÂùÒåÉú àåÉúÈí; åÀàÈîÇø ëÌÈì äÈòÈí 'àÈîÅï'</q>". ò"ô çæ"ì, ìôðé ëì ÷ììä äéúä áøëä äôåëä, ëâåï "<strong>áøåê àùø é÷éí àú ãáøé äúåøä äæàú</strong>". </p><p><strong>ä÷îú äúåøä</strong> ëåììú, áéï äùàø, úåëçåú ìàðùéí ùòåáøéí òì äúåøä. îëàï, îé ùàéðå îåëéç àú äøùòéí àìà àåîø ìäí ùäí öãé÷éí - ééòðù á÷ììä ùëì ùáèé éùøàì (äð÷øàéí òîéí) ÷éììå àú äàðùéí ùàéðí î÷éîéí àú äúåøä: <strong>é÷áåäå òîéí, éæòîåäå ìàåîéí</strong>; åîöã ùðé, îé ùîåëéç àú äøùòéí åî÷éí àú äúåøä, éæëä ááøëä: <strong>åòìéäí úáåà áøëú èåá</strong> <small>(äçôõ çééí, ñôø çåîú äãú, îàîø çéæå÷ äãú, îàîø ã)</small>.</p> </div><!--cellcontent--> </div> </div><!--long--> </div><!--page--> <table class='inner_navigation'> <tr><td> &nbsp;<a href='24-00.html'>ôø÷ ëã</a>&nbsp;&nbsp;&nbsp;&nbsp;ôñå÷&nbsp;&nbsp; &nbsp;<a href='24-01.html'>1</a>&nbsp; &nbsp;<a href='24-02.html'>2</a>&nbsp; &nbsp;<a href='24-03.html'>3</a>&nbsp; &nbsp;<a href='24-04.html'>4</a>&nbsp; &nbsp;<a href='24-05.html'>5</a>&nbsp; &nbsp;<a href='24-06.html'>6</a>&nbsp; &nbsp;<a href='24-07.html'>7</a>&nbsp; &nbsp;<a href='24-08.html'>8</a>&nbsp; &nbsp;<a href='24-09.html'>9</a>&nbsp; &nbsp;<a href='24-10.html'>10</a>&nbsp; &nbsp;<a href='24-11.html'>11</a>&nbsp; &nbsp;<a href='24-12.html'>12</a>&nbsp; &nbsp;<a href='24-13.html'>13</a>&nbsp; &nbsp;<a href='24-14.html'>14</a>&nbsp; &nbsp;<a href='24-15.html'>15</a>&nbsp; &nbsp;<a href='24-16.html'>16</a>&nbsp; &nbsp;<a href='24-17.html'>17</a>&nbsp; &nbsp;<a href='24-18.html'>18</a>&nbsp; &nbsp;<a href='24-19.html'>19</a>&nbsp; &nbsp;<a href='24-20.html'>20</a>&nbsp; &nbsp;<a href='24-21.html'>21</a>&nbsp; &nbsp;<a href='24-22.html'>22</a>&nbsp; &nbsp;<a href='24-23.html'>23</a>&nbsp; &nbsp;<b>24</b>&nbsp; &nbsp;<a href='24-25.html'>25</a>&nbsp; &nbsp;<a href='24-26.html'>26</a>&nbsp; &nbsp;<a href='24-27.html'>27</a>&nbsp; &nbsp;<a href='24-28.html'>28</a>&nbsp; &nbsp;<a href='24-29.html'>29</a>&nbsp; &nbsp;<a href='24-30.html'>30</a>&nbsp; &nbsp;<a href='24-31.html'>31</a>&nbsp; &nbsp;<a href='24-32.html'>32</a>&nbsp; &nbsp;<a href='24-33.html'>33</a>&nbsp; &nbsp;<a href='24-34.html'>34</a>&nbsp; &nbsp;<a href='24-99.html'>ñéëåí</a>&nbsp; </td></tr> <tr><td> <a href='00-00.html'><b>ñôø îùìé</b></a> &nbsp;&nbsp;&nbsp;ôø÷&nbsp;&nbsp; &nbsp;<a href='01-00.html'>à</a>&nbsp; &nbsp;<a href='02-00.html'>á</a>&nbsp; &nbsp;<a href='03-00.html'>â</a>&nbsp; &nbsp;<a href='04-00.html'>ã</a>&nbsp; &nbsp;<a href='05-00.html'>ä</a>&nbsp; &nbsp;<a href='06-00.html'>å</a>&nbsp; &nbsp;<a href='07-00.html'>æ</a>&nbsp; &nbsp;<a href='08-00.html'>ç</a>&nbsp; &nbsp;<a href='09-00.html'>è</a>&nbsp; &nbsp;<a href='10-00.html'>é</a>&nbsp; &nbsp;<a href='11-00.html'>éà</a>&nbsp; &nbsp;<a href='12-00.html'>éá</a>&nbsp; &nbsp;<a href='13-00.html'>éâ</a>&nbsp; &nbsp;<a href='14-00.html'>éã</a>&nbsp; &nbsp;<a href='15-00.html'>èå</a>&nbsp; &nbsp;<a href='16-00.html'>èæ</a>&nbsp; &nbsp;<a href='17-00.html'>éæ</a>&nbsp; &nbsp;<a href='18-00.html'>éç</a>&nbsp; &nbsp;<a href='19-00.html'>éè</a>&nbsp; &nbsp;<a href='20-00.html'>ë</a>&nbsp; &nbsp;<a href='21-00.html'>ëà</a>&nbsp; &nbsp;<a href='22-00.html'>ëá</a>&nbsp; &nbsp;<a href='23-00.html'>ëâ</a>&nbsp; &nbsp;<b>ëã</b>&nbsp; &nbsp;<a href='25-00.html'>ëä</a>&nbsp; &nbsp;<a href='26-00.html'>ëå</a>&nbsp; &nbsp;<a href='27-00.html'>ëæ</a>&nbsp; &nbsp;<a href='28-00.html'>ëç</a>&nbsp; &nbsp;<a href='29-00.html'>ëè</a>&nbsp; &nbsp;<a href='30-00.html'>ì</a>&nbsp; &nbsp;<a href='31-00.html'>ìà</a>&nbsp; </td></tr> </table><!-- inner_navigation --> </div><!--tokn--> <h2 id='tguvot'>úâåáåú</h2> <ul id='ultguvot'> <li></li> </ul><!--end--> <script type='text/javascript'>tguva();txtit()</script> </div><!--pnim--> </body> </html>
erelsgl/erel-sites
tnk1/ktuv/mj/24-24.html
HTML
lgpl-3.0
10,067
namespace PacketDotNet.Ieee80211 { public struct BlockAcknowledgmentFields { public static readonly int BlockAckBitmapPosition; public static readonly int BlockAckRequestControlLength = 2; public static readonly int BlockAckRequestControlPosition; public static readonly int BlockAckStartingSequenceControlLength = 2; public static readonly int BlockAckStartingSequenceControlPosition; static BlockAcknowledgmentFields() { BlockAckRequestControlPosition = MacFields.DurationIDPosition + MacFields.DurationIDLength + (2 * MacFields.AddressLength); BlockAckStartingSequenceControlPosition = BlockAckRequestControlPosition + BlockAckRequestControlLength; BlockAckBitmapPosition = BlockAckStartingSequenceControlPosition + BlockAckStartingSequenceControlLength; } } }
chmorgan/packetnet
PacketDotNet/Ieee80211/BlockAcknowledgmentFields.cs
C#
lgpl-3.0
876
/* * Copyright (c) 2004-2020 The YAWL Foundation. All rights reserved. * The YAWL Foundation is a collaboration of individuals and * organisations who are committed to improving workflow technology. * * This file is part of YAWL. YAWL is free software: you can * redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation. * * YAWL is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General * Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with YAWL. If not, see <http://www.gnu.org/licenses/>. */ package org.yawlfoundation.yawl.elements; import java.util.*; /** * This class collects the set of all currently enabled transitions (ie. tasks) of a net. * It is designed to provide a completely correct implementation of the YAWL deferred * choice semantics. * * Enabled transitions are grouped by the id of the enabling place (condition). For * each place: if there is one or more composite tasks enabled, one of the composite * tasks is chosen (randomly if more than one) and all other tasks are not fired; * otherwise, all the atomic tasks are enabled, allowing a choice to be made from the * environment, and each atomic task is 'stamped' with an identifier that services may * use to identify tasks that are part of the same group. * * This class is used exclusively by YNetRunner's continueIfPossible() and fireTasks() * methods. * * Author: Michael Adams * Date: 5/03/2008 */ public class YEnabledTransitionSet { // a table of [place id, set of enabled transitions] private Map<String, TaskGroup> transitions = new HashMap<String, TaskGroup>(); // the only constructor public YEnabledTransitionSet() { } /** * Adds an enabled task to the relevant task group * @param task the enabled task */ public void add(YTask task) {; for (String id : getFlowsFromIDs(task)) add(id, task); } /** * Gets the final set(s) of enabled transitions (one for each enabling place) * @return the set of groups */ public Set<TaskGroup> getAllTaskGroups() { return new HashSet<TaskGroup>(transitions.values()); } /** @return true if there are no enabled transitions in this set */ public boolean isEmpty() { return transitions.isEmpty(); } /** * Adds a task to the group with the id passed * @param id the id of the enabling condition * @param task the enabled task */ private void add(String id, YTask task) { TaskGroup group = transitions.get(id) ; if (group != null) // already a group for this id group.add(task); else // create a new group transitions.put(id, new TaskGroup(task)); } /** * Gets the list of condition ids that are enabling this task * @param task the enabled task * @return a set of condition ids */ private Set<String> getFlowsFromIDs(YTask task) { Set<String> priorSet = new HashSet<String>(); for (YFlow flow : task.getPresetFlows()) { YNetElement prior = flow.getPriorElement(); if (isEnablingCondition(prior)) priorSet.add(prior.getID()) ; } return priorSet; } private boolean isEnablingCondition(YNetElement element) { return (element instanceof YCondition) && ((YCondition) element).containsIdentifier(); } /*********************************************************************************/ /** * A group of YTasks plus an identifier */ public class TaskGroup { private String _id ; // the group id of this group private List<YCompositeTask> _compositeTasks; private List<YAtomicTask> _atomicTasks; private List<YAtomicTask> _emptyAtomicTasks; /** Constructor with no args */ TaskGroup() { super(); _id = UUID.randomUUID().toString(); // generate a new id for this group } /** * Constructor with an initial group member * @param task the first task in this group */ TaskGroup(YTask task) { this(); add(task); } /** * Add a task to this group * @param task the task to add * @return true if the added task was not already in the group */ public boolean add(YTask task) { if (task instanceof YCompositeTask) { return addCompositeTask((YCompositeTask) task); } else if (task instanceof YAtomicTask) { return addAtomicTask((YAtomicTask) task); } return false; } /** * Gets the set of atomic tasks in this group * @return the set of enabled atomic tasks */ public Set<YAtomicTask> getAtomicTasks() { return _atomicTasks != null ? new HashSet<YAtomicTask>(_atomicTasks) : Collections.<YAtomicTask>emptySet(); } /** @return true if this group has at least one decomposition-less atomic task */ public boolean hasEmptyTasks() { return getEmptyTaskCount() > 0; } /** @return the number of composite tasks in this group */ public int getCompositeTaskCount() { return getTaskCount(_compositeTasks); } /** @return the number of composite tasks in this group */ public int getEmptyTaskCount() { return getTaskCount(_emptyAtomicTasks); } /** @return true if this group has at least one composite task */ public boolean hasCompositeTasks() { return getCompositeTaskCount() > 0 ; } /** @return the generated group id for this group */ public String getID() { return _id; } /** @return the deferred choice UID for this group (if any) - may be null */ public String getDeferredChoiceID() { return getTaskCount(_atomicTasks) > 1 ? _id : null; } /** * YAWL semantics are that if there is more than one composite task enabled * by a condition, one must be non-deterministically chosen to fire. * * @return null if there are no composite tasks in this group, the only * composite task if there is one, or a randomly chosen one if there are * several */ public YCompositeTask getRandomCompositeTaskFromGroup() { return getRandomTask(_compositeTasks); } /** * @return as above, except for empty tasks instead of composites */ public YAtomicTask getRandomEmptyTaskFromGroup() { return getRandomTask(_emptyAtomicTasks); } private boolean addCompositeTask(YCompositeTask task) { if (_compositeTasks == null) _compositeTasks = new ArrayList<YCompositeTask>(); return _compositeTasks.add(task); } private boolean addAtomicTask(YAtomicTask task) { if (task.getDecompositionPrototype() != null) { if (_atomicTasks == null) _atomicTasks = new ArrayList<YAtomicTask>(); return _atomicTasks.add(task); } if (_emptyAtomicTasks == null) _emptyAtomicTasks = new ArrayList<YAtomicTask>(); return _emptyAtomicTasks.add(task); } private <T extends YTask> T getRandomTask(List<T> taskList) { if (taskList == null) return null; switch (taskList.size()) { case 0 : return null; case 1 : return taskList.get(0); default: return taskList.get(new Random().nextInt(taskList.size())) ; } } private int getTaskCount(List<? extends YTask> taskList) { return taskList != null ? taskList.size() : 0; } } }
yawlfoundation/yawl
src/org/yawlfoundation/yawl/elements/YEnabledTransitionSet.java
Java
lgpl-3.0
8,207
#include <asf.h> const usart_serial_options_t usart_serial_options = { .baudrate = 9600, .charlength = USART_CHSIZE_8BIT_gc, .paritytype = USART_PMODE_DISABLED_gc, .stopbits = false }; int main (void) { /* Insert system clock initialization code here (sysclk_init()). */ sysclk_init(); board_init(); stdio_serial_init(&USARTC0, &usart_serial_options); /* Insert application code here, after the board has been initialized. */ printf("\n\rHello ATMEL World!\n\r"); while (1); }
artnavsegda/avrnavsegda
atmelstudio7/xmega/serial/serial/src/main.c
C
lgpl-3.0
504
//////////////////////////////////////////////////////////////////////// // Copyright (c) Nehmulos 2011-2014 // This file is part of N0 Strain Serialization Library. // // N0Strain-Serialization-Library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // N0Strain-Serialization-Library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with N0Strain-Serialization-Library. If not, see https://gnu.org/licenses/lgpl-3.0 //////////////////////////////////////////////////////////////////////// #ifndef BINARY_WRITER_H_ #define BINARY_WRITER_H_ #include "Describer.h" #include "BinaryFstream.h" #include <stack> namespace nw { class BinaryWriter : public Describer{ public: BinaryWriter(const String filepath); virtual ~BinaryWriter(); void virtual close(); void readFromFile(const String filename); bool isInWriteMode(); bool push(const String tagName); void describeArray(const String arrayName, const String elementsName, unsigned int size); void describeValueArray(const String arrayName, unsigned int size); bool enterTag(const String childrenTagName); bool enterNextElement(unsigned int iterator); void autoEnterTags(bool doIt); /* Serialize functions */ void describeName(const String name); void describeValue(bool&); void describeValue(char&); void describeValue(unsigned char&); void describeValue(signed char&); void describeValue(short&); void describeValue(unsigned short&); void describeValue(int&); void describeValue(unsigned int&); void describeValue(long&); void describeValue(unsigned long&); void describeValue(float&); void describeValue(Pointer); void describeValue(double&); void describeValue(long long&); void describeValue(long double&); void describeValue(String&); void describeBlob(const String childName,nw::Pointer binaryBlob, unsigned int blobSize); void comment(const String text); String getParentName(); void pop(); private: BinaryFstream file; std::stack<unsigned int> arraySize; //helpers inline void registerPointer(DescribedObject*); inline void writeValidationSequence(); }; } // namespace nw #endif /* BINARY_WRITER_H_ */
Nehmulos/N0Strain-Serialization-Library
src/BinaryWriter.h
C
lgpl-3.0
2,853
/* * Copyright (C) 2003-2014 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.controller.home; import java.net.MalformedURLException; import java.net.URL; import org.exoplatform.R; import org.exoplatform.singleton.AccountSetting; import org.exoplatform.singleton.SocialServiceHelper; import org.exoplatform.social.client.api.ClientServiceFactory; import org.exoplatform.social.client.api.SocialClientContext; import org.exoplatform.social.client.api.SocialClientLibException; import org.exoplatform.social.client.api.model.RestActivity; import org.exoplatform.social.client.api.model.RestIdentity; import org.exoplatform.social.client.api.model.RestProfile; import org.exoplatform.social.client.api.model.RestSpace; import org.exoplatform.social.client.api.service.ActivityService; import org.exoplatform.social.client.api.service.IdentityService; import org.exoplatform.social.client.api.service.SpaceService; import org.exoplatform.social.client.api.service.VersionService; import org.exoplatform.social.client.core.ClientServiceFactoryHelper; import org.exoplatform.ui.HomeActivity; import org.exoplatform.utils.ExoConstants; import org.exoplatform.utils.Log; import org.exoplatform.utils.SettingUtils; import org.exoplatform.utils.SocialActivityUtil; import org.exoplatform.widget.WarningDialog; import android.content.Context; import android.content.res.Resources; import android.os.AsyncTask; import android.view.MenuItem; /** * Load and connect the app to the Social services and objects:<br/> * - Identity service <br/> * - Activity service <br/> * - User identity <br/> * - User profile <br/> * Initialize SocialServiceHelper with these objects. */ public class SocialServiceLoadTask extends AsyncTask<Void, Void, String[]> { private Context mContext; private ActivityService<RestActivity> mActivityService; private IdentityService<RestIdentity> mIdentityService; private SpaceService<RestSpace> mSpaceService; private String mUserIdentity; private String okString; private String titleString; private String contentString; private HomeController homeController; private MenuItem loaderItem; private static final String TAG = SocialServiceLoadTask.class.getName(); public SocialServiceLoadTask(Context context, HomeController controller, MenuItem loader) { mContext = context; homeController = controller; loaderItem = loader; changeLanguage(); } private void changeLanguage() { Resources resource = mContext.getResources(); okString = resource.getString(R.string.OK); titleString = resource.getString(R.string.Warning); contentString = resource.getString(R.string.LoadingDataError); } @Override public void onPreExecute() { if (loaderItem != null) loaderItem.setActionView(R.layout.action_bar_loading_indicator); } @SuppressWarnings({ "deprecation", "unchecked" }) @Override public String[] doInBackground(Void... params) { Log.i(TAG, "accessing social service"); try { String userName = AccountSetting.getInstance().getUsername(); String password = AccountSetting.getInstance().getPassword(); URL url = new URL(SocialActivityUtil.getDomain()); Log.i(TAG, "userName: " + userName); Log.i(TAG, "url: " + url.toString()); SocialClientContext.setProtocol(url.getProtocol()); SocialClientContext.setHost(url.getHost()); SocialClientContext.setPort(url.getPort()); SocialClientContext.setPortalContainerName(ExoConstants.ACTIVITY_PORTAL_CONTAINER); SocialClientContext.setRestContextName(ExoConstants.ACTIVITY_REST_CONTEXT); SocialClientContext.setUsername(userName); SocialClientContext.setPassword(password); ClientServiceFactory clientServiceFactory = ClientServiceFactoryHelper.getClientServiceFactory(); VersionService versionService = clientServiceFactory.createVersionService(); SocialClientContext.setRestVersion(versionService.getLatest()); clientServiceFactory = ClientServiceFactoryHelper.getClientServiceFactory(); mActivityService = clientServiceFactory.createActivityService(); mIdentityService = clientServiceFactory.createIdentityService(); mSpaceService = clientServiceFactory.createSpaceService(); mUserIdentity = mIdentityService.getIdentityId(ExoConstants.ACTIVITY_ORGANIZATION, userName); RestIdentity restIdent = mIdentityService.getIdentity(ExoConstants.ACTIVITY_ORGANIZATION, userName); RestProfile profile = restIdent.getProfile(); String[] profileArray = new String[2]; profileArray[0] = profile.getAvatarUrl(); profileArray[1] = profile.getFullName(); return profileArray; } catch (SocialClientLibException e) { Log.d(TAG, "SocialClientLibException: " + e.getLocalizedMessage()); return null; } catch (RuntimeException e) { Log.d(TAG, "RuntimeException: " + e.getLocalizedMessage()); return null; } catch (MalformedURLException e) { Log.d(TAG, "MalformedURLException: " + e.getLocalizedMessage()); return null; } } @Override protected void onCancelled(String[] result) { if (loaderItem != null) loaderItem.setActionView(null); onCancelled(); } @Override public void onPostExecute(String[] result) { if (result != null) { SocialServiceHelper.getInstance().userIdentity = mUserIdentity; SocialServiceHelper.getInstance().activityService = mActivityService; SocialServiceHelper.getInstance().identityService = mIdentityService; SocialServiceHelper.getInstance().spaceService = mSpaceService; SocialServiceHelper.getInstance().userProfile = result; if (HomeActivity.homeActivity != null) { HomeActivity.homeActivity.setProfileInfo(result); } if (AccountSetting.getInstance().shouldSaveProfileInfo(result[1], result[0])) { SettingUtils.persistServerSetting(mContext); } /** Load activities for view flipper */ homeController.onLoad(ExoConstants.NUMBER_OF_ACTIVITY_HOME, HomeController.FLIPPER_VIEW); } else { if (loaderItem != null) loaderItem.setActionView(null); WarningDialog dialog = new WarningDialog(mContext, titleString, contentString, okString); dialog.show(); } } }
exoplatform/mobile-android
app/src/main/java/org/exoplatform/controller/home/SocialServiceLoadTask.java
Java
lgpl-3.0
7,227
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_tangible_wearables_armor_stormtrooper_armor_stormtrooper_bicep_l = object_tangible_wearables_armor_stormtrooper_shared_armor_stormtrooper_bicep_l:new { templateType = ARMOROBJECT, faction = "Imperial", playerRaces = { "object/creature/player/bothan_male.iff", "object/creature/player/bothan_female.iff", "object/creature/player/human_male.iff", "object/creature/player/human_female.iff", "object/creature/player/moncal_male.iff", "object/creature/player/moncal_female.iff", "object/creature/player/rodian_male.iff", "object/creature/player/rodian_female.iff", "object/creature/player/sullustan_male.iff", "object/creature/player/sullustan_female.iff", "object/creature/player/trandoshan_male.iff", "object/creature/player/trandoshan_female.iff", "object/creature/player/twilek_male.iff", "object/creature/player/twilek_female.iff", "object/creature/player/zabrak_male.iff", "object/creature/player/zabrak_female.iff", "object/mobile/vendor/aqualish_female.iff", "object/mobile/vendor/aqualish_male.iff", "object/mobile/vendor/bith_female.iff", "object/mobile/vendor/bith_male.iff", "object/mobile/vendor/bothan_female.iff", "object/mobile/vendor/bothan_male.iff", "object/mobile/vendor/devaronian_male.iff", "object/mobile/vendor/gran_male.iff", "object/mobile/vendor/human_female.iff", "object/mobile/vendor/human_male.iff", "object/mobile/vendor/ishi_tib_male.iff", "object/mobile/vendor/moncal_female.iff", "object/mobile/vendor/moncal_male.iff", "object/mobile/vendor/nikto_male.iff", "object/mobile/vendor/quarren_male.iff", "object/mobile/vendor/rodian_female.iff", "object/mobile/vendor/rodian_male.iff", "object/mobile/vendor/sullustan_female.iff", "object/mobile/vendor/sullustan_male.iff", "object/mobile/vendor/trandoshan_female.iff", "object/mobile/vendor/trandoshan_male.iff", "object/mobile/vendor/twilek_female.iff", "object/mobile/vendor/twilek_male.iff", "object/mobile/vendor/weequay_male.iff", "object/mobile/vendor/zabrak_female.iff", "object/mobile/vendor/zabrak_male.iff" }, -- Damage types in WeaponObject vulnerability = ACID + STUN + LIGHTSABER, -- These are default Blue Frog stats healthEncumbrance = 15, actionEncumbrance = 16, mindEncumbrance = 19, -- LIGHT, MEDIUM, HEAVY rating = LIGHT, maxCondition = 45000, kinetic = 30, energy = 30, electricity = 30, stun = 0, blast = 30, heat = 30, cold = 30, acid = 0, lightSaber = 0 } ObjectTemplates:addTemplate(object_tangible_wearables_armor_stormtrooper_armor_stormtrooper_bicep_l, "object/tangible/wearables/armor/stormtrooper/armor_stormtrooper_bicep_l.iff")
kidaa/Awakening-Core3
bin/scripts/object/tangible/wearables/armor/stormtrooper/armor_stormtrooper_bicep_l.lua
Lua
lgpl-3.0
4,740
# SIMF Semantic Information Modeling for Federation Specification Working Repository For latest see "DraftSMIFSpecification" Note that the by consensus of the submitters, SIMF was renamed "Semantic Modeling for Information Federation" (SMIF)
ModelDriven/SIMF
README.md
Markdown
lgpl-3.0
243
var dir_1dfe7b4d98f7fbcbf3888d2e6eb0ed23 = [ [ "eventBus.hpp", "event_bus_8hpp_source.html", null ], [ "eventHandler.hpp", "event_handler_8hpp_source.html", null ], [ "observable.hpp", "observable_8hpp_source.html", null ], [ "observer.hpp", "observer_8hpp_source.html", null ] ];
vlachenal/anch-framework
docs/dir_1dfe7b4d98f7fbcbf3888d2e6eb0ed23.js
JavaScript
lgpl-3.0
296
# created based on # https://python-packaging.readthedocs.io/en/latest/minimal.html # But instead of python setup.py register sdist upload, # use https://pypi.org/p/twine/ # from setuptools import setup import sys import os import re sys.path.append("src") def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except IOError: return "File '%s' not found.\n" % fname def readVersion(): txt = read("src/moddy/version.py") ver = re.findall(r"([0-9]+)", txt) print("ver=%s" % ver) return ver[0] + "." + ver[1] + "." + ver[2] setup( name="moddy", install_requires=["svgwrite"], version=readVersion(), description="A discrete event simulator generating sequence diagrams", long_description=read("README.rst"), url="https://github.com/KlausPopp/Moddy", project_urls={ "Documentation": "https://klauspopp.github.io/Moddy/", "Source Code": "https://github.com/KlausPopp/Moddy/", }, keywords="simulation modelling", author="Klaus Popp", author_email="klauspopp@gmx.de", license="LGPL-3.0", platforms="OS Independent", package_dir={"": "src"}, packages=[ "moddy", "moddy.seq_diag_interactive_viewer", "moddy.lib", "moddy.lib.net", ], package_data={"moddy.seq_diag_interactive_viewer": ["*.css", "*.js"]}, )
KlausPopp/Moddy
setup.py
Python
lgpl-3.0
1,397
/************************************************************ ** ** file: btreeprimitivedefinitions.h ** author: Andreas Steffens ** license: LGPL v3 ** ** description: ** ** This file contains definitions for the b-tree framework ** test bench's common primitives. ** ************************************************************/ #ifndef BTREEPRIMITIVEDEFINITIONS_H #define BTREEPRIMITIVEDEFINITIONS_H typedef enum { BTREETEST_KEY_GENERATION_DESCEND, BTREETEST_KEY_GENERATION_ASCEND, BTREETEST_KEY_GENERATION_RANDOM, BTREETEST_KEY_GENERATION_CONST } btreetest_key_generation_e; #endif // BTREEPRIMITIVEDEFINITIONS_H
andreas-steffens/btree-framework-demonstration
src/btreetest/testbench/primitives/btreeprimitivedefinitions.h
C
lgpl-3.0
627
#include <string> #include <cmath> #include <math.h> #include <random> #include <ctime> using namespace std; /* class Pole { public: int razmer; Pole(int razmer); ~ */ int ** CreateFullMassive(int razmer) { int count = 1; int ** mas = new int*[razmer]; for(int i=0; i<razmer; i++) { mas[i] = new int[razmer]; } for(int i=0; i<razmer; i++) for(int j=0; j<razmer; j++) { mas[i][j] = count++; } mas[razmer-1][razmer-1] = 0; return mas; } int ** PeremeshatMassive(int ** massive, int razmer) { int i; int j; for(int g=0; g<2; g++) { //******************************************* //×åòûðå ðàçà íà÷àòü ñ êàæäîãî èç óãëîâ if(g==0) { i = razmer - 1; j = razmer - 1; } else if(g==1) { //Ãîíþ ïóñòîé êâàäðàò â ëåâûé âåðõíèé óãîë while(1) { if(i!=0) { massive[i][j] = massive[i-1][j]; massive[i-1][j]=0; i--; } if(j!=0) { massive[i][j] = massive[i][j-1]; massive[i][j-1]=0; j--; } if(i==0 & j==0) break; } } //************************************ for(int k=0; k<pow((double)5, (double)razmer); k++) { //********************************************* //Âû÷èñëåíèå ðàíäîìíîãî ÷èñëà r ñ ó÷åòîì ðåàëüíîãî âðåìåíè â ñåêóíäàõ äèàïàçîí 1-100 int r = rand() % 100 +1; time_t myTimer; myTimer = time(NULL); myTimer-=1494850400; r+=myTimer*10; while(r>100) r-=100; //********************************************* //Ïðîâåðêè íà íàõîæåíèå if(i == 0 && j == 0)//óãîë ëåâî âåðõ { if(r>50) { massive[i][j] = massive[i+1][j]; massive[i+1][j]=0; i++; } else { massive[i][j] = massive[i][j+1]; massive[i][j+1]=0; j++; } } else if(i == 0 && j == razmer-1)//óãîë âåðõ ïðàâî { if(r>50) { massive[i][j] = massive[i+1][j]; massive[i+1][j]=0; i++; } else { massive[i][j] = massive[i][j-1]; massive[i][j-1]=0; j--; } } else if(i == razmer-1 && j == 0)//óãîë ëåâî íèç { if(r>50) { massive[i][j] = massive[i-1][j]; massive[i-1][j]=0; i--; } else { massive[i][j] = massive[i][j+1]; massive[i][j+1]=0; j++; } } else if(i == razmer-1 && j == razmer-1)//óãîë ïðàâî íèç { if(r>50) { massive[i][j] = massive[i-1][j]; massive[i-1][j]=0; i--; } else { massive[i][j] = massive[i][j-1]; massive[i][j-1]=0; j--; } } //ñòîðîíû else if(i == 0)//ñòîðîíà ëåâî { if(r>33) { massive[i][j] = massive[i+1][j]; massive[i+1][j]=0; i++; } else if(r>66) { massive[i][j] = massive[i][j-1]; massive[i][j-1]=0; j--; } else { massive[i][j] = massive[i][j+1]; massive[i][j+1]=0; j++; } } else if(j == 0)//ñòîðîíà âåðõ { if(r>33) { massive[i][j] = massive[i+1][j]; massive[i+1][j]=0; i++; } else if(r>66) { massive[i][j] = massive[i-1][j]; massive[i-1][j]=0; i--; } else { massive[i][j] = massive[i][j+1]; massive[i][j+1]=0; j++; } } else if(i == razmer-1)//ñòîðîíà íèç { if(r>33) { massive[i][j] = massive[i][j-1]; massive[i][j-1]=0; j--; } else if(r>66) { massive[i][j] = massive[i-1][j]; massive[i-1][j]=0; i--; } else { massive[i][j] = massive[i][j+1]; massive[i][j+1]=0; j++; } } else if(j == razmer-1)//ñòîðîíà ïðàâî { if(r>33) { massive[i][j] = massive[i][j-1]; massive[i][j-1]=0; j--; } else if(r>66) { massive[i][j] = massive[i+1][j]; massive[i+1][j]=0; i++; } else { massive[i][j] = massive[i-1][j]; massive[i-1][j]=0; i--; } } else//öåíòð { if(r>25) { massive[i][j] = massive[i][j-1]; massive[i][j-1]=0; j--; } else if(r>50) { massive[i][j] = massive[i-1][j]; massive[i-1][j]=0; i--; } else if(r>75) { massive[i][j] = massive[i][j+1]; massive[i][j+1]=0; j++; } else { massive[i][j] = massive[i+1][j]; massive[i+1][j]=0; i++; } } } } return massive; } void DeleteMassive(int ** massive, int razmer) { for(int i=0; i<razmer; i++) delete []massive[i]; } bool SwapQuadro(int ** massive, int razmer, int x, int y) { //****Ïîèñê ïóñòîé ÿ÷åéêè****** int g, l; for(int i=0; i<razmer;i++) for(int j=0; j<razmer; j++) if(massive[i][j] == 0) { g=i; l=j; } //*********************** //****Ïðîâåðêà íà ñîñåäñòâî íóëÿ ñ íàéäåíîé(íàæàòîé) ÿ÷åéêîé if((g+1==x & l==y) || (g-1==x & l==y) || (l-1 == y & g==x) || (l+1==y & g==x)) return true; else return false; //*********************** } bool Win_niPuh(int ** massive, int razmer) { if(massive[razmer-1][razmer-1] == 0) { int val=1; for(int i=0; i<razmer; i++) for(int j=0; j<razmer;j++) { if(massive[i][j]==0) { return true; } else if(massive[i][j]!=val) return false; val++; } } else { return false; } }
Shifter1602/6sem
Cpp (patterns)/CourseWork(15)(COMMAND)/MFC/Pytnashki Shablon (Decorator + Command)/Pytnashki Shablon/MassiveForPyatnashki.h
C
lgpl-3.0
5,177
package com.advancedtunnelbore.lib; public class RefStrings { public static final String MODID = "advancedtunnelbore"; public static final String NAME = "Advanced Tunnel Boring"; public static final String VERSION = "0.0.1"; public static final String CLIENTSIDE = "com.advancedtunnelbore.main.ClientProxy"; public static final String SERVERSIDE = "com.advancedtunnelbore.main.ServerProxy"; }
hihellobyeoh/Advanced-Tunnelboring
src/main/java/com/advancedtunnelbore/lib/RefStrings.java
Java
lgpl-3.0
400
/** * Created on Dec 09, 2015 * @author Lijing Wang OoOfreedom@gmail.com */ #pragma once #include "internal_types.hpp" #include <ndn-cxx/face.hpp> #include <ndn-cxx/security/key-chain.hpp> #include <ndn-cxx/util/scheduler.hpp> #include <boost/thread.hpp> #include <boost/bind.hpp> #include <boost/thread/mutex.hpp> #include <fstream> #include <unistd.h> #include <string> #include <stdlib.h> #include <chrono> namespace ndnpaxos { class Client { public: Client(ndn::Name prefix, int commit_win, int ratio = 100); ~Client(); void attach(); void stop(); void start_commit(); void consume(ndn::Name &); private: void onTimeout(const ndn::Interest& interest); void onData(const ndn::Interest& interest, const ndn::Data& data); ndn::shared_ptr<ndn::Face> face_; ndn::Name prefix_; int com_win_; int ratio_; int write_or_read_; slot_id_t commit_counter_; slot_id_t thr_counter_; slot_id_t rand_counter_; boost::mutex counter_mut_; boost::mutex thr_mut_; std::vector<uint64_t> periods_; std::vector<uint64_t> throughputs_; std::vector<int> trytimes_; std::vector<std::chrono::high_resolution_clock::time_point> starts_; bool recording_; bool done_; }; } // namespace ndnpaxos
PhdLoLi/NDNPaxos
libndnpaxos/client.hpp
C++
lgpl-3.0
1,245
/* * Copyright (C) 2005-2011 Alfresco Software Limited. * * This file is part of Alfresco * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alfresco is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Alfresco. If not, see <http://www.gnu.org/licenses/>. */ package org.alfresco.repo.jscript; import org.alfresco.repo.jscript.app.CustomResponse; import org.json.JSONException; import org.json.JSONObject; import java.io.Serializable; import java.util.Map; /** * Populates DocLib webscript response with custom metadata output * * @author: mikeh */ public final class SlingshotDocLibCustomResponse extends BaseScopableProcessorExtension { private Map<String, Object> customResponses; /** * Set the custom response beans * * @param customResponses */ public void setCustomResponses(Map<String, Object> customResponses) { this.customResponses = customResponses; } /** * Returns a JSON string to be added to the DocLib webscript response. * * @return The JSON string */ public String getJSON() { return this.getJSONObj().toString(); } /** * Returns a JSON object to be added to the DocLib webscript response. * * @return The JSON object */ protected Object getJSONObj() { JSONObject json = new JSONObject(); for (Map.Entry<String, Object> entry : this.customResponses.entrySet()) { try { Serializable response = ((CustomResponse) entry.getValue()).populate(); json.put(entry.getKey(), response == null ? JSONObject.NULL: response); } catch (JSONException error) { error.printStackTrace(); } } return json; } }
loftuxab/community-edition-old
projects/repository/source/java/org/alfresco/repo/jscript/SlingshotDocLibCustomResponse.java
Java
lgpl-3.0
2,303
/* * Created on 19-sept.-2003 */ package org.javlo.component.core; import org.javlo.context.ContentContext; /** * @author pvandermaesen */ public class Unknown extends AbstractVisualComponent { public static final IContentVisualComponent INSTANCE = new Unknown(); public static final String TYPE = "unknow"; public Unknown() { } public Unknown(ContentContext newCtx, ComponentBean bean) throws Exception { init(bean, newCtx); } @Override protected String getEditXHTMLCode(ContentContext ctx) throws Exception { StringBuffer finalCode = new StringBuffer(); finalCode.append(getSpecialInputTag()); finalCode.append("<br />"); finalCode.append("<b>&nbsp;not found : " + getComponentBean().getType() + "</b>"); finalCode.append("<br /><br />"); finalCode.append("<textarea id=\"" + getContentName() + "\" name=\"" + getContentName() + "\""); finalCode.append(" rows=\"" + (countLine() + 1) + "\" onkeyup=\"javascript:resizeTextArea($('" + getContentName() + "'));\">"); finalCode.append(getValue()); finalCode.append("</textarea>"); return finalCode.toString(); } @Override public String getViewXHTMLCode(ContentContext ctx) throws Exception { if (ctx.isAsViewMode()) { return ""; } else { return "<b>unknow component : " + getComponentBean().getType() + "</b>"; } } @Override public String getXHTMLConfig(ContentContext ctx) throws Exception { return "?"; } @Override public String getPrefixViewXHTMLCode(ContentContext ctx) { return ""; } @Override public String getSuffixViewXHTMLCode(ContentContext ctx) { return ""; } /* * @see org.javlo.itf.IContentVisualComponent#getType() */ @Override public String getType() { return TYPE; } }
Javlo/javlo
src/main/java/org/javlo/component/core/Unknown.java
Java
lgpl-3.0
1,725
/** * Copyright © 2002 Instituto Superior Técnico * * This file is part of FenixEdu Academic. * * FenixEdu Academic is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FenixEdu Academic is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>. */ package org.fenixedu.academic.domain.studentCurriculum; import static org.fenixedu.academic.domain.studentCurriculum.StudentCurricularPlanEnrolmentPreConditions.EnrolmentPreConditionResult.createFalse; import static org.fenixedu.academic.domain.studentCurriculum.StudentCurricularPlanEnrolmentPreConditions.EnrolmentPreConditionResult.createTrue; import org.fenixedu.academic.domain.EnrolmentPeriod; import org.fenixedu.academic.domain.ExecutionSemester; import org.fenixedu.academic.domain.ExecutionYear; import org.fenixedu.academic.domain.StudentCurricularPlan; import org.fenixedu.academic.domain.accounting.EnrolmentBlocker; import org.fenixedu.academic.domain.student.Registration; import org.fenixedu.academic.domain.student.registrationStates.RegistrationState; import org.fenixedu.academic.domain.student.registrationStates.RegistrationStateType; public class StudentCurricularPlanEnrolmentPreConditions { static public class EnrolmentPreConditionResult { private boolean valid = false; private String message; private String[] args; private EnrolmentPeriod period; private EnrolmentPreConditionResult valid(final boolean value) { this.valid = value; return this; } public boolean isValid() { return valid; } private EnrolmentPreConditionResult message(final String message, final String... args) { this.message = message; this.args = args; return this; } private EnrolmentPreConditionResult withPeriod(EnrolmentPeriod period) { this.period = period; return this; } public String message() { return this.message; } public String[] args() { return this.args; } public EnrolmentPeriod getEnrolmentPeriod() { return period; } static public EnrolmentPreConditionResult createTrue() { return new EnrolmentPreConditionResult().valid(true); } static public EnrolmentPreConditionResult createFalse(final String message, final String... args) { return new EnrolmentPreConditionResult().valid(false).message(message, args); } } /* * Change? If next period is not defined then we should use last? Or previous of given semester? */ static private EnrolmentPreConditionResult outOfPeriodResult(final String periodType, final EnrolmentPeriod nextPeriod) { if (nextPeriod != null) { return createFalse("message.out.curricular.course.enrolment.period." + periodType, nextPeriod.getStartDateDateTime().toString("dd/MM/yyyy"), nextPeriod.getEndDateDateTime().toString("dd/MM/yyyy")).withPeriod(nextPeriod); } else { return createFalse("message.out.curricular.course.enrolment.period." + periodType + ".noDates"); } } static public EnrolmentPreConditionResult checkPreConditionsToEnrol(StudentCurricularPlan scp, ExecutionSemester semester) { final EnrolmentPreConditionResult result = checkEnrolmentPeriods(scp, semester); if (!result.isValid()) { return result; } return checkDebts(scp); } /** * * Check if student has any debts that prevent him to enrol in curricular * courses * * @param scp * @return EnrolmentPreConditionResult */ static EnrolmentPreConditionResult checkDebts(StudentCurricularPlan scp) { if (EnrolmentBlocker.enrolmentBlocker.isAnyGratuityOrAdministrativeOfficeFeeAndInsuranceInDebt(scp, ExecutionYear.readCurrentExecutionYear())) { return createFalse("error.StudentCurricularPlan.cannot.enrol.with.debts.for.previous.execution.years"); } if (scp.getPerson().hasAnyResidencePaymentsInDebtForPreviousYear()) { return createFalse("error.StudentCurricularPlan.cannot.enrol.with.residence.debts"); } return createTrue(); } static private boolean hasSpecialSeason(final StudentCurricularPlan scp, final ExecutionSemester semester) { if (scp.hasSpecialSeasonFor(semester)) { return true; } final Registration registration = scp.getRegistration(); return registration.getSourceRegistration() != null && registration.getSourceRegistration().getLastStudentCurricularPlan().hasSpecialSeasonFor(semester); } /** * Check student enrolment periods * * @param scp * @param semester * @return EnrolmentPreConditionResult */ static EnrolmentPreConditionResult checkEnrolmentPeriods(StudentCurricularPlan scp, ExecutionSemester semester) { if (semester.isFirstOfYear() && hasSpecialSeason(scp, semester)) { if (!scp.getDegreeCurricularPlan().getActiveEnrolmentPeriodInCurricularCoursesSpecialSeason(semester).isPresent()) { return outOfPeriodResult("specialSeason", scp.getDegreeCurricularPlan() .getNextEnrolmentPeriodInCurricularCoursesSpecialSeason()); } } else if (semester.isFirstOfYear() && hasPrescribed(scp, semester)) { if (!scp.getDegreeCurricularPlan().getActiveEnrolmentPeriodInCurricularCoursesFlunkedSeason(semester).isPresent()) { return outOfPeriodResult("flunked", scp.getDegreeCurricularPlan() .getNextEnrolmentPeriodInCurricularCoursesFlunkedSeason()); } } else if (!scp.getDegreeCurricularPlan().getActiveCurricularCourseEnrolmentPeriod(semester).isPresent()) { return outOfPeriodResult("normal", scp.getDegreeCurricularPlan().getNextEnrolmentPeriod()); } return createTrue(); } static EnrolmentPreConditionResult checkEnrolmentPeriodsForSpecialSeason(StudentCurricularPlan scp, ExecutionSemester semester) { if (!scp.getDegreeCurricularPlan().hasOpenSpecialSeasonEnrolmentPeriod(semester)) { return outOfPeriodResult("specialSeason", scp.getDegreeCurricularPlan() .getNextEnrolmentPeriodInCurricularCoursesSpecialSeason()); } return createTrue(); } /* * Student must have flunked state and then registered (in same year), otherwise is not considered to be prescribed */ private static boolean hasPrescribed(StudentCurricularPlan scp, ExecutionSemester semester) { for (RegistrationState state : scp.getRegistration().getRegistrationStates(semester.getExecutionYear())) { if (state.getExecutionYear().equals(semester.getExecutionYear()) && RegistrationStateType.FLUNKED.equals(state.getStateType())) { return scp.getRegistration().hasRegisteredActiveState(); } } return false; } }
sergiofbsilva/fenixedu-academic
src/main/java/org/fenixedu/academic/domain/studentCurriculum/StudentCurricularPlanEnrolmentPreConditions.java
Java
lgpl-3.0
7,697
import {Component, View, Inject} from 'app/app'; import 'components/contextselector/context-selector'; import {SELECTION_MODE_BOTH, SELECTION_MODE_IN_CONTEXT, SELECTION_MODE_WITHOUT_CONTEXT} from 'components/contextselector/context-selector'; import contextSelectorStubTemplate from 'context-selector.stub.html!text'; @Component({ selector: 'seip-context-selector-stub' }) @View({ template: contextSelectorStubTemplate }) @Inject() export class ContextSelectorStub { constructor() { this.config = { parentId: 'test_id' }; this.config.both = { parentId: 'test_id', contextSelectorSelectionMode: SELECTION_MODE_BOTH }; this.config.selectionModeInContext = { parentId: 'test_id', contextSelectorSelectionMode: SELECTION_MODE_IN_CONTEXT }; this.config.selectionModeWithoutContext = { parentId: 'test_id', contextSelectorSelectionMode: SELECTION_MODE_WITHOUT_CONTEXT }; } }
SirmaITT/conservation-space-1.7.0
docker/sep-ui/sandbox/components/contextselector/context-selector.stub.js
JavaScript
lgpl-3.0
957
// UGTrackingLayer.h: interface for the UGTrackingLayer class. // ////////////////////////////////////////////////////////////////////// /*! ************************************************************************************** \file UGTrackingLayer.h ************************************************************************************** \author ³Â¹úÐÛ \brief ¸ú×Ùͼ²ãÀ࣬ÊÇÒ»¸öÄÚ´æÍ¼²ã£¬×ÜÊÇÔÚÆäËûͼ²ãµÄ×îÉÏÃæ£¬ÓÃÓÚÁÙʱ¶ÔÏóµÄÏÔʾ¡£ \attention ----------------------------------------------------------------------------------<br> Copyright (c) 2000-2010 SuperMap Software Co., Ltd. <br> All Rights Reserved. <br> ----------------------------------------------------------------------------------<br> ************************************************************************************** \version 2005-05-20 ³Â¹úÐÛ ³õʼ»¯°æ±¾. <br> ************************************************************************************** */ #if !defined(AFX_UGTRACKINGLAYER_H__DC6194D6_CDEC_4A74_8522_AC23C8C202F5__INCLUDED_) #define AFX_UGTRACKINGLAYER_H__DC6194D6_CDEC_4A74_8522_AC23C8C202F5__INCLUDED_ #include "Map/UGGeoEvent.h" #include "Stream/ugdefs.h" #include "Drawing/UGDrawing.h" namespace UGC { //! \brief BeforeTrackingLayerDraw ʼþ»Øµ÷º¯Êý typedef void (UGSTDCALL *BeforeTrackingLayerDrawProc)(UGlong pWnd,UGbool& bCancel,UGGraphics* pGraphics); //! \brief AfterTrackingLayerDraw ʼþ»Øµ÷º¯Êý typedef void (UGSTDCALL *AfterTrackingLayerDrawProc)(UGlong pWnd,UGGraphics* pGraphics); class MAP_API UGTrackingLayer { public: UGTrackingLayer(); #ifdef SYMBIAN60 ~UGTrackingLayer(); #else virtual ~UGTrackingLayer(); #endif public: //! \brief µã»÷ʼþ UGint HitTest(const UGPoint2D& pntHitTest, UGdouble dTolerance); //! \brief ÊÇ·ñ¿É¼û UGbool IsVisible()const; //! \brief ÉèÖÃÊÇ·ñ¿É¼û void SetVisible(UGbool bVisible = true); //! \brief ÊÇ·ñ¿ÉÑ¡Ôñ UGbool IsSelectable()const; //! \brief ÉèÖÃÊÇ·ñ¿ÉÑ¡Ôñ void SetSelectable(UGbool bSelectable = false); //! \brief ÊÇ·ñ¿É±à¼­ UGbool IsEditable()const; //! \brief ÉèÖÃÊÇ·ñ¿É±à¼­ void SetEditable(UGbool bEditable = false); //! \brief ÊÇ·ñ¿É²¶×½ UGbool IsSnapable()const; //! \brief ÉèÖÃÊÇ·ñ¿É²¶×½ void SetSnapable(UGbool bSnapable = false); //! \brief ÊÇ·ñ·ûºÅËæ×Åͼ²ãµÄËõ·Å¶øËõ·Å UGbool IsSymbolScalable()const; //! \brief ÉèÖ÷ûºÅÊÇ·ñ¿ÉËõ·Å void SetSymbolScalable(UGbool bSymbolScalable = false); //! \brief ÊÇ·ñÉèÖÃÎı¾µþ¸Ç UGbool IsAllowTextOverlap()const; //! \brief ÉèÖÃÎı¾µþ¸Ç void SetAllowTextOverlap(UGbool bAllowTextOverlap = true); //! \brief ²éÕÒ¶ÔÓ¦±êÇ©µÄ¸ú×Ù²ã¶ÔÏó /** \return ¶ÔÓ¦±êÇ©µÄË÷Òý */ UGint Find(const UGString &strTag, UGint nFromIndex = 0) const; //! \brief ²éÕÒ¶ÔÓ¦¼¸ºÎ¶ÔÏóµÄ¸ú×Ù²ã¶ÔÏó /** \return ¶ÔÓ¦¼¸ºÎ¶ÔÏóµÄË÷Òý */ UGint Find(const UGGeometry* pGeometry, UGint nFromIndex = 0); //! \brief ÒÆ³ýÖ¸¶¨±êÇ©µÄ¶ÔÏó UGbool Remove(const UGString &strTag, UGint nFromIndex = 0); //! \brief ÒÆ³ýÖ¸¶¨Ë÷ÒýµÄ¶ÔÏó UGint RemoveAt(UGint nIndex, UGint nCount = 1); //! \brief Ôö¼Ó¼¸ºÎ¶ÔÏ󵽸ú×Ù²ã UGGeoEvent* Add(const UGGeometry* pGeometry, const UGString &strTag); //! \brief µÃµ½Ö¸¶¨Ë÷ÒýµÄ¸ú×Ù²ã¶ÔÏó UGGeoEvent* GetAt(UGint nIndex) const; //! \brief ÒÆ³ý¸ú×Ù²ãËùÓжÔÏó void RemoveAll(); //! \brief ÒÆ³ý¸ú×Ù²ãËùÓжÔÏó void RemoveAllEx(); //! \brief »ñÈ¡¶ÔÏó¸öÊý UGint GetCount()const; //! \brief ÉèÖÃÖ¸¶¨Ë÷Òý¶ÔÏóµÄ±êÇ© void SetTagAt(UGint nIndex, const UGString &strTag); //add by xiaoys 2012-07-10 ¸Ã½Ó¿ÚÖ÷ÒªÊÇÓÃÀ´ÔÚjni²ã·â×°»ñÈ¡×Ö¶ÎÐÅÏ¢½Ó¿Ú UGDataset* GetDataset(); //! \brief »æÖƸú×Ù²ã #ifdef SYMBIAN60 UGbool OnDraw(UGGraphics* pGraphics, UGDrawing *pDrawing); #else virtual UGbool OnDraw(UGGraphics* pGraphics, UGDrawing *pDrawing); #endif //! \brief ÉèÖÃÖ¸¶¨µÄ×Ö·û±àÂë void SetCharset(UGString::Charset nCharset); //! \brief µÃµ½Ö¸¶¨µÄ×Ö·û±àÂë UGString::Charset GetCharset()const; //! \brief µÃµ½×î´ó·ûºÅ´óС UGdouble GetMaxMarkerSize() const; //! \brief µÃµ½ÓÐÐ§ÇøÓò UGRect2D GetInvalidRect() const; //! \brief ÉèÖÃÓÐÐ§ÇøÓò void SetInvalidRect(const UGRect2D& rcInvalid); UGdouble GetSymScaleDefinition() const; void SetSymScaleDefinition(UGdouble dSymScaleDefinition); UGdouble CalculateSymbolScale(UGdouble dScale) const; void SetDrawing(UGDrawing* pDrawing); //! \brief »ñÈ¡Ìî³äÔ­µãµÄģʽ UGint GetFillOrgMode() const; //! \brief ÉèÖÃÌî³äÔ­µãģʽ void SetFillOrgMode(UGGraphics::BrushOrgMode nFillOrgMode); UGbool BuildSpatialIndex(UGSpatialIndexInfo &spatial); //! \brief ¿ªÊ¼ÊÂÎñ UGbool BeginTrans() ; //! \brief Ìá½»ÊÂÎñ void Commit() ; //! \brief ³·ÏûÊÂÎñ void Rollback(); //! \brief ÅжÏÊÂÎñÊÇ·ñ¿ªÊ¼ UGbool IsTransStarted() ; //! \brief ÉèÖÃÅúÁ¿¸üбêÖ¾ //! \param bIsEditBulkOperate [in] TRUEΪ¿ªÊ¼ÅúÁ¿¸üУ¬FALSEΪȡÏûÅúÁ¿¸üбêÖ¾ UGbool EditBulk(UGbool bIsEditBulkOperate); //! \brief ÅúÁ¿¸üÐÂʱ,Ç¿ÖÆË¢ÐÂ,½«±¾´ÎÅúÁ¿±à¼­µÄÊý¾Ý±£´æ //! \return ÊÇ·ñˢгɹ¦ UGbool FlushBulkEdit(); //! \brief È¡Ïû±¾´ÎÅúÁ¿¸üеÄÄÚÈÝ£¬´ÓÉÏ´ÎÌá½»µãÖÁ´Ë ±à¼­µÄÄÚÈÝÎÞЧ£¬µ«¿ÉÒÔ¼ÌÐø¿ªÊ¼½øÐÐÅúÁ¿±à¼­ UGbool CancleBulkOperated(); //added by xielin 2007-10-17 ÓÃÓÚÓÅ»¯¸ú×Ù²ãµÄÏÔʾËÙ¶È //! \brief ÏÔʾµÄʱºòÊÇ·ñ°´ÕÕ¶ÔÏóÀàÐÍÅÅÐòÏÔʾ£¬Ä¬Èϰ´ÕÕ¶ÔÏóÀàÐÍÅÅÐòÏÔʾ¡£ÕâÑù¶Ô´ó²¿·ÖµÄ¸ú×ÙÓ¦Óã¨Ò»¸ö¸ú×ÙµãÒ»¸ö±ê×¢£¬×¢ÒⲻҪ۳ɏ´ºÏ¶ÔÏ󣩣¬ÄÜÌá¸ß»æÖÆËÙ¶È void SetOrderByGeometryType(UGbool bOrderByGeometryType=true); //! \brief ·µ»ØÊÇ·ñ°´ÕÕ¶ÔÏóÀàÐÍÅÅÐòÏÔʾ UGbool IsOrderByGeometryType(); //! \brief ÊÇ·ñΪÏ߹⻬ģʽ UGbool IsLineSmoothingMode()const; //! \brief ÉèÖÃÏ߹⻬ģʽ void SetLineSmoothingMode(UGbool bSmoothingMode = true); //! \brief ÊÇ·ñΪÎı¾¹â»¬Ä£Ê½ UGbool IsTextSmoothingMode()const; //! \brief ÉèÖÃÎı¾¹â»¬Ä£Ê½ void SetTextSmoothingMode(UGbool bSmoothingMode = true); //! \brief ÊÇ·ñΪÉ豸ͼ²ã UGbool IsDeviceLayer(); //! \brief ±£´æÍ¼²ãÊý¾Ý /** \param strFileName ±£´æÂ·¾¶[in] \param bOverWrite ÊÇ·ñÇ¿ÖÆ¸²¸Ç[in] \return ±£´æÊÇ·ñ³É¹¦ */ //UGbool SaveAs(const UGString& strFileName ,UGbool bOverWrite = false)const; //! \brief ´ò¿ªÍ¼²ãÊý¾Ý /** \param strFileName ´ò¿ªÂ·¾¶[in] \return ´ò¿ªÊÇ·ñ³É¹¦ */ UGbool Open(const UGString& strFileName,UGbool bAsMemoryMode = false); //! \brief Çå¿Õͼ²ã void Clear(); //! \brief ¶Áȡͼ²ãµÄXMLÐÅÏ¢ UGbool FromXML(const UGString& strXML,const UGString& strWorkspacePath,const UGString& strMapName,UGint nVersion = 0); //! \brief ±£´æÍ¼²ãΪXML UGString ToXML(const UGString& strWorkspacePath,const UGString& strMapName,UGint nVersion = 0)const; //! \brief ÉèÖøú×Ù²ãͼ²ãµÄ͸Ã÷¶È /* \param nTransPercent ͸Ã÷¶È[in] */ void SetTransPercent(UGuint nTransPercent); //! \brief »ñȡͼ²ãµÄ͸Ã÷¶È UGuint GetTransPercent(); void SetBeforeTrackingLayerDrawFunc(BeforeTrackingLayerDrawProc pBeforeTrackingLayerDrawFunc,UGlong pWnd); void SetAfterTrackingLayerDrawFunc(AfterTrackingLayerDrawProc pAfterTrackingLayerDrawFunc,UGlong pWnd); void SendBeforeTrackingLayerDrawFunc(UGbool& bCancel,UGGraphics* pGraphics); void SendAfterTrackingLayerDrawFunc(UGGraphics* pGraphics); private: //modified by lugw 2007-05-11 ´Ëº¯Êý¸ÄΪ˽ÓУ¬ÍⲿÔݲ»Ê¹Óà void SetGeometryAt(UGint nIndex, const UGGeometry* pGeometry); //! \brief ´´½¨ÄÚ´æÊý¾ÝÔ´,Èç¹û³ÉÔ±Êý¾ÝÔ´²»Îª¿Õ£¬·µ»Øtrue£¬Îª¿Õ·µ»Øfalse UGbool CreateMemoryDs(); //! \brief »ñÈ¡É豸ͼ²ã´æ´¢Â·¾¶ UGString GetFileName(const UGString& strWorkspacePath,const UGString& strMapName)const; UGRecordset* GetRecordset(); //{{ add by xiaoys 2012-07-03 Ϊ×ÓÀàTrackingLayerEx¿ª·ÅһЩÐ麯Êý public: UGbool IsTrackingLayerEx(); //! \brief ͨ¹ý¸ú×Ù²ã¶ÔÏó±êÇ©»ñÈ¡¶ÔÏó virtual UGGeoEvent* GetEvent(const UGString& strTag); //! \brief ͨ¹ý¸ú×Ù²ã¶ÔÏó×ֶκÍÖµ»ñÈ¡¼Ç¼ÐòºÅ virtual UGint Query(UGArray<UGint>& arIDs, const UGString& strFieldName, const UGString& strVar); //! \brief ÉèÖ÷ûºÅ¿É¼û virtual void SetSymbolVisible(UGbool bVisible); //! \brief ÉèÖ÷ûºÅÉÁ˸ virtual void SetSymbolTwinkling(UGchar cTwinkling); //! \brief ÉèÖ÷ûºÅ¶ÔÆë·½Ê½ virtual void SetSymbolAlign(UGchar cAlign); //! \brief ÉèÖ÷ûºÅÆ«ÒÆ virtual void SetSymbolOffset(UGshort sX, UGshort sY); //! \brief Ïò¸ú×Ù²ãÌí¼Ó¶ÔÏóµÄÊôÐÔ±êÇ©£»---------------- virtual UGbool AddLabel(const UGString& strField, const UGTextStyle& LabelStyle,UGbool bVisible = true, UGbool bAddToTail = true); //! \brief ÔÚ¸ú×Ù²ãÒÆ³ýרÌâͼ£»------------------------ virtual UGbool RemoveLabel(const UGString& strField); //! \brief ÉèÖñêÇ©Æ«ÒÆ virtual UGbool SetLabelOffset(const UGString& strTag, UGshort usX, UGshort usY); //! \brief ÉèÖñêǩ˵Ã÷ virtual UGbool SetLabelCaption(const UGString& strTag, const UGString& strCaption); //! \brief ÉèÖñêÇ©µÄÎÄ×ÖÑùʽ virtual UGbool SetLabelTextStyle(const UGString& strTag, const UGTextStyle& TextStyle); //! \brief ÉèÖñêÇ©ÊÇ·ñÏÔʾ virtual UGbool SetLabelVisible(const UGString& strTag,UGbool bVisible); //! \brief ½«Ö¸¶¨±êÇ©ÉÏÒÆÒ»²ã£» virtual UGbool LabelMoveUp(const UGString &strTag); //! \brief ½«Ö¸¶¨±êÇ©ÏÂÒÆÒ»²ã£» virtual UGbool LabelMoveDown(const UGString &strTag); //! \brief ½«Ö¸¶¨±êÇ©ÖÃΪ×î¶¥²ã£» virtual UGbool LabelMoveTop(const UGString &strTag); //! \brief ½«Ö¸¶¨±êÇ©ÖÃΪ×îµ×²ã£» virtual UGbool LabelMoveBottom(const UGString &strTag); //! \brief Çå³ýËùÓбêÇ©£» virtual void ClearLabel(); //! \brief н¨×Ö¶Î virtual UGbool CreateUserField(const UGString& strName,UGFieldInfo::FieldType nType,UGint nSize,UGint nAttributes = 0); virtual UGbool CreateUserFields(const UGFieldInfos& fieldInfos); //{{ add by xiaoys 2012-07-06 virtual UGbool GetFieldInfos(UGFieldInfos& infos); virtual UGbool GetFieldInfo(UGFieldInfo& info, const UGString& strFieldName); virtual UGbool DeleteUserField(const UGString& strFieldName); //}} add by xiaoys 2012-07-06 //! \brief ÉèÖõ±Ç°×Ö¶ÎÖµ virtual UGbool SetFieldValue(const UGString& strFieldName,const UGVariant& var); //! \brief Ð޸ĵÚiIndex¸ö¶ÔÏóÖ¸¶¨×ֶεÄÖµ¡£ virtual UGbool SetFieldValue(const UGString& strFieldName,const UGVariant& var,const UGint& iIndex); //! \brief »ñÈ¡¶ÔÏóµÚiIndex¸öÊôÐÔ×Ö¶ÎÃû³Æ virtual UGString GetFieldName(UGint iIndex); //! \brief Ôö¼ÓÒ»¸ö´øÊôÐԵıê×¢¶ÔÏó virtual UGint AddFeature(UGGeometry *pGeometry, const UGArray<UGString> &aryFields, const UGArray<UGVariant *> &aryValues,const UGString& strTag); //! \brief Çå³ý¸ú×Ù²ãËùÓжÔÏ󣬵«±£Áô±í½á¹¹£»------------------------ void DeleteAllFeatures(); //}} add by xiaoys 2012-07-03 Ϊ×ÓÀàTrackingLayerEx¿ª·ÅһЩÐ麯Êý //add by xiaoys 2012-07-16 virtual UGbool GetFieldValue(UGVariant& var, UGint iIndex, const UGString& strField); protected: UGDrawing* m_pDrawing; UGRect2D m_rcInvalid; //! \brief ×î´óµÄ·ûºÅµÄ´óС¡£ÕâÊDZƲ»µÃÒѵ쬱ØÐëËæÊ±Î¬»¤ UGdouble m_dMaxMarkerSize; UGuint m_unOptions; UGList<UGGeoEvent*> m_Events; UGDataSource* m_pDs; UGDatasetVector* m_pDv; UGRecordset* m_pRecordset; UGString::Charset m_nCharset; //! \brief ·ûºÅËõ·Å±ÈÀý³ß UGdouble m_dSymScaleDefinition; UGGraphics::BrushOrgMode m_nFillOrgMode; UGbool m_bOrderByGeometryType; UGbool m_bLineSmoothingMode; UGbool m_bTextSmoothingMode; UGbool m_bDeviceTrackingLayer; UGbool m_bTrackingLayerEx; UGMutex m_mutex; UGuint m_nTransPercent; UGGraphics* m_pTransPercentGraphics; UGImage* m_pTransPercentImage; UGBrush* m_pTransPercentBrush; UGPen* m_pTransPercentPen; BeforeTrackingLayerDrawProc m_pBeforeTrackingLayerDrawFunc; AfterTrackingLayerDrawProc m_pAfterTrackingLayerDrawFunc; UGlong m_pEventView; //µ÷ÓÃʼþ»Øµ÷º¯ÊýµÄ¶ÔÏóÖ¸Õë }; } #endif // !defined(AFX_UGTRACKINGLAYER_H__DC6194D6_CDEC_4A74_8522_AC23C8C202F5__INCLUDED_)
zhouqin/EngineBaidu
01_SourceCode_7.0.0_B/Include/Map/UGTrackingLayer.h
C
lgpl-3.0
12,101
<?php defined('ROOTPATH') OR die('No direct access allowed.'); /* File: xajaxPluginManager.inc.php Contains the xajax plugin manager. Title: xajax plugin manager Please see <copyright.inc.php> for a detailed description, copyright and license information. */ /* @package xajax @version $Id: xajaxPluginManager.inc.php 6 2011-03-27 19:01:27Z gekosale $ @copyright Copyright (c) 2005-2006 by Jared White & J. Max Wilson @license http://www.xajaxproject.org/bsd_license.txt BSD License */ //SkipAIO require(dirname(__FILE__) . '/xajaxPlugin.inc.php'); //EndSkipAIO /* Class: xajaxPluginManager */ class xajaxPluginManager { /* Array: aRequestPlugins */ var $aRequestPlugins; /* Array: aResponsePlugins */ var $aResponsePlugins; /* Array: aConfigurable */ var $aConfigurable; /* Array: aRegistrars */ var $aRegistrars; /* Array: aProcessors */ var $aProcessors; /* Array: aClientScriptGenerators */ var $aClientScriptGenerators; /* Function: xajaxPluginManager Construct and initialize the one and only xajax plugin manager. */ function xajaxPluginManager() { $this->aRequestPlugins = array(); $this->aResponsePlugins = array(); $this->aConfigurable = array(); $this->aRegistrars = array(); $this->aProcessors = array(); $this->aClientScriptGenerators = array(); } /* Function: getInstance Implementation of the singleton pattern: returns the one and only instance of the xajax plugin manager. Returns: object - a reference to the one and only instance of the plugin manager. */ function &getInstance() { static $obj; if (!$obj) { $obj = new xajaxPluginManager(); } return $obj; } /* Function: loadPlugins Loads plugins from the folders specified. */ function loadPlugins($aFolders) { foreach ($aFolders as $sFolder) { if ($handle = opendir($sFolder)) { while (!(false === ($sName = readdir($handle)))) { $nLength = strlen($sName); if (8 < $nLength) { $sFileName = substr($sName, 0, $nLength - 8); $sExtension = substr($sName, $nLength - 8, 8); if ('.inc.php' == $sExtension) { require $sFolder . '/' . $sFileName . $sExtension; } } } closedir($handle); } } } /* Function: _insertIntoArray Inserts an entry into an array given the specified priority number. If a plugin already exists with the given priority, the priority is automatically incremented until a free spot is found. The plugin is then inserted into the empty spot in the array. nPriorityNumber - (number): The desired priority, used to order the plugins. */ function _insertIntoArray(&$aPlugins, &$objPlugin, $nPriority) { while (isset($aPlugins[$nPriority])) $nPriority++; $aPlugins[$nPriority] = $objPlugin; } /* Function: registerPlugin Registers a plugin. objPlugin - (object): A reference to an instance of a plugin. Below is a table for priorities and their description: 0 thru 999: Plugins that are part of or extensions to the xajax core 1000 thru 8999: User created plugins, typically, these plugins don't care about order 9000 thru 9999: Plugins that generally need to be last or near the end of the plugin list */ function registerPlugin(&$objPlugin, $nPriority=1000) { if (is_a($objPlugin, 'xajaxRequestPlugin')) { $this->_insertIntoArray($this->aRequestPlugins, $objPlugin, $nPriority); if (method_exists($objPlugin, 'register')) $this->_insertIntoArray($this->aRegistrars, $objPlugin, $nPriority); if (method_exists($objPlugin, 'canProcessRequest')) if (method_exists($objPlugin, 'processRequest')) $this->_insertIntoArray($this->aProcessors, $objPlugin, $nPriority); } else if (is_a($objPlugin, 'xajaxResponsePlugin')) { $this->aResponsePlugins[] = $objPlugin; } else { //SkipDebug $objLanguageManager = xajaxLanguageManager::getInstance(); trigger_error( $objLanguageManager->getText('XJXPM:IPLGERR:01') . get_class($objPlugin) . $objLanguageManager->getText('XJXPM:IPLGERR:02') , E_USER_ERROR ); //EndSkipDebug } if (method_exists($objPlugin, 'configure')) $this->_insertIntoArray($this->aConfigurable, $objPlugin, $nPriority); if (method_exists($objPlugin, 'generateClientScript')) $this->_insertIntoArray($this->aClientScriptGenerators, $objPlugin, $nPriority); } /* Function: canProcessRequest Calls each of the request plugins and determines if the current request can be processed by one of them. If no processor identifies the current request, then the request must be for the initial page load. See <xajax->canProcessRequest> for more information. */ function canProcessRequest() { $bHandled = false; $aKeys = array_keys($this->aProcessors); sort($aKeys); foreach ($aKeys as $sKey) { $mResult = $this->aProcessors[$sKey]->canProcessRequest(); if (true === $mResult) $bHandled = true; else if (is_string($mResult)) return $mResult; } return $bHandled; } /* Function: processRequest Calls each of the request plugins to request that they process the current request. If the plugin processes the request, it will return true. */ function processRequest() { $bHandled = false; $aKeys = array_keys($this->aProcessors); sort($aKeys); foreach ($aKeys as $sKey) { $mResult = $this->aProcessors[$sKey]->processRequest(); if (true === $mResult) $bHandled = true; else if (is_string($mResult)) return $mResult; } return $bHandled; } /* Function: configure Call each of the request plugins passing along the configuration setting specified. sName - (string): The name of the configuration setting to set. mValue - (mixed): The value to be set. */ function configure($sName, $mValue) { $aKeys = array_keys($this->aConfigurable); sort($aKeys); foreach ($aKeys as $sKey) $this->aConfigurable[$sKey]->configure($sName, $mValue); } /* Function: register Call each of the request plugins and give them the opportunity to handle the registration of the specified function, event or callable object. */ function register($aArgs) { $aKeys = array_keys($this->aRegistrars); sort($aKeys); foreach ($aKeys as $sKey) { $objPlugin = $this->aRegistrars[$sKey]; $mResult = $objPlugin->register($aArgs); if (is_a($mResult, 'xajaxRequest')) return $mResult; if (is_array($mResult)) return $mResult; if (is_bool($mResult)) if (true === $mResult) return true; } //SkipDebug $objLanguageManager = xajaxLanguageManager::getInstance(); trigger_error( $objLanguageManager->getText('XJXPM:MRMERR:01') . print_r($aArgs, true) , E_USER_ERROR ); //EndSkipDebug } /* Function: generateClientScript Call each of the request and response plugins giving them the opportunity to output some javascript to the page being generated. This is called only when the page is being loaded initially. This is not called when processing a request. */ function generateClientScript() { $aKeys = array_keys($this->aClientScriptGenerators); sort($aKeys); foreach ($aKeys as $sKey) $this->aClientScriptGenerators[$sKey]->generateClientScript(); } /* Function: getPlugin Locate the specified response plugin by name and return a reference to it if one exists. */ function &getPlugin($sName) { $aKeys = array_keys($this->aResponsePlugins); sort($aKeys); foreach ($aKeys as $sKey) if (is_a($this->aResponsePlugins[$sKey], $sName)) return $this->aResponsePlugins[$sKey]; $bFailure = false; return $bFailure; } }
qrooel/madison_square
lib/xajax/xajax_core/xajaxPluginManager.inc.php
PHP
lgpl-3.0
8,020
/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2014 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.core.issue.workflow; import org.junit.Test; import org.sonar.api.user.User; import org.sonar.core.user.DefaultUser; import static org.mockito.Mockito.*; public class SetAssigneeTest { @Test public void assign() { User user = new DefaultUser().setLogin("eric").setName("eric"); SetAssignee function = new SetAssignee(user); Function.Context context = mock(Function.Context.class); function.execute(context); verify(context, times(1)).setAssignee(user); } @Test public void unassign() { Function.Context context = mock(Function.Context.class); SetAssignee.UNASSIGN.execute(context); verify(context, times(1)).setAssignee(null); } }
jblievremont/sonarqube
sonar-core/src/test/java/org/sonar/core/issue/workflow/SetAssigneeTest.java
Java
lgpl-3.0
1,581
package org.xBaseJ.test; /** * xBaseJ - Java access to dBase files *<p>Copyright 1997-2014 - American Coders, LTD - Raleigh NC USA *<p>All rights reserved *<p>Currently supports only dBase III format DBF, DBT and NDX files *<p> dBase IV format DBF, DBT, MDX and NDX files *<p>American Coders, Ltd *<br>P. O. Box 97462 *<br>Raleigh, NC 27615 USA *<br>1-919-846-2014 *<br>http://www.americancoders.com @author Joe McVerry, American Coders Ltd. @Version 20140310 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library Lesser General Public * License along with this library; if not, write to the Free * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ import junit.framework.TestCase; import org.xBaseJ.DBF; import org.xBaseJ.fields.Field; /** * @author Joe McVerry - American Coders, Ltd. * * To change the template for this generated type comment go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ public class TestLockRead extends TestCase { /** * */ public void testReadLock() { } public void threadThis() { try { DBF writer = new DBF("testfiles/temp.dbf"); for (int i = 0; i < writer.getRecordCount(); i++) { writer.read(true); Field str_field = writer.getField(1); System.out.println(str_field.get()); } writer.close(); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } }
sebkur/xBaseJ
src/test/java/org/xBaseJ/test/TestLockRead.java
Java
lgpl-3.0
2,050
//------------------------------------------------------------------------------ // <auto-generated> // このコードはツールによって生成されました。 // ランタイム バージョン:4.0.30319.34209 // // このファイルへの変更は、以下の状況下で不正な動作の原因になったり、 // コードが再生成されるときに損失したりします。 // </auto-generated> //------------------------------------------------------------------------------ namespace Test_NyARRealityGl_IdMarker.Properties { using System; /// <summary> /// ローカライズされた文字列などを検索するための、厳密に型指定されたリソース クラスです。 /// </summary> // このクラスは StronglyTypedResourceBuilder クラスが ResGen // または Visual Studio のようなツールを使用して自動生成されました。 // メンバーを追加または削除するには、.ResX ファイルを編集して、/str オプションと共に // ResGen を実行し直すか、または VS プロジェクトをビルドし直します。 [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// このクラスで使用されているキャッシュされた ResourceManager インスタンスを返します。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Test_NyARRealityGl_IdMarker.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// 厳密に型指定されたこのリソース クラスを使用して、すべての検索リソースに対し、 /// 現在のスレッドの CurrentUICulture プロパティをオーバーライドします。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
nyatla/NyARToolkitCS
forFW2.0/sample/Test_NyARRealityD3d_IdMarker/Properties/Resources.Designer.cs
C#
lgpl-3.0
3,271
<?php namespace SolasMatch\API\Lib; use \PhpAmqpLib\Connection\AMQPConnection; use \PhpAmqpLib\Message\AMQPMessage; use \SolasMatch\Common as Common; class MessagingClient { public $MainExchange = "SOLAS_MATCH"; // change to consts public $AlertsExchange = "ALERTS"; public $OrgCreatedTopic = "users"; public $TaskRevokedTopic = "users"; public $TaskScoreTopic = "tasks"; public $TaskUploadNotificationTopic = "tasks"; public $CalculateProjectDeadlinesTopic = "projects"; public $UserTaskClaimTopic = "email"; public $PasswordResetTopic = "email"; public $OrgMembershipAcceptedTopic = "email"; public $OrgMembershipRefusedTopic = "email"; public $TaskArchivedTopic = "email"; public $TaskClaimedTopic = "email"; public $EmailVerificationTopic = "email"; public $BannedLoginTopic = "email"; public $UserFeedbackTopic = "email"; public $OrgFeedbackTopic = "email"; public $UserReferenceRequestTopic = "email"; public $UserBadgeAwardedTopic = "email"; public $ProjectImageUploadedTopic = "email"; public $ProjectImageRemovedTopic = "email"; public $ProjectImageStatusChangedTopic = "email"; private $connection; public function messagingClient() { // Default ctor } public function init() { $ret=null; $ret = $this->openConnection(); return $ret; } private function openConnection() { $ret = false; try { $this->connection = new AMQPConnection( Common\Lib\Settings::get('messaging.host'), Common\Lib\Settings::get('messaging.port'), Common\Lib\Settings::get('messaging.username'), Common\Lib\Settings::get('messaging.password') ); if ($this->connection) { $ret = true; } } catch (Exception $e) { error_log("ERROR: ".$e->getMessage()); } return $ret; } public function sendTopicMessage($msg, $exchange, $topic) { $channel = $this->connection->channel(); $channel->exchange_declare($exchange, 'topic', false, true, false); $channel->basic_publish($msg, $exchange, $topic); $channel->close(); } public function sendMessage($msg, $exchange) { $channel = $this->connection->channel(); $channel->exchange_declare($exchange, 'fanout', false, true, false); $channel->basic_publish($msg, $exchange); $channel->close(); } public function createMessageFromString($message) { return new AMQPMessage($message, array('content_type' => 'text/plain')); } public function createMessageFromProto($proto) { $apiFormat = Common\Lib\Settings::get('ui.api_format'); $serializer = null; switch ($apiFormat) { case '.json' : $serializer = new Common\Lib\JSONSerializer(); return new AMQPMessage($serializer->serializeToString($proto)); break; // case '.html' : $serializer = new Common\Lib\HTMLSerializer(); // break; // case '.php' : $serializer = new Common\Lib\PHPSerializer(); // break; // case '.proto' : $serializer = new Common\Lib\ProtobufSerializer(); // break; // case '.xml' : $serializer = new Common\Lib\XMLSerializer(); // break; default : throw new Common\Exceptions\SolasMatchException( "Error: No API format specified or unsupported format." ); } return new AMQPMessage($serializer->serialize($proto)); } }
TheRosettaFoundation/SOLAS-Match
api/lib/MessagingClient.class.php
PHP
lgpl-3.0
3,893
/** * Closest.java * Created by pgirard at 11:35:48 AM on Dec 3, 2010 * in the com.qagwaai.starmalaccamax.shared.model package * for the StarMalaccamax project */ package com.qagwaai.starmalaccamax.shared.model; /** * @author pgirard * */ public interface Closest extends Model { /** * * @return the closest unique identifier */ Long getId(); /** * * @return the order of this entry in the closest calculation */ int getNumberOfJumps(); /** * * @return closest is associated with a specific solar system */ Long getSolarSystemId(); /** * * @return the to system reference */ Long getToSolarSystemId(); /** * * @param id * the closest unique identifier */ void setId(Long id); /** * * @param order * the order of this entry in the closest calculation */ void setNumberOfJumps(int order); /** * * @param solarSystemId * closest is associated with a specific solar system */ void setSolarSystemId(Long solarSystemId); /** * * @param toSolarSystemId * the to system reference */ void setToSolarSystemId(Long toSolarSystemId); }
qagwaai/StarMalaccamax
src/com/qagwaai/starmalaccamax/shared/model/Closest.java
Java
lgpl-3.0
1,362
package net.bukkit_plugin.kojima1021.bukkit.backcommand; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.event.Listener; import org.bukkit.plugin.java.JavaPlugin; /** * @license GPL3 * @author kojima1021 */ public class Main extends JavaPlugin implements Listener { static String prefix = ChatColor.AQUA + "[" + ChatColor.YELLOW + "BackCommand" + ChatColor.AQUA + "]" + ChatColor.RESET + " "; //インスタンス private static Main instance; /** * メインクラスを取得します * * @return instance */ public static Main getInstance() { return instance; } public static String GetPrefix() { return prefix; } //Plugin開始時 @Override public void onEnable() { /** * 初期設定完了; */ //リスナー登録 getServer().getPluginManager().registerEvents(this, this); getServer().getPluginManager().registerEvents(new PlayerListener(), this); getCommand("back").setExecutor(new Commands()); getCommand("bcd").setExecutor(new Commands()); //インスタンス設定 instance = this; //Config this.saveDefaultConfig(); } //Plugin終了時 @Override public void onDisable() { } public static Boolean GetDebug() { FileConfiguration config = getInstance().getConfig(); Boolean tof = config.getBoolean("debug"); return tof; } public static void DebugMessage(String message) { if (GetDebug()) { Bukkit.broadcastMessage(message); System.out.print(message); } } }
kojima1021/BackCommand
src/main/java/net/bukkit_plugin/kojima1021/bukkit/backcommand/Main.java
Java
lgpl-3.0
1,739
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Global tlv_unauthenticated_info_req</title> <link rel="stylesheet" href="../../boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.75.2"> <link rel="home" href="../../index.html" title="ODTONE 0.4"> <link rel="up" href="../../odtone_mih_library.html#header..home.carlos.Projectos.odtone.inc.odtone.mih.tlv_types_hpp" title="Header &lt;/home/carlos/Projectos/odtone/inc/odtone/mih/tlv_types.hpp&gt;"> <link rel="prev" href="tlv_poa.html" title="Global tlv_poa"> <link rel="next" href="tlv_network_type.html" title="Global tlv_network_type"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr><td valign="top"><img alt="'ODTONE - Open Dot Twenty One'" width="100" height="100" src="../.././images/logo.png"></td></tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="tlv_poa.html"><img src="../../images/prev.png" alt="Prev"></a><a accesskey="u" href="../../odtone_mih_library.html#header..home.carlos.Projectos.odtone.inc.odtone.mih.tlv_types_hpp"><img src="../../images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../images/home.png" alt="Home"></a><a accesskey="n" href="tlv_network_type.html"><img src="../../images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="odtone.mih.tlv_unauthenticated_inf_idp5774384"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Global tlv_unauthenticated_info_req</span></h2> <p>odtone::mih::tlv_unauthenticated_info_req</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="../../odtone_mih_library.html#header..home.carlos.Projectos.odtone.inc.odtone.mih.tlv_types_hpp" title="Header &lt;/home/carlos/Projectos/odtone/inc/odtone/mih/tlv_types.hpp&gt;">/home/carlos/Projectos/odtone/inc/odtone/mih/tlv_types.hpp</a>&gt; </span><span class="keyword">static</span> <span class="keyword">const</span> <a class="link" href="tlv_cast_.html" title="Class template tlv_cast_">tlv_cast_</a><span class="special">&lt;</span> <span class="keyword">bool</span><span class="special">,</span> <a class="link" href="tlv_.html" title="Struct template tlv_">tlv_</a><span class="special">&lt;</span> <span class="number">61</span> <span class="special">&gt;</span> <span class="special">&gt;</span> tlv_unauthenticated_info_req<span class="special">;</span></pre></div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2009-2012 Universidade Aveiro<br>Copyright &#169; 2009-2012 Instituto de Telecomunica&#231;&#245;es - P&#243;lo Aveiro<p> This software is distributed under a license. The full license agreement can be found in the LICENSE in this distribution. This software may not be copied, modified, sold or distributed other than expressed in the named license agreement. This software is distributed without any warranty. </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="tlv_poa.html"><img src="../../images/prev.png" alt="Prev"></a><a accesskey="u" href="../../odtone_mih_library.html#header..home.carlos.Projectos.odtone.inc.odtone.mih.tlv_types_hpp"><img src="../../images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../images/home.png" alt="Home"></a><a accesskey="n" href="tlv_network_type.html"><img src="../../images/next.png" alt="Next"></a> </div> </body> </html>
ATNoG/EMICOM
doc/html/odtone/mih/tlv_unauthenticated_inf_idp5774384.html
HTML
lgpl-3.0
3,919
package org.bladerunnerjs.api.spec.utility; import static org.junit.Assert.*; import java.io.File; import java.io.IOException; import java.util.Date; import java.util.List; import javax.naming.InvalidNameException; import org.bladerunnerjs.api.BRJS; import org.bladerunnerjs.api.FileObserver; import org.bladerunnerjs.api.model.exception.modelupdate.ModelUpdateException; import org.bladerunnerjs.api.plugin.AssetPlugin; import org.bladerunnerjs.api.plugin.CommandPlugin; import org.bladerunnerjs.api.plugin.ContentPlugin; import org.bladerunnerjs.api.plugin.MinifierPlugin; import org.bladerunnerjs.api.plugin.ModelObserverPlugin; import org.bladerunnerjs.api.plugin.Plugin; import org.bladerunnerjs.api.plugin.RequirePlugin; import org.bladerunnerjs.api.plugin.TagHandlerPlugin; import org.bladerunnerjs.api.spec.engine.BuilderChainer; import org.bladerunnerjs.api.spec.engine.NodeBuilder; import org.bladerunnerjs.api.spec.engine.SpecTest; import org.bladerunnerjs.api.spec.logging.MockLogLevelAccessor; import org.bladerunnerjs.memoization.PollingFileModificationObserver; import org.bladerunnerjs.memoization.WatchingFileModificationObserver; import org.bladerunnerjs.model.SdkJsLib; import org.bladerunnerjs.model.ThreadSafeStaticBRJSAccessor; import org.bladerunnerjs.plugin.proxy.VirtualProxyAssetPlugin; import org.bladerunnerjs.plugin.proxy.VirtualProxyCommandPlugin; import org.bladerunnerjs.plugin.proxy.VirtualProxyContentPlugin; import org.bladerunnerjs.plugin.proxy.VirtualProxyMinifierPlugin; import org.bladerunnerjs.plugin.proxy.VirtualProxyModelObserverPlugin; import org.bladerunnerjs.plugin.proxy.VirtualProxyRequirePlugin; import org.bladerunnerjs.plugin.proxy.VirtualProxyTagHandlerPlugin; import org.bladerunnerjs.plugin.utility.PluginLoader; import org.bladerunnerjs.utility.FileUtils; import org.mockito.Mockito; public class BRJSBuilder extends NodeBuilder<BRJS> { private BRJS brjs; public BRJSBuilder(SpecTest modelTest, BRJS brjs) { super(modelTest, brjs); this.brjs = brjs; } //TODO: look at brjs is null - commands must be added before BRJS is created public BuilderChainer hasBeenPopulated() throws Exception { brjs.populate("default"); return builderChainer; } public BuilderChainer hasCommandPlugins(CommandPlugin... commands) { verifyBrjsIsNotSet(); for (CommandPlugin command : commands) { specTest.pluginLocator.pluginCommands.add(new VirtualProxyCommandPlugin(command)); } return builderChainer; } public BuilderChainer hasModelObserverPlugins(ModelObserverPlugin... modelObservers) { verifyBrjsIsNotSet(); for (ModelObserverPlugin modelObserver : modelObservers) { specTest.pluginLocator.modelObservers.add(new VirtualProxyModelObserverPlugin(modelObserver)); } return builderChainer; } public BuilderChainer hasContentPlugins(ContentPlugin... contentPlugins) { verifyBrjsIsNotSet(); for (ContentPlugin contentPlugin : contentPlugins) { specTest.pluginLocator.contentPlugins.add(new VirtualProxyContentPlugin(contentPlugin)); } return builderChainer; } public BuilderChainer hasConfigurationFileWithContent(String filename, String content) throws Exception { FileUtils.write(brjs.conf().file(filename), content); return builderChainer; } public BuilderChainer hasAssetPlugins(AssetPlugin... assetPlugins) { verifyBrjsIsNotSet(); for (AssetPlugin assetPlugin : assetPlugins) { specTest.pluginLocator.assetPlugins.add(new VirtualProxyAssetPlugin(assetPlugin)); } return builderChainer; } public BuilderChainer hasMinifierPlugins(MinifierPlugin... minifyPlugins) { verifyBrjsIsNotSet(); for (MinifierPlugin minifierPlugin : minifyPlugins) { specTest.pluginLocator.minifiers.add(new VirtualProxyMinifierPlugin(minifierPlugin)); } return builderChainer; } public BuilderChainer hasTagHandlerPlugins(TagHandlerPlugin... tagHandlers) { verifyBrjsIsNotSet(); for (TagHandlerPlugin tagHandler : tagHandlers) { specTest.pluginLocator.tagHandlers.add(new VirtualProxyTagHandlerPlugin(tagHandler)); } return builderChainer; } public BuilderChainer automaticallyFindsCommandPlugins() { verifyBrjsIsNotSet(); verifyPluginsUnitialized(specTest.pluginLocator.pluginCommands); specTest.pluginLocator.pluginCommands.addAll(PluginLoader.createPluginsOfType(Mockito.mock(BRJS.class), CommandPlugin.class, VirtualProxyCommandPlugin.class)); return builderChainer; } public BuilderChainer automaticallyFindsModelObservers() { verifyBrjsIsNotSet(); verifyPluginsUnitialized(specTest.pluginLocator.modelObservers); specTest.pluginLocator.modelObservers.addAll(PluginLoader.createPluginsOfType(Mockito.mock(BRJS.class), ModelObserverPlugin.class, VirtualProxyModelObserverPlugin.class)); return builderChainer; } public BuilderChainer automaticallyFindsContentPlugins() { verifyBrjsIsNotSet(); verifyPluginsUnitialized(specTest.pluginLocator.contentPlugins); specTest.pluginLocator.contentPlugins.addAll(PluginLoader.createPluginsOfType(Mockito.mock(BRJS.class), ContentPlugin.class, VirtualProxyContentPlugin.class)); return builderChainer; } public BuilderChainer automaticallyFindsTagHandlerPlugins() { verifyBrjsIsNotSet(); verifyPluginsUnitialized(specTest.pluginLocator.tagHandlers); specTest.pluginLocator.tagHandlers.addAll(PluginLoader.createPluginsOfType(Mockito.mock(BRJS.class), TagHandlerPlugin.class, VirtualProxyTagHandlerPlugin.class)); return builderChainer; } public BuilderChainer automaticallyFindsAssetPlugins() { verifyBrjsIsNotSet(); verifyPluginsUnitialized(specTest.pluginLocator.assetPlugins); specTest.pluginLocator.assetPlugins.addAll(PluginLoader.createPluginsOfType(Mockito.mock(BRJS.class), AssetPlugin.class, VirtualProxyAssetPlugin.class)); return builderChainer; } public BuilderChainer automaticallyFindsBundlerPlugins() { automaticallyFindsContentPlugins(); automaticallyFindsTagHandlerPlugins(); automaticallyFindsAssetPlugins(); automaticallyFindsRequirePlugins(); return builderChainer; } public BuilderChainer automaticallyFindsMinifierPlugins() { verifyBrjsIsNotSet(); verifyPluginsUnitialized(specTest.pluginLocator.minifiers); specTest.pluginLocator.minifiers.addAll(PluginLoader.createPluginsOfType(Mockito.mock(BRJS.class), MinifierPlugin.class, VirtualProxyMinifierPlugin.class)); return builderChainer; } public BuilderChainer automaticallyFindsRequirePlugins() { verifyBrjsIsNotSet(); verifyPluginsUnitialized(specTest.pluginLocator.requirePlugins); specTest.pluginLocator.requirePlugins.addAll(PluginLoader.createPluginsOfType(Mockito.mock(BRJS.class), RequirePlugin.class, VirtualProxyRequirePlugin.class)); return builderChainer; } public BuilderChainer automaticallyFindsAllPlugins() { automaticallyFindsContentPlugins(); automaticallyFindsTagHandlerPlugins(); automaticallyFindsAssetPlugins(); automaticallyFindsCommandPlugins(); automaticallyFindsModelObservers(); automaticallyFindsRequirePlugins(); return builderChainer; } public BuilderChainer hasNotYetBeenCreated() throws Exception { if (brjs != null) { brjs.close(); } brjs = null; specTest.brjs = null; specTest.resetTestObjects(); return builderChainer; } @Override public BuilderChainer hasBeenCreated() throws Exception { if (brjs != null) { brjs.close(); } brjs = specTest.createModel(); brjs.io().installFileAccessChecker(); specTest.brjs = brjs; this.node = brjs; super.hasBeenCreated(); return builderChainer; } public BuilderChainer hasBeenCreatedWithWorkingDir(File workingDir) throws Exception { brjs = specTest.createModelWithWorkingDir(workingDir); brjs.io().installFileAccessChecker(); specTest.brjs = brjs; this.node = brjs; super.hasBeenCreated(); return builderChainer; } public BuilderChainer hasBeenAuthenticallyCreated() throws Exception { if (brjs != null) { brjs.close(); } brjs = specTest.createNonTestModel(); brjs.io().installFileAccessChecker(); specTest.brjs = brjs; this.node = brjs; return builderChainer; } public BuilderChainer hasBeenAuthenticallyCreatedWithWorkingDir(File workingDir) throws Exception { if (brjs != null) { brjs.close(); } brjs = specTest.createNonTestModel(workingDir); brjs.io().installFileAccessChecker(); specTest.brjs = brjs; this.node = brjs; return builderChainer; } public BuilderChainer hasBeenAuthenticallyCreatedWithFileWatcherThread() throws Exception { hasBeenAuthenticallyCreated(); attachFileWatcherThread(new WatchingFileModificationObserver(brjs)); return builderChainer; } public BuilderChainer hasBeenAuthenticallyCreatedWithFilePollingThread() throws Exception { hasBeenAuthenticallyCreated(); attachFileWatcherThread(new PollingFileModificationObserver(brjs, 500)); return builderChainer; } public BuilderChainer hasBeenAuthenticallyCreatedWithAutoConfiguredObserverThread() throws Exception { hasBeenAuthenticallyCreated(); attachFileWatcherThread(brjs.fileObserver()); return builderChainer; } public BuilderChainer hasBeenAuthenticallyCreatedWithFileWatcherThreadAndWorkingDir(File workingDir) throws Exception { hasBeenAuthenticallyCreatedWithWorkingDir(workingDir); attachFileWatcherThread(new WatchingFileModificationObserver(brjs)); return builderChainer; } public BuilderChainer hasBeenAuthenticallyReCreated() throws Exception { return hasBeenAuthenticallyCreated(); } public BuilderChainer usedForServletModel() throws Exception { ThreadSafeStaticBRJSAccessor.destroy(); ThreadSafeStaticBRJSAccessor.initializeModel(brjs); return builderChainer; } private void verifyBrjsIsSet() { if (specTest.brjs == null) { throw new RuntimeException("BRJS must exist before this command can be used."); } } private void verifyBrjsIsNotSet() { if (specTest.brjs != null) { throw new RuntimeException("Plugins must be added to BRJS before it is created."); } } private <P extends Plugin> void verifyPluginsUnitialized(List<P> pluginList) { if (pluginList.size() > 0) { throw new RuntimeException("automaticallyFindsXXX() invoked after plug-ins have already been added."); } } public BuilderChainer commandHasBeenRun(String... args) throws Exception { brjs.runCommand(args); brjs.incrementFileVersion(); return builderChainer; } public BuilderChainer userCommandHasBeenRun(String... args) throws Exception { brjs.runUserCommand(new MockLogLevelAccessor(), args); return builderChainer; } public BuilderChainer usesProductionTemplates() throws IOException { verifyBrjsIsSet(); return usesProductionTemplates(locateBrjsSdk()); } public BuilderChainer usesProductionTemplates(File brjsSdkDir) throws IOException { verifyBrjsIsSet(); File templateDir = new File(brjsSdkDir, "sdk/templates"); FileUtils.copyDirectory(brjs, templateDir, brjs.sdkTemplateGroup("default").dir().getParentFile()); File j2eeify = new File(brjsSdkDir, "sdk/j2eeify-app"); FileUtils.copyDirectory(brjs, j2eeify, brjs.file("sdk/j2eeify-app")); return builderChainer; } public BuilderChainer usesJsDocResources() throws IOException { verifyBrjsIsSet(); return usesJsDocResources(locateBrjsSdk()); } public BuilderChainer usesJsDocResources(File brjsSdkDir) throws IOException { verifyBrjsIsSet(); File jsdocResourcesDir = new File(brjsSdkDir, "sdk/jsdoc-toolkit-resources"); File jsdocResourcesDest = brjs.sdkRoot().file("jsdoc-toolkit-resources"); FileUtils.copyDirectory(brjs, jsdocResourcesDir, jsdocResourcesDest); new File(jsdocResourcesDest, "jsdoc-toolkit/jsdoc").setExecutable(true); return builderChainer; } public BuilderChainer hasVersion(String version) { specTest.appVersionGenerator.setVersion(version); return builderChainer; } public BuilderChainer localeSwitcherHasContents(String string) throws IOException, InvalidNameException, ModelUpdateException { SdkJsLib localeSwitcherLib = brjs.sdkLib("br-locale"); FileUtils.write(localeSwitcherLib.file("src/switcher.js"), string); return builderChainer; } public BuilderChainer appsHaveBeeniterated() { brjs.apps(); return builderChainer; } public BuilderChainer pluginsAccessed() { brjs.plugins(); return builderChainer; } public void hasBeenInactiveForOneMillisecond() { long currentTime = (new Date()).getTime(); try { do { Thread.sleep(1); } while (currentTime == (new Date()).getTime()); } catch (InterruptedException e) { throw new RuntimeException(e); } } private File locateBrjsSdk() { File thisDir = new File(".").getAbsoluteFile(); File brjsSdk; do { brjsSdk = new File(thisDir, "brjs-sdk"); thisDir = thisDir.getParentFile(); } while (!brjsSdk.isDirectory() && thisDir != null); if (!brjsSdk.exists() || brjsSdk == null) { throw new RuntimeException("Unable to find parent brjs-sdk directory"); } return brjsSdk; } public BuilderChainer doesNotContainFolder(String filePath) { File file = brjs.file(filePath); org.apache.commons.io.FileUtils.deleteQuietly(file); assertFalse(file.exists()); return builderChainer; } private void attachFileWatcherThread(FileObserver observer) throws IOException { brjs.io().uninstallFileAccessChecker(); specTest.fileWatcherThread = observer; specTest.fileWatcherThread.start(); } }
janhancic/brjs
brjs-core/src/main/java/org/bladerunnerjs/api/spec/utility/BRJSBuilder.java
Java
lgpl-3.0
13,472
var searchData= [ ['generic_5ftype',['generic_type',['../structshyft_1_1time__axis_1_1generic__dt.html#a3251a243c6e09621bc1fd0102cd2ec0e',1,'shyft::time_axis::generic_dt']]] ];
statkraft/shyft-doc
core/html/search/enums_2.js
JavaScript
lgpl-3.0
179
/* * Copyright © gaosong * * This program and the accompanying materials are licensed under * the terms of the GNU Lesser General Public License version 3.0 * as published by the Free Software Foundation. */ package org.gsimple.event.test.adv; public class ChildEvent extends Event { }
dean2015/gs-simple
gsimple/gsimple-event/src/test/java/org/gsimple/event/test/adv/ChildEvent.java
Java
lgpl-3.0
295
package org.idisoft.restos.administracionusuarios; import javax.persistence.EntityExistsException; import javax.persistence.NoResultException; import javax.security.sasl.AuthenticationException; import org.idisoft.restos.model.Usuario; public interface AdministradorUsuarios { public Usuario auntenticarUsuario(final String login, final String password) throws NoResultException,IllegalArgumentException, AuthenticationException; public Usuario registrarUsuario(final Usuario usuario) throws EntityExistsException, IllegalArgumentException; }
jorgeejgonzalez/restos
backend/src/main/java/org/idisoft/restos/administracionusuarios/AdministradorUsuarios.java
Java
lgpl-3.0
556
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #ifndef QTAWS_LISTSTREAMPROCESSORSRESPONSE_H #define QTAWS_LISTSTREAMPROCESSORSRESPONSE_H #include "rekognitionresponse.h" #include "liststreamprocessorsrequest.h" namespace QtAws { namespace Rekognition { class ListStreamProcessorsResponsePrivate; class QTAWSREKOGNITION_EXPORT ListStreamProcessorsResponse : public RekognitionResponse { Q_OBJECT public: ListStreamProcessorsResponse(const ListStreamProcessorsRequest &request, QNetworkReply * const reply, QObject * const parent = 0); virtual const ListStreamProcessorsRequest * request() const Q_DECL_OVERRIDE; protected slots: virtual void parseSuccess(QIODevice &response) Q_DECL_OVERRIDE; private: Q_DECLARE_PRIVATE(ListStreamProcessorsResponse) Q_DISABLE_COPY(ListStreamProcessorsResponse) }; } // namespace Rekognition } // namespace QtAws #endif
pcolby/libqtaws
src/rekognition/liststreamprocessorsresponse.h
C
lgpl-3.0
1,572
/* * Copyright (C) 2003-2014 eXo Platform SAS. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.exoplatform.addons.codefest.team_b.core.api; import java.util.List; import org.exoplatform.addons.codefest.team_b.core.model.Task; import org.exoplatform.addons.codefest.team_b.core.model.TaskFilter; import org.exoplatform.commons.utils.ListAccess; /** * Created by The eXo Platform SAS * Author : eXoPlatform * exo@exoplatform.com * Jun 26, 2014 */ public class TaskListAccess implements ListAccess<Task> { /** the task manager */ private TaskManager taskManager; /** the task filter */ private TaskFilter taskFilter; public TaskListAccess(TaskManager taskManager, TaskFilter filter) { this.taskFilter = filter; this.taskManager = taskManager; } @Override public Task[] load(int index, int length) throws Exception, IllegalArgumentException { List<Task> tasks = taskManager.load(taskFilter, index, length); return tasks.toArray(new Task[tasks.size()]); } public Task[] getAll() throws Exception, IllegalArgumentException { List<Task> tasks = taskManager.load(taskFilter, 0, -1); return tasks.toArray(new Task[tasks.size()]); } @Override public int getSize() throws Exception { return taskManager.count(taskFilter); } }
exo-codefest/2014-team-B
lib/src/main/java/org/exoplatform/addons/codefest/team_b/core/api/TaskListAccess.java
Java
lgpl-3.0
1,944
/* * Copyright (C) 2014 Walkman * Author: Luca Muratore * email: luca.muratore@iit.it * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #ifndef GENERIC_MODULE_HPP #define GENERIC_MODULE_HPP // YARP #include <yarp/os/all.h> // status interface #include <GYM/yarp_status_interface.h> // command interface #include <GYM/yarp_command_interface.hpp> // switch interface #include <GYM/yarp_switch_interface.hpp> // param helper #include <paramHelp/paramHelperServer.h> #include <paramHelp/paramProxyBasic.h> #include <paramHelp/paramProxyInterface.h> // C++11 smart pointers #include <memory> //generic thread #include <GYM/generic_thread.hpp> // param helper define for params #define PARAM_ID_DT 1000 #define PARAM_ID_ROBOT 1001 #define PARAM_SIZE_DT 1 #define PARAM_SIZE_ROBOT 1 // param helper define for commands #define COMMAND_ID_HELP 1000 #define COMMAND_ID_SAVE_PARAMS 1001 /** * @brief auxiliary struct to specify a constraint between T and B. **/ template<class T, class B> struct derived_constraint { /** * @brief constraint: T must be a subclass of B. * * @param ps a pointer to a T. * @return void **/ static void constraints(T* ps) { B* pb = ps; } /** * @brief constraint trigger at compile time. * **/ derived_constraint() { void(*fp)(T*) = constraints; } }; /** * @brief generic module template with a switch interface, a status interface and a paramHelper a generic thread. * The template type T must be a subclass of a generic_thread. * * @author Luca Muratore (luca.muratore@iit.it) **/ template<class T> class generic_module : public yarp::os::RFModule, public paramHelp::ParamValueObserver, public paramHelp::CommandObserver { private: // generic module related variables std::string module_prefix; double module_period; bool alive; // thread controlled by the generic module T* thread; double thread_period; // name of the robot std::string robot_name; // switch interface of the module std::shared_ptr<walkman::yarp_switch_interface> switch_interface; // status interface of the module std::shared_ptr<walkman::yarp_status_interface> status_interface; std::string actual_status; int actual_num_seq; // resource finder yarp::os::ResourceFinder rf; // param helper std::shared_ptr<paramHelp::ParamHelperServer> ph; yarp::os::Port rpc_port; std::vector<paramHelp::ParamProxyInterface *> actual_ph_parameters; std::vector<paramHelp::CommandDescription> actual_ph_commands; bool to_configure; bool to_open_port; /** * @brief create the standard commands for the param helper: * - help : get instructions about how to communicate with this module * - save_params <file_name>: Save the actual configuration parameters to file, inside the resource finder context folder * * @return a std::vector with the CommandDescription objects the standard parameters */ std::vector<paramHelp::CommandDescription> create_standard_ph_commands() { std::vector<paramHelp::CommandDescription> standard_ph_commands; // insert help command standard_ph_commands.push_back(paramHelp::CommandDescription( "help", COMMAND_ID_HELP, "Get instructions about how to communicate with this module") ); // insert save_params command standard_ph_commands.push_back(paramHelp::CommandDescription( "save_params", COMMAND_ID_SAVE_PARAMS, "Usage -> save_params <file_name>. Save the actual configuration parameters to file, inside the resource finder context folder") ); return standard_ph_commands; } /** * @brief get the parameters for the param helper: standard parameters + custom(user defined) parameters calling custom_get_ph_commands() * * @return a std::vector the ParamProxyInterface* of all the parameters: standard + custom */ std::vector<paramHelp::ParamProxyInterface *> get_ph_parameters() { // standard params std::vector<paramHelp::ParamProxyInterface *> ph_parameters( create_standard_ph_parameters() ); // custom params std::vector<paramHelp::ParamProxyInterface *> custom_ph_parameters( custom_get_ph_parameters() ); // concat the two vectors ph_parameters.insert( ph_parameters.end(), custom_ph_parameters.begin(), custom_ph_parameters.end() ); return ph_parameters; } /** * @brief get the commands for the param helper: standard commands + custom(user defined) commands calling custom_get_ph_commands() * * @return a std::vector the CommandDescription objects of all the commands: standard + custom */ std::vector<paramHelp::CommandDescription> get_ph_commands() { // standard params std::vector<paramHelp::CommandDescription> ph_commands( create_standard_ph_commands() ); // custom params std::vector<paramHelp::CommandDescription> custom_ph_commands( custom_get_ph_commands() ); // concat the two vectors ph_commands.insert(ph_commands.end(), custom_ph_commands.begin(), custom_ph_commands.end() ); return ph_commands; } /** * @brief link the standard parameters to the generic module and call custom_ph_link_parameters() for custom link params for the module */ void ph_link_parameters() { ph->linkParam(PARAM_ID_DT, &thread_period); ph->linkParam(PARAM_ID_ROBOT, &robot_name); custom_ph_link_parameters(); } /** * @brief register paramValueChangedCallback and call custom_ph_param_value_changed_callback() */ void ph_param_value_changed_callback() { custom_ph_param_value_changed_callback(); } /** * @brief register the standard commands and call custom_ph_register_commands() for custom commands registration */ void ph_register_commands() { ph->registerCommandCallback(COMMAND_ID_HELP, this); ph->registerCommandCallback(COMMAND_ID_SAVE_PARAMS, this); custom_ph_register_commands(); } /** * @brief utility function for checking a suffix in a std::string - TODO: to move outside this class * * @return true if str ends with the specified suffix */ bool has_suffix(const std::string &str, const std::string &suffix) { return str.size() >= suffix.size() && str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0; } protected: /** * @brief create the standard parameters for the param helper: * - thread_period : an int that represents the period of the controlled thread in millisec * - robot_name : a string that represents the name of the robot * * @return a std::vector with the ParamProxyInterface* of the standard parameters */ virtual std::vector<paramHelp::ParamProxyInterface *> create_standard_ph_parameters() { std::vector<paramHelp::ParamProxyInterface *> standard_ph_parameters; // insert thread_period param standard_ph_parameters.push_back( new paramHelp::ParamProxyBasic<int>( "thread_period", PARAM_ID_DT, PARAM_SIZE_DT, paramHelp::ParamLowerBound<int>(1), paramHelp::PARAM_CONFIG, NULL, "control thread period [milliseconds]" ) ); // insert robot name param standard_ph_parameters.push_back( new paramHelp::ParamProxyBasic<std::string>( "robot_name", PARAM_ID_ROBOT, PARAM_SIZE_ROBOT, paramHelp::PARAM_CONFIG, NULL, "robot name" ) ); return standard_ph_parameters; } /** * @brief initializer for the mandatory params that are: * - the thread period expressed in millisec (int). * - the robot name (std::string). * * @return true if the initialization has success. False otherwise. */ virtual bool initializeMandatoryParam() { yarp::os::Value actual_find_value; //thread period in millisec as an int if( rf.check("thread_period") ) { actual_find_value = rf.find("thread_period"); if ( actual_find_value.isInt() ) { thread_period = actual_find_value.asInt(); } else { //thread period is not an int std::cerr << "Error: thread_period param found but NOT an int" << std::endl; return false; } } else { //thread period does not exist std::cerr << "Error: thread period param NOT found" << std::endl; return false; } //robot name as a string if( rf.check("robot_name") ) { actual_find_value = rf.find("robot_name"); if ( actual_find_value.isString() ) { robot_name = actual_find_value.asString(); } else { //robot name is not a string std::cerr << "Error: robot_name param found but NOT a string" << std::endl; return false; } } else { //robot name does not exist std::cerr << "Error: robot_name param NOT found" << std::endl; return false; } //intizializaions had success return true; } public: // command line args int argc; char** argv; /** * @brief constructor of the generic module. * It creates a standard switch interface at /module_prefix/switch:i and a status interface for the module at /module_prefix/module/status:o * * @param argc: argc * @param argv: argv * @param module_prefix module name * @param module_period period of the module in milliseconds * @param rf resource finder **/ generic_module( int argc, char* argv[], std::string module_prefix, int module_period, yarp::os::ResourceFinder rf ) : argc( argc ), argv( argv ), module_prefix( module_prefix ), module_period( static_cast<double>(module_period) / 1000 ), rf( rf ), alive( false ), actual_num_seq( 0 ), actual_status(), thread( NULL ), to_configure( true ), to_open_port( true ) { // check that T is a generic_thread subclass (at compile time) derived_constraint<T, generic_thread>(); } /** * @brief cutom get parameters for param helper: could be redefined in subclasses * * @return an empty std::vector if not redefined */ virtual std::vector<paramHelp::ParamProxyInterface *> custom_get_ph_parameters() { std::vector<paramHelp::ParamProxyInterface *> empty_vector; return empty_vector; } /** * @brief cutom get commands for param helper: could be redefined in subclasses * * @return an empty std::vector if not redefined */ virtual std::vector<paramHelp::CommandDescription> custom_get_ph_commands() { std::vector<paramHelp::CommandDescription> empty_vector; return empty_vector; } /** * @brief custom link parameters for param helper function: should be redefined if custom parameters are present */ virtual void custom_ph_link_parameters() { } /** * @brief custom param value changed callbacks for param helper: could be redefined if needed */ virtual void custom_ph_param_value_changed_callback() { } /** * @brief custom register command for param helper function: should be redefined if custom commands are present */ virtual void custom_ph_register_commands() { } /** * @brief respond to the rpc port attached to the generic module * * @param command command received * @param reply reply of the module * @return true on rpc process success, false otherwise */ virtual bool respond(const yarp::os::Bottle& command, yarp::os::Bottle& reply) final { bool respond_ok = true; // ph locked ph->lock(); // try to process the command received if( !ph->processRpcCommand( command, reply ) ) { reply.addString( ( std::string( "Command " ) + command.toString().c_str() + " not recognized." ).c_str() ); respond_ok = false; } ph->unlock(); // ph unlocked // if reply is empty put something into it, otherwise the rpc communication gets stuck if( reply.size() == 0 ) reply.addString( ( std::string( "Command " ) + command.toString().c_str()+" received." ).c_str() ); return respond_ok; } /** * @brief custom parameter updated handler: could be redefined in subclasses * * @param pd the ParamProxyInterface* of the updated param */ virtual void custom_parameterUpdated(const paramHelp::ParamProxyInterface *pd) { } /** * @brief custom command received handler: could be redefined in subclasses * * @param cd the CommandDescription object related to the command received * @param params the parameters of the command received * @param reply the reply of the module */ virtual void custom_commandReceived(const paramHelp::CommandDescription &cd, const yarp::os::Bottle &params, yarp::os::Bottle &reply) { } /** * @brief handler called when a parameter is updated: it calls the custom_parameterUpdated() function * * @param pd the ParamProxyInterface* of the updated param */ void parameterUpdated(const paramHelp::ParamProxyInterface *pd) final { // call custom parameterUpdated custom_parameterUpdated( pd ); } /** * @brief handler called when a command is received: it handles the standard commmand as specified in their descriptions and it calls the custom_commandReceived() function * * @param cd the CommandDescription object related to the command received * @param params the parameters of the command received * @param reply the reply of the module */ void commandReceived(const paramHelp::CommandDescription &cd, const yarp::os::Bottle &params, yarp::os::Bottle &reply) final { switch(cd.id) { // help command case COMMAND_ID_HELP: { ph->getHelpMessage(reply); } break; // save parameters command case COMMAND_ID_SAVE_PARAMS: { // get the filename from the params of the save command std::string fileName = params.get( 0 ).toString(); // get the folder name std::string folderName = rf.getHomeContextPath() + "/"; // complete conf path std::string confPath = has_suffix( fileName, ".ini" ) ? folderName + fileName : folderName + fileName + ".ini"; // create the params to save array std::vector<int> configIds; int param_size = actual_ph_parameters.size(); for(unsigned int i = 0; i < param_size; ++i) { std::cout << actual_ph_parameters[i]->name << std::endl; if( actual_ph_parameters[i]->ioType.value == paramHelp::PARAM_IN_OUT || actual_ph_parameters[i]->ioType.value == paramHelp::PARAM_INPUT || actual_ph_parameters[i]->ioType.value == paramHelp::PARAM_CONFIG ) { //add the parameter if the condition is verified configIds.push_back( actual_ph_parameters[i]->id ); } } // write on the file specified by the confPath reply.addString( "Saving to " + confPath + " ... " ); ph->writeParamsOnFile( confPath, configIds.data(), configIds.size()); reply.addString( "ok" ); } break; } // call custom commandReceived custom_commandReceived( cd, params, reply ); } /** * @brief open the generic YARP module standard ports: a switch interface, a status interface and a rpc for the paramHelper * * @return void */ void open_gym_ports() { if( to_open_port ) { std::cout << "Opening the generic ports ..." << std::endl; // update the flag : open port only at the first configure to_open_port = false; // attach to the module the rpc port for the param helper attach( rpc_port ); // open the rpc port for the param helper rpc_port.open( "/" + module_prefix +"/rpc" ); // open standard switch interface switch_interface = std::make_shared<walkman::yarp_switch_interface>( module_prefix ) ; // open status interface status_interface = std::make_shared<walkman::yarp_status_interface>( module_prefix + "/module" ) ; // status rate setted at the half of the module period status_interface->setRate( module_period*1000.0 / 2.0 );//HACK //TODO change double to int everywhere status_interface->start(); } } /** * @brief generic module standard configure: take the rf and initialize the mandatory params. * It calls the custom_configure() at the end of the function. * @param rf resource finder. * * @return true if the rf (standard or custom) exists and the param helper is initialized with success. False otherwise. **/ bool configure( yarp::os::ResourceFinder &rf ) final { // TBD to be removed: will be handled by YARP yarp::os::Time::isValid(); if( to_configure ) { std::cout << "Configuring the module ..." << std::endl; // update the flag to_configure = false; // set the name of the module setName( module_prefix.c_str() ); // get the data for the param heleper using copy constructor to avoid problems on delete actual_ph_parameters = get_ph_parameters(); actual_ph_commands = get_ph_commands(); // switch to standard c const vector const paramHelp::ParamProxyInterface * const* ph_parameters = &actual_ph_parameters[0]; const paramHelp::CommandDescription* ph_commands = &actual_ph_commands[0]; // create the param helper ph = std::make_shared<paramHelp::ParamHelperServer>( ph_parameters, actual_ph_parameters.size(), ph_commands , actual_ph_commands.size() ); // link parameters ph_link_parameters(); // register callbacks for param value changed ph_param_value_changed_callback(); // register commands ph_register_commands(); // check the rf and the mandatory params initialization if( initializeMandatoryParam() ) { // param helper params init yarp::os::Bottle init_msg; if( ph->initializeParams( rf, init_msg ) ) { // print the bottle paramHelp::printBottle( init_msg ); // opend standard module port open_gym_ports(); } else { // error on the parameters initialization std::cerr << "Error while initializing param helper parameters from resource finder: further details below" << std::endl; // print the bottle paramHelp::printBottle( init_msg ); return false; } // call the init on the param helper if( ph->init( module_prefix ) ) { //call the custom configure return custom_configure( rf ); } else { // error on the param helper initialization std::cerr << "Error while opening the param helper YARP info and stream ports." << std::endl; return false; } } else { // error on param helper mandatory params std::cerr << "Error while initializing param helper mandatory param" << std::endl; return false; } } else { std::cout << "Module already configured. Skipping configure ..." << std::endl; return true; } } /** * @brief custom configure function: could be redefined in subclasses * * @return true on succes. False otherwise. **/ virtual bool custom_configure( yarp::os::ResourceFinder &rf ) { return true; } /** * @brief call configure, create a new custom thread and make it start * * @return true if the thread correctly starts and the configure has success. False otherwise **/ bool start() { if( configure( rf ) ) { // create the thread thread = new T( module_prefix, rf, ph ); // start the thread if( !thread->start() ) { // error starting the thread delete thread; thread = NULL; return false; } // thread correctly started alive = true; return true; } // configure error else { return false; } } /** * @brief call cutom_stop, stop and delete the thread. * * @return true if custom_stop has succes. False otherwise. **/ bool close() final { //call cutom_close bool custom_close_ret = custom_close(); // could happend that alive is false here -> close called in automatic after updateModule return false if( alive ){ thread->stop(); delete thread; thread = NULL; } alive = false; to_configure = true; return custom_close_ret; } /** * @brief cutom stop function: could be redefined in subclasses * * @return true on succes. False otherwise. **/ virtual bool custom_close() { return true; } /** * @brief call custom_pause on the thread and suspend the thread. * * @return true if custom_pause has succes. False otherwise. **/ virtual bool pause() final { bool custom_pause_ret = thread->custom_pause(); thread->suspend(); return custom_pause_ret; } /** * @brief call custom_resume on the thread and resume the thread. * * @return true if custom_resume has succes. False otherwise. **/ virtual bool resume() final { bool custom_resume_ret = thread->custom_resume(); thread->resume(); return custom_resume_ret; } /** * @brief check if the module is alive. * * @return true if the module is alive. False otherwise. **/ bool isAlive() { return alive; } /** * @brief getter for the period of the thread. * * @return the period of the thread in [milliseconds]. **/ double getThreadPeriod() { return thread_period; } /** * @brief getter for the name of the robot. * * @return the name of the robot. **/ std::string getRobotName() { return robot_name; } /** * @brief getter for the period of the module. * * @return the period of the module. **/ double getPeriod() final { return module_period; } /** * @brief getter for the prefix of the module. * * @return the prefix of the module. **/ std::string getModulePrefix() { return module_prefix; } /** * @brief update module function, called every module_period as specified in the constructor. * Gets the command from the switch interface and executes it. * * Possible commands are: start, stop, pause, resume and quit. * * * @return false after a quit command. True otherwise. **/ bool updateModule() { // status update if( this->isAlive() ) { actual_status = "Control Thread alive at updateModule : #"; } else { actual_status = "Control Thread NOT alive at updateModule : #"; } status_interface->setStatus( actual_status + std::to_string(actual_num_seq), actual_num_seq); actual_num_seq++; // get the command std::string switch_command; if( switch_interface->getCommand( switch_command ) ) { std::cout << "Switch Interface cmd received: " << switch_command << std::endl; //stop command if( switch_command == "stop" ) { if( this->isAlive() ) { std::cout << "Stopping control thread" << std::endl; this->close(); } } //start command else if( switch_command == "start" ) { if( this->isAlive() ) { std::cout << "Stopping control thread" << std::endl; this->close(); } std::cout << "Starting module" << std::endl; if( this->start() ) { std::cout << "Control thread is started" << std::endl; } else { std::cout << "Error starting control thread" << std::endl; } } // pause command else if( switch_command == "pause" ) { if( this->isAlive() ) { std::cout << "Control thread paused" << std::endl; this->pause(); } } // resume command else if( switch_command == "resume" ) { if( this->isAlive() ) { std::cout << "Control thread resumed" << std::endl; this->resume(); } } // quit command else if( switch_command == "quit" ) { std::cout << "Quit" << std::endl; std::cout << "Closing the module ... " << std::endl; return false; } else { std::cout << switch_command << " is not vaild" << std::endl; } } // true if the module is not quitted return true; } /** * @brief getter method for the ResourceFinder * * @return the resource finder */ yarp::os::ResourceFinder get_resource_finder() { return rf; } /** * @brief getter method for the param helper * * @return the param helper */ std::shared_ptr<paramHelp::ParamHelperServer> get_param_helper() { return ph; } /** * @brief TODO * * @return T* */ T* get_thread() { return thread; } /** * @brief virtual generic module destructor */ virtual ~generic_module() { } }; #endif
robotology-playground/GYM
include/GYM/generic_module.hpp
C++
lgpl-3.0
29,728
\section{Proof and Axioms} \label{s:proof} \lstset{morekeywords={fwd}} As previously discussed, instead of providing a concrete set of typing rules, we provide a set of properties that the type system needs to ensure. We will express such properties using type judgements of the form $\ty{e}{T}$. This judgement form allows an $l$ to be typed with different types based on how it is used, e.g. we might have $\S;\G;\h.m\oR l \cR \vdash l : \Kw{mut}\ C$ and $\S;\G;l.m\oR \h \cR \nvdash l : \Kw{mut}\ C$, where $m$ is a \Q!mut! method taking a \Q!read! parameter. Importantly, we allow types to change during reduction (such as to model promotions), but do not allow the types inside methods to change when they are called (see the \thm{Method Consistency} assumption below). \subheading{Auxiliary Definitions} To express our type system assumptions, we first need some auxiliary definitions. We define what it means for an $l$ to be \reach from an expression or context:\\ \indent $\reach(\s, e, l)$ iff $\exists l' \in e$ such that $l \in \rog(\s, l')$,\\ \indent $\reach(\s, \E, l)$ iff $\exists l' \in \E$ such that $l \in \rog(\s, l')$. \noindent We now define what it means for an object to be \immut: it is in the \rog of an \Q!imm! reference or a \reach \Q!imm! field:\\* \indent $\immut(\s, e, l)$ iff $\exists \E, l'$ such that: \begin{iitemize} \item $e = \E[l']$, \tyr{l'}{\Kw{imm}\,\_}, and $l \in \rog(\s, l')$, or \item $\reach(\s, e, l')$, $\Ss(l').f = \Kw{imm}\,\_$, and $l \in \rog(\s, \s[l'.f])$. \end{iitemize} \noindent We define the \mrog of an $l$ to be the $l'$s reachable from $l$ by traversing through any number of \Q!mut! and \Q!capsule! fields:\\ \indent $l' \in \mrog(\s, l)$ iff:% \begin{iitemize} \item $l' = l$ or \item $\exists f$ such that $\Ss(l).f \in \{\Kw{capsule}\,\_, \Kw{mut}\,\_\}$, and $l' \in \mrog(\s, \s[l.f])$ \end{iitemize} \noindent Now we can define what it means for an $l$ to be \muty\footnote{We use the term \muty to distinguish from \immut: an object might be neither \muty nor \immut, e.g. if there are only \Q!read! references to it.} by a sub-expression $e$, found in \E: something in $l$ is reachable from a \Q!mut! reference in $e$, by passing through any number of \Q!mut! and \Q!capsule! fields:\\ \indent $\muty(\s, \E, e, l)$ iff $\exists \E',l'$ such that: \begin{iitemize} \item $e = \E'[l']$, $\tyr[\E']{l'}{\Kw{mut}\,\_,}$ and \item $\mrog(\s, l')$ not disjoint $\rog(\s, l)$. \end{iitemize} \noindent Finally, we model the \encap property of \Q!capsule! references:\\ \indent $\encap(\s, \E, l)$ iff $\forall l' \in \rog(\s, l)$, if $\muty(\s, \h, \E[l], l')$, then not $\reach(\s, \E, l')$. \subheading{Axiomatic Type Properties} Here we assume a slight variation of the usual \thm{Subject Reduction}: a (sub) expression obtained using any number of reductions, from a well-typed and well-formed initial $\s_0|e_0$, is also well-typed: \SS\begin{Assumption}[Subject Reduction]\rm If $\VS(\s, \E[e])$, then $\Ss; \emptyset; \E \vdash e : T$. \end{Assumption} As we do not have a concrete type system, we need to assume some properties about its derivations. First we require that \Q!new! expressions only have field initialisers with the appropriate type, fields are only updated with expressions of the appropriate type, methods are only called on receivers with the appropriate RC, method parameters have the appropriate type, and method calls are typed with the return type of the method:% \SS\begin{Assumption}[Type Consistency]\rm\ \begin{ienumerate} %if S; G; E |- e.f = e' : _ C, and C.f = T', then S; G; E[e.f = []] |- e' : T' \item If $C.i = T_i\,\_$, then \ty[\Kw{new}\ C\oR e_1,\ldots,e_{i-1},\h,e_{i+1},\ldots,e_n\cR]{e_i}{T_i}. \item If \ty[\h.f \equals e']{e}{\_\,C} and $C.f = T'\,f$, then \ty[e.f \equals \h]{e'}{T'}. \item If \ty[\h.m\oR e_1,\ldots,e_n\cR]{e}{\_\,C} and $C.m = \mdf\,\Kw{method}\,\T\,m\oR\T_1\,\x_1,\ldots,\T_n\x_n\cR\,\_$, then: \begin{enumerate} \item \ty[\h.m\oR e_1,\ldots,e_n\cR]{e}{\mdf\,C}, \item \ty[e.m\oR e_1,\ldots,e_{i-1},\h,e_{i+1},\ldots,e_n\cR]{e_i}{T_i}, and \item \ty{e.m\oR e_1,\ldots,e_n\cR}{T}. %\item hello \end{enumerate} \end{ienumerate} \end{Assumption}% \noindent We also assume that any expression inside a method body can be typed with the same reference capabilities as when it is expanded by our \textsc{mcall} rule:% \SS\begin{Assumption}[Method Consistency]\rm\ If $\VS(\s, \EV[l.m\oR v_1,\ldots,v_n \cR])$ %and $\s|\EV[l.m\oR v_1,\ldots,v_n \cR] \rightarrow \s|$, where: \begin{iitemize} \item $\Ss; \emptyset; \EV[\h.m\oR v_1,\ldots,v_n \cR] \vdash l : \_\,C$, $C.m =\_\,\Kw{method}\,\_\,m\oR T_1\,x_1,\ldots T_n\,x_n \cR\,\E[e]$, \item $\E'$ = $\M{l}{\E}{l.\invariant}$ if $C.m$ is a capsule mutator, otherwise $\E' = \E$, \item $\G = \Kw{this} : \mdf\,C,x_1:T_1, \ldots, x_n:T_n$, and $e' = e[\Kw{this}\coloneqq l,x_1\coloneqq v_1,\ldots,x_n\coloneqq v_n]$, \end{iitemize} \indent then $\emptyset; \G; \E \vdash e : \mdf\,\_$ iff $\Ss; \emptyset; \EV[\E'[\Kw{this}\coloneqq l,x_1\coloneqq v_1,\ldots,x_n\coloneqq v_n]] \vdash e' : \mdf\,\_$. \end{Assumption} \noindent Now we define formal properties about our RCs, thus giving them meaning. First we require that an \immut object not also be \muty: i.e. an object reachable from an \Q!imm! reference/field cannot also be reached from a \Q!mut!/\Q!capsule! reference and through \Q!mut!/\Q!capsule! fields:% \SS\begin{Assumption}[Imm Consistency]\rm\ \\ \indent If $\VS(\s, e)$ and $\immut(\s, e, l)$, then not $\muty(\s, \h, e, l)$. \noindent Note that this does not prevent \emph{promotion} from a \Q!mut! to an \Q!imm!: a reduction step may change the type of an $l$ from \Q!mut! to \Q!imm!, provided that in the new state, the above assumption holds. \end{Assumption} We require that if something was not \muty, that it remains that way; this prevents, for example, runtime promotions from \Q!read! to \Q!mut!, as well as field accesses returning a \Q!mut! from a receiver that was not \Q!mut!:% \SS\begin{Assumption}[Mut Consistency]\rm If $\VS(\s, \EV[e])$, \\ \indent not $\muty(\s, \EV, e, l)$, and $\s|\EV[e] \rightarrow^{+} \s'|\EV[e']$, then not $\muty(\s', \EV, e', l)$. \end{Assumption} \vspace{2pt} % Without this, the next line clashes with a footnote \noindent We require that a \Q!capsule! reference be \encap; and require that \Q!capsule! is a subtype of \Q!mut!:% \SS\begin{Assumption}[Capsule Consistency]\rm\ \begin{ienumerate} \item If \tyr{l}{\Kw{capsule}\,\_}, then $\encap(\s, \E, l)$. \item If \ty{e}{\Kw{capsule}\,C}, then \ty{e}{\Kw{mut}\,C}. \end{ienumerate} \end{Assumption}% \noindent We require that field updates only be performed on \Q!mut! receivers:% \SS\begin{Assumption}[Mut Update]\rm If \ty{e.f \equals e'}{T}, then \ty[\h.f \equals e']{e}{\Kw{mut}\,\_}. \end{Assumption} \noindent We additionally require that field accesses only be typed as \Q!mut!, if their receiver is also \Q!mut!:% \SS\begin{Assumption}[Mut Access]\rm If \ty{e.f}{\Kw{mut}\,\_}, then \ty[\h.f]{e}{\Kw{mut}\,\_}. \end{Assumption} \noindent Finally, we require that a \Q!read! variable or method result not be typeable as \Q!mut!; in conjunction with \thm{Mut Consistency}, \thm{Mut Update}, and \thm{Method Consistency}, this allows one to safely pass or return a \Q!read! without it being used to modify the object's \rog:% \SS\begin{Assumption}[Read Consistency]\rm\ \begin{ienumerate} \item If $\G(x) = \Kw{read}\,\_$, then $\nty{x}{\Kw{mut}\,\_}$. \item If \ty[\h.m\oR \es\cR]{e}{\_\,C} and $C.m = \_\,\Kw{method}\,\Kw{read}\,C'\,\_$, then $\nty{e.m\oR \es \cR}{\Kw{mut}\,\_}$. \end{ienumerate} \noindent Note that \thm{Mut Consistency} prevents an access to a \Q!read! field from being typed as \Q!mut! \end{Assumption}\SS \subheading{Strong Exception Safety} Finally we assume strong exception safety: the memory preserved by each \Q@try@--\Q@catch@ execution is not \muty within the \Q!try!:% \SS\begin{Assumption}[Strong Exception Safety]\rm If $\VS(\s', \E[\Kw{try}^{\s_0}\oC e_0\cC\ \Kw{catch}\ \oC e_1\cC])$, then\\ \indent $\forall l \in \dom(\s_0)$, not $\muty(\s, \E[\Kw{try}^{\s_0}\oC \h\cC\ \Kw{catch}\ \oC e_1\cC], e_0, l)$. \end{Assumption} We use strong exception safety to prove that locations preserved by \Q@try@ blocks are never monitored (this is important as it means that a \Q!catch! that catches a monitor failure will not be able to see the responsible object):% \SS\begin{Lemma}[Unmonitored Try]\rm If $\VS(\s, e)$, $\forall \E$, if $e = \E[\Kw{try}^{\s_0}\oC\E[\M{l}{\_}{\_}]\cC\,\_])$, then $l\notin\s_0$ \end{Lemma}\SS \begin{proof} The proof is by induction: after 0 reduction steps, $e$ cannot contain a monitor expression by the definition of \VS. If this property holds for $\VS(\s, e)$ but not for $\s'|e'$ with $\s|e\rightarrow \s'|e'$, we must have applied the \textsc{update}, \textsc{mcall}, or \textsc{new} rules; since our well-formedness rules on method bodies prevent any other reduction step from introducing a monitor expression. If the reduction was a \textsc{new}, $l$ will be fresh, so it could not have been in $\s_0$. If the reduction was an \textsc{update}, by \thm{Mut Update}, $l$ must have been \Q!mut!, similarly \textsc{mcall} will only introduce a monitor over a call to a \Q!mut! method, so by \thm{Type Consistency}, $l$ was \Q!mut!; either way we have that $l$ was \muty, since our reductions never change the $\s_0$ annotation, by \thm{Strong Exception Safety}, we have that $l \notin \s_0$. \end{proof} \subheading{Determinism} We can use our object capability discipline (described in Section \ref{s:formalism}) to prove that the \Q!invariant()! method is deterministic and does not mutate existing memory:% \SS\begin{Lemma}[Determinism]\rm If $\VS(\s, \EV[l.\invariant])$ and \begin{iitemize} \item[] $\s|\EV[l.\invariant] \rightarrow \s'|\EV[e'] \rightarrow^{+} \s''|\EV[e'']$, \end{iitemize} \indent then $\s'' = \s,\_$, $\s|\EV[l.\invariant] \Rightarrow^+ \s''|\EV[e'']$, and $\forall l' \in \dom(\s)$, not $\muty(\s'', \EV, e'', l)$. \end{Lemma}\SS \begin{proof} The proof will proceed by induction. \emph{Base case}: If $\s|\EV[l.\invariant] \rightarrow \s'|\EV[e']$, then the reduction was performed by \textsc{mcall}. By our well-formedness rules, the \Q!invariant()! method takes a \Q!read! \Q!this!, so by \thm{Method Consistency} and \thm{Read Consistency}, we have that $l$ is not \muty in $e'$. By our well-formedness rules on method bodies and \textsc{mcall}, we have that no other $l'$ was introduced in $e'$, thus nothing is $\muty$ in $e'$. The only non-deterministic single reduction steps are for calls to \Q!mut! methods on a \Q!Cap!; however \Q!invariant()! is a \Q!read! method, so even if $l$ = $c$, we have $\s|\EV[l.\invariant] \Rightarrow \s'|\EV[e']$. In addition, since \textsc{mcall} does not mutate $\s'$ with have $\s' = \s$. \emph{Inductive case}: Consider $\s|\EV[l.\invariant] \Rightarrow^+ \s'|\EV[e'] \rightarrow \s''|\EV[e'']$. We inductively assume that $\forall l' \in \dom(\s)$, not $\muty(\s', \EV, e', l)$; thus by \thm{Mut Consistency}, each such $l'$ is not \muty in $e'$. We also inductively assume that $\s' = \s,\_$, since nothing in $\s$ was \muty: by \thm{Mut Update}, our reduction can't have modified anything in \s, i.e. $\s'' = \s,\_$. As our reduction rules never remove things from memory, $c \in \dom(\s)$, so it can't by $\muty$ in $e'$. By definition of \Q!Cap!, no other instances of \Q!Cap! exist, thus by \thm{Type Consistency}, no \Q!mut! methods of \Q!Cap! can be called; since calling such a method is the only way to get a non-deterministic reduction, we have $\s'|\EV[e'] \Rightarrow \s''|\EV[e'']$. \end{proof} %Thanks to how our reduction rules are designed, especially \textsc{try error}, %@Progress will need to rely on @StrongExceptionSafety internally. % To the best of our knowledge, only the type system of 42~\cite{ServettoEtAl13a,ServettoZucca15} % supports all these assumptions out of the box, % while both Gordon~\cite{GordonEtAl12} and Pony~\cite{clebsch2015deny,clebsch2017orca} supports all except StrongExceptionSafety, % however it should be trivial to modify them to support it: % the \Q@try-catch@ rule could be modified to % $\emptyset;\G\vdash\Kw{try}\ \oC e_0\cC\ \Kw{catch}\ \oC e_1\cC:\T$ % if\\* $\emptyset; % \G,\{x:\Kw{read}\,C | x:\Kw{mut}\,C\,\in\G\} % \vdash e_0:\T$ and $\emptyset;\G\vdash e_1:\T$, % i.e. $e_0$ can be typed when seeing all externally defined mutable references as \Q@read@. \subheading{Capsule Field Soundness} Now we define and prove important properties about our novel \Q!capsule! fields. We first start with a few core auxiliary definitions. We define a notation to easily get the \Q!capsule! field declarations for an $l$:\\ \indent $f \in \cf(\s, l)$ iff $\Ss(l).f = \Kw{capsule}\,\_$. \noindent An $l$ is \HNC if it is not reachable from its \Q!capsule! fields:\\ \indent $\HNC(\s, l)$ iff $\forall f \in \cf(\s, l)$, $l \notin \rog(\s, \s[l.f])$. \noindent We say that an $l$ is \WE if none of its \Q!capsule! fields is \muty without passing through $l$:\\ \indent $\WE(\s, e, l)$ iff $\forall f \in \cf(\s, l)$, not $\muty(\s\setminus l, \h, e, \s[l.f])$. \noindent We say that an $l$ is \NCM if we aren't in a monitor for $l$ which must have been introduced by \textsc{mcall}, and we don't access any of it's \Q!capsule! fields as \Q!mut!:\\ \indent $\NCM(\s, e, l)$ iff $\forall \E$: \begin{iitemize} \item if $e = \E[\M{l}{e'}{\_}]$, then $e' = l$, and \item if $e = \E[l.f]$, $f \in \cf(\s, l)$, and \ntyr[\h.f]{l}{\Kw{capsule}\,\_}, then \ntyr{l.f}{\Kw{mut}\,\_}. \end{iitemize} \noindent Finally we say that $l$ is \HNO if we are in a monitor introduced for a call to a capsule mutator, and $l$ is not reachable from inside this monitor, except perhaps through a single \Q!capsule! field access.\\ \indent $\HNO(\s, e, l)$ iff $e = \EV[\M{l}{e'}{\_}]$, and either: \begin{iitemize} \item $e' = \E[l.f]$, $f \in \cf(\s, l)$, and not $\reach(\s, \E, l)$ or \item not $\reach(\s, e', l)$. \end{iitemize} \noindent Now we formally state the core properties of our \Q!capsule! fields (informally described in \ref{s:protocol}):% \SS\begin{theorem}[Capsule Field Soundness]\rm If $\VS(\s, e)$ then $\forall l$, if $\reach(\s, e, l)$, then:\\ \indent $\HNC(\s, l)$ and either: \begin{iitemize} \item $\WE(\s, e, l)$ and $\NCM(\s, e, l)$, or \item $\HNO(\s, e, l)$. \end{iitemize} \end{theorem}\SS \begin{proof} This trivially holds in the base case when $\s = c\mapsto\Kw{Cap}\{\}$, since \Q!Cap! has no \Q!capsule! fields and the initial main expression cannot have monitors. Now we suppose it holds for a $\VS$ and prove it for the next $\VS$. Note that any single reduction step can be obtained by exactly one application of the \textsc{ctxv} rule and one other rule. We will first proceed by cases on the property we need to prove, and then by the non-\textsc{ctxv} reduction rules that could violate or ensure it:% \begin{ienumerate} \item \HNC: \begin{enumerate} \item (\textsc{new}) $\s|\EV[\Kw{new}\ C\oR v_1,\ldots,v_n\cR]\rightarrow \s'| \EV[\M{l}{l}{l\singleDot\invariant}]$, where $\s' = \s,l\mapsto C\{v_1,\ldots,v_n\}$: \begin{itemize} \item This reduction step doesn't modify any pre-existing $l'$, so we can't have broken \HNC for them. \item Since the pre-existing \s was not modified, by \VS, $l \notin \rog(\s, v_i) = \rog(\s', \s'[l.f])$; thus \HNC holds for $l$. \end{itemize} \item (\textsc{update}) $\s|\EV[l.f\equals{}v]\rightarrow \s[l.f=v]|\EV[\M{l}{l}{l.\invariant}]$: \begin{itemize} % \item $l$ cant have been \HNO, since we had $l.f = v$ inside our evaluation context, and $l.f = v$ is not a field access. \item If $f \in \cf(\s, l)$: by \thm{Mut Update}, we have that $l$ is \muty, so by \thm{Type Consistency} and \thm{Capsule Consistency}, $\encap(\s, \EV[l.f = \square], v)$, hence $l$ is not \reach from $v$, and so after the update, \HNC still holds for $l$. \item Now consider any $l'$ and $f' \in \cf(\s, l')$, with $l'.f' \neq l.f$: \begin{itemize} \item If $l'$ was \WE, by \thm{Mut Update}, $l$ is \Q!mut!. By \WE, the \rog of $l'.f'$ is not \muty (except through a field \emph{access} on $l'$), thus we have that $l \notin \rog(\s, \s[l'.f'])$, in addition, since $l'.f' \neq l.f$, we can't have modified the $\rog$ of $l'.f'$, hence $l'$ is still \HNC. \item Otherwise, $l'$ was \HNO, and so $l' \notin \rog(\s, v)$, so we can't have added $l'$ to the \rog of anything, thus \HNC still holds. \end{itemize} \end{itemize} \item No other reduction rule modifies memory, so they trivially preserve \HNC for all $l$s. \end{enumerate} \item \HNO: \begin{enumerate} \item (\textsc{access}) $\s|\EV[l.f]\rightarrow \s|\EV[\s[l.f]]$: \begin{itemize} \item Suppose $l$ was \HNO, then $\EV = \EV'[\M{l}{\E[l.f]}{\_}]$, with $l$ not \reach from $\E$, and $l.f$ is an access to a \Q!capsule! field. By \HNC, $l$ is not in the \rog of $\s[l.f]$, and so $l$ is not \reach from $\E[\s[l.f]]$, and so \HNO still holds. \item Clearly this reduction cannot have made any $l'$ \reach in a sub-expression where it wasn't already \reach, so we can't have violated \HNO for any other $l'$. \end{itemize} \item (\textsc{monitor exit}) $\s|\EV[\M{l}{v}{\Kw{true}}]\rightarrow \s|\EV[v]$: \begin{itemize} \item As with the above case, we can't have violated \HNO for any $l' \neq l$. \item If this monitor was introduced by \textsc{new} or \textsc{update}, then $v = l$. And so \HNO can't have held for $l$ since $l = v$, and $v$ was not the receiver of a field access. \item Otherwise, this monitor was introduce by \textsc{mcall}, due to a call to a capsule mutator on $l$. Consider the state $\s_0|\EV[e_0]$ immediately before that \textsc{mcall}: \begin{itemize} \item We must not have had that $l$ was \HNO, since $e_0$ would contain $l$ as the receiver of a method call. Thus, by induction, $l$ was originally \WE and \NCM. \item Because \NCM held in $s_0|\EV[e_0]$, and $v$ contains no field accesses or monitor, it also holds in $\EV[v]$. \item Since a capsule mutator cannot have any \Q!mut! parameters, by \thm{Type Consistency}, \thm{Mut Consistency}, and \thm{Mut Update}, the body of the method can't have modified $\s_0$: thus $\s = \s_0, \_$. Since no pre-existing memory has changed since the \textsc{mcall}, and a capsule mutator cannot have a \Q!mut! return type, by \thm{Type Consistency}, we must have $\Ss; \emptyset; \EV \vdash v : \mdf\,\_$ where $\mdf \neq \Kw{mut}$: \begin{itemize} \item If $\mdf = \Kw{capsule}$, by \thm{Capsule Consistency}, the value of any \Q!capsule! field of $l$ can't be in the \rog of $v$ (unless $l$ is no longer \reach), so we haven't made such a field \muty. \item Otherwise, $\mdf \in \{\Kw{read}, \Kw{imm}\}$, by \thm{Read Consistency}, \thm{Imm Consistency}, and \thm{Mut Consistency}, we have that $v$ is not \muty. \end{itemize} Either way, the \textsc{monitor exit} reduction has restored $\WE(\s_0, \EV[e_0], l)$. \end{itemize} \end{itemize} \item (\textsc{try error}) $\s|\EV[\Kw{try}^{\s_0}\oC \error\cC\ \Kw{catch}\ \oC e\cC] \rightarrow \s|\EV[e]$, where $\error = \EV'[\M{l}{\_}{\_}]$: \begin{itemize} \item[] By our reduction rules, we were previously in state $\s_0|\EV[\Kw{try}\ \oC e_0\cC\ \Kw{catch}\ \oC e \cC]$. By \thm{Unmonitored Try}, $l \notin \dom(\s_0)$, and so $l$ was not \reach from $\EV[\Kw{try}\ \oC e_0\cC\ \Kw{catch}\ \oC e \cC]$. By \thm{Strong Exception Safety}, we have that nothing in $\s_0$ has changed, so we must still have that $l$ is not \reach from $\EV[e]$: thus it doesn't matter that $l$ is no longer \HNO. \end{itemize} \item No other rules remove monitors or field accesses, or make something \reach that wasn't before; thus they preserve \HNO for all $l$s. \end{enumerate} \item \NCM: \begin{enumerate} \item (\textsc{mcall}) $\s|\EV[l\singleDot\m\oR v_1,\ldots,v_n\cR]\rightarrow \s|\EV[e]$: \begin{itemize} \item Suppose $m$ is not a capsule mutator, by our well-formedness rules for method bodies, $e$ doesn't contain a monitor. \begin{itemize} \item Since $m$ is not a capsule mutator, if $e = \E[l.f]$, for some $f \in \cf(\s, l)$, we must have that $m$ was not a \Q!mut! method. So by \thm{Mut Access} and \thm{Method Consistency}, we have that $\Ss; \emptyset; \EV[\E] \nvdash l.f : \Kw{mut}\,\_$ only if $m$ was a \Q!capsule! method, which by \thm{Method Consistency}, would mean that $\Ss; \emptyset; \EV[\E[\h.f]] \vdash l : \Kw{capsule}\,\_$. So regardless of what fields $e$ accesses on $l$, we can't have broken \NCM for $l$. \item Consider $l' \neq l$, since fields are instance-private, and by our well-formedness rules on method bodies, $l' \notin e$, thus we can't have introduced any field accesses on $l$. As $e$ doesn't contain monitors either, we haven't broken \NCM for $l'$. \end{itemize} \item Otherwise, $e = \M{l}{e'}{l.\invariant}$. By our rules for capsule mutators, $m$ must be a \Q!mut! method with only \Q!imm! and \Q!capsule! parameters, thus by \thm{Type Consistency}, $l$ must have been \Q!mut!, and each $v_i$ must be \Q!imm! or \Q!capsule!. By \thm{Imm Consistency} and \thm{Capsule Consistency}, $l$ can't be reachable from any $v_i$. Since capsule mutators use \Q!this! only once, to access a \Q!capsule! field, $e' = \E[l.f]$, for some $f \in \cf(\s, l)$. Since $l$ is not \reach from any $v_i$, $l \notin \E$, and by our well-formedness rules for method bodies, $l$ is not \reach from any $l' \in \E$, thus \HNO now holds for $l$. \end{itemize} \item Since no other rule can introduce a monitor expression over an $e \neq l$, nor introduce field access, by \thm{Mut Consistency} and \thm{Mut Access}, we can't have broken \NCM for any $l$. \end{enumerate} \item \WE: \begin{enumerate} \item (\textsc{new}) $\s|\EV[\Kw{new}\ C\oR v_1,\ldots,v_n\cR]\rightarrow \s,l\mapsto C\{v_1,\ldots,v_n\}| \EV[\M{l}{l}{l\singleDot\invariant}]$: \begin{itemize} \item Consider any pre-existing $l'$. Suppose we broke \WE for $l'$ by making some $f' \in \cf(\s, l)$ \muty. Since the \rog of $l'$ can't have been modified, nor could the \rog of any other pre-existing $l''$, we must have that $\s[l'.f]$ is now \muty through some $l.f$. This requires that a $v_i$ be an initialiser for a \Q!mut! or \Q!capsule! field, which by \thm{Type Consistency} and \thm{Capsule Consistency}, means that $v_i$ must also be typeable as \Q!mut!. But then the $\s[l'.f']$ was already \muty through $v_i$, so $l'$ can't have already been \WE, a contradiction. \item Now consider each $i$ with $C.i = \Kw{capsule}\,\_\,f$. By \thm{Type Consistency} and \thm{Capsule Consistency}, $v_i$ was \encap and $\rog(\s, v_i)$ is not \muty from \EV, and so $v_i$ is not $\muty(\s'\setminus l, \h, \EV[\M{l}{l}{l.\invariant}], v_i)$; thus \WE holds for $l$ and each of its \Q!capsule! fields. \end{itemize} \item (\textsc{update}) $\s|\EV[l.f\equals{}v]\rightarrow \s[l.f=v]|\EV[\M{l}{l}{l.\invariant}]$: \begin{itemize} \item If $l$ was \WE and $f \in \cf(\s, l)$, by \thm{Type Consistency} and \thm{Capsule Consistency}, $v$ is \encap, thus $v$ is not \muty from \EV, and $l$ is not \reach from $v$, thus $v$ is still \encap and \WE still holds for $l$ and $f$. \item Now consider any \WE $l'$ and $f' \in \cf(\s, l')$, with $l'.f' \neq l.f$; by the above \textsc{Update} case for \HNC, $l \notin \rog(\s, \s[l'.f'])$. If $f$ was a \Q!mut! or \Q!capsule! field, by \thm{Type Consistency} and \thm{Capsule Consistency}, $v$ was \Q!mut!, so by \WE, $v \notin \rog(\s, \s[l'.f'])$; thus we can't have made $\rog(\s, \s[l'.f'])$ \muty through $l.f$; so $l'.f'$ can't now be \muty through $l$. By \thm{Mut Consitency}, we couldn't have have made $l'.f'$ \muty some other way, so $l'$ is still \WE. \end{itemize} \item (\textsc{access}) $\s|\EV[l.f]\rightarrow \s|\EV[\s[l.f]]$: \begin{itemize} \item Suppose $l$ was \WE and \NCM, and $f \in \cf(\s, l)$, by \thm{Mut Access}, either $\Ss; \emptyset; \EV \nvdash \s[l.f] : \Kw{mut}\,\_$ or $\Ss; \emptyset; \EV[\h.f] \vdash l : \Kw{capsule}\,\_$. If $l$ was \Q!capsule!, then by \thm{Capsule Consistency} and \HNC, $l$ is not \reach from $\EV[\s[l.f]]$, so it is irrelevant if $l$ is no longer \WE. Otherwise, if $l$ was not \Q!capsule!, $\s[l.f]$ will not be \Q!mut!, so \WE is preserved for l. Note that if $l$ wasn't \NCM, it was \HNO, so we don't need to preserve \WE. \item Since this reduction doesn't modify memory, by \thm{Mut Consistency}, there is no other way to make the \rog of a \Q!capsule! field $f'$ of $l'$ \muty without going through $l'$, so \WE is preserved for $l'$. \end{itemize} \item Since none of the other reduction rules modify memory, by \thm{Mut Consistency}, they can't violate \WE. \end{enumerate} \end{ienumerate} \noindent In each case above, for each $l$, \HNC holds; and either \WE and \NCM holds, or \HNO holds. \end{proof} \subheading{Stronger Soundness} It is hard to prove \thm{Soundness} directly, so we first define a stronger property, called \thm{Stronger Soundness}. An object is \mony if execution is currently inside of a monitor for that object, and the monitored expression $e_1$ does not contain $l$ as a \emph{proper} sub-expression: \indent $\mony(e,l)$ iff $e=\EV[\M{l}{e_1}{e_2}]$ and either $e_1=l$ or $l \notin e_1$.%\loseSpace \noindent A monitored object is associated with an expression that cannot observe it, but may reference its internal representation directly. In this way, we can safely modify its representation before checking its invariant. The idea is that at the start the object will be valid and $e_1$ will reference $l$; but during reduction, $l$ will be used to modify the object; only after that moment, the object may become invalid. \thm{Stronger Soundness} says that starting from a well-typed and well-formed $\s_0|e_0$, and performing any number of reductions, every \reach object is either \valid or \mony:% \SS\begin{theorem}[Stronger Soundness]\rm If \VS(\s, e) then $\forall l$, if $\reach(\s, e, l)$ then $\valid(\s, l)$ or $\mony(e, l)$. \end{theorem}\SS \begin{proof} We will prove this inductively, in a similar way to how we proved \thm{Capsule Field Soundness}. In the base case, we have $\s = c\mapsto\Kw{Cap}\{\}$, since \Q!Cap! is defined to have the trivial invariant, we have that $c$ (the only thing in \s), is \valid. Now we assume that everything reachable from the previous \VS was \valid or \mony, and proceed by cases on the non-\textsc{ctxv} rule that gets us to the next \VS. \begin{ienumerate} \item (\textsc{update}) $\s|\EV[l.f\equals v]\rightarrow \s'|\EV[e']$, where $e'=\M{l}{l}{l.\invariant}$: \begin{itemize} \item Clearly $l$ is now $\mony$. \item Consider any other $l'$, where $l \in \rog(\s,l')$ and $l'$ was \valid; now suppose we just made $l'$ not \valid. By our well-formedness criteria, \Q@invariant()@ can only accesses \Q@imm@ and \Q@capsule@ fields, thus by \thm{Imm Consistency} and \thm{Mut Update}, we must have that $l$ was in the \rog of $l'.f'$, for some $f' \in \cf(\s, l')$. Since $l \neq l'$, $l'$ can't have been \WE. Thus, by \thm{Capsule Field Soundness}, $l'$ was \HNO, and $\EV = \EV'[\M{l'}{\EV''}{\_}]$: \begin{itemize} \item If $\EV''[l.f \equals v] = \E[l'.f']$, then by \HNO, $l'$ is not reachable from \E. The monitor must have been introduced by an \textsc{mcall}, on a capsule mutator for $l'$. Since a capsule mutator can take only \Q!imm! and \Q!capsule! parameters, by \thm{Type Consistency}, \thm{Imm Consistency}, and \thm{Capsule Consistency}, $l$ cannot be in their \rog{}s (since $l$ was in the \rog of $l'$, and $l$ is \Q!mut!). Thus the only way for the body of the monitor to access $l$ is by accessing $l'.f'$. Since capsule mutators can access \Q!this! only once, and by the proof of \thm{Capsule Field Soundness}, there is no other $l'.f'$ in $\E[l'.f']$, nor was there one in a previous stage of reduction: hence $l$ is not \reach from $\E$. This is in contradiction with us having just updated $l$. \item Thus, by \HNO, we must have $\EV''[l.f \equals v] = e$, with $l'$ not \reach from $e$; so $l'$ was, and still is, \mony. \end{itemize} \item Since we don't remove any monitors, we can't have violated \mony. In addition, if an $l$ was not in the \rog of a \valid $l'$, by \thm{Determinism}, $l$ is still \valid. \end{itemize} \item (\textsc{monitor exit}) $\s|\M{l}{v}{\Kw{true}}\rightarrow \s|v$: \begin{itemize} \item[] By our \VS and our well-formedness requirements on method bodies, the monitor expression must have been introduced by \textsc{update}, \textsc{mcall}, or \textsc{new}. In each case the 3\textsuperscript{rd} expression started of as $l.\invariant$, and it has now (eventually) been reduced to $\Kw{true}$, thus by \thm{Determinism} $l$ is \valid. This rule does not modify pre-existing memory, introduce pre-existing $l$s into the main expression, nor remove monitors on other $l$s, thus every other pre-existing $l'$ is still \valid (due to \thm{Determinism}), or \mony. \end{itemize} \item (\textsc{new}) $\s|\EV[\Kw{new}\ C\oR\vs\cR]\rightarrow \s,l\mapsto C\{\vs\}|\EV[ \M{l}{l}{l.\invariant}]$: \begin{itemize} \item[] Clearly the newly created object, $l$, is \mony. As with the case for \textsc{monitor exit} above, every other \reach $l$ is still \valid or \mony. \end{itemize} \item (\textsc{try error}) $\s|\EV[\Kw{try}^{\s_0}\oC \error\cC\ \Kw{catch}\ \oC e\cC] \rightarrow \s|\EV[e]$, where $\error = \EV'[\M{l}{\_}{\_}]$: \begin{itemize} \item[] By the proof of \thm{Capsule Field Soundness}, we must have that $l$ is no longer \reach, it is ok that it is now no longer \valid or \mony. As with the case for \textsc{monitor exit} above, every other \reach $l$ is still \valid or \mony. \end{itemize} \end{ienumerate} \noindent None of the other reduction rules modify memory, the memory locations reachable inside of the main expression, or any pre-existing monitor expressions; thus regardless of the reduction performed, we have that each \reach $l$ is \valid or \mony. \end{proof} \subheading{Proof of Soundness} First we need to prove that an object is not reachable from one of its \Q!imm! fields; if it were, \Q!invariant()! could access such a field and observe a potentially broken object:\SS \begin{Lemma}[Imm Not Circular]\rm\ \\ \indent If $\VS(\s, e)$, $\forall f,l$, if $\reach(\s, e, l)$, $\Ss(l).f = \Kw{imm}\,\_$, then $l \notin \rog(\s, \s[l.f])$. \end{Lemma}\SS \begin{proof} The proof is by induction; obviously the property holds in the initial $\s|e$, since $\s = c\mapsto \Kw{Cap}\{\}$. Now suppose it holds in a \VS(\s, e) and consider $\s|e \rightarrow \s'|e'$. \begin{ienumerate} \item Consider any pre-existing \reach $l$ and $f$ with $\Ss(l).f = \Kw{imm}\,\_$, by \thm{Imm Consistency} and \thm{Mut Update}, the only way $\rog(\s, \s[l.f])$ could have changed is if $e = \EV[l.f = v]$, i.e. we just applied the \textsc{update} rule. By \thm{Mut Update} we must have that $l$ was \Q!mut!, by \thm{Type Consistency}, $v$ must have been \Q!imm!, so by \thm{Imm Consistency}, $l \notin \rog(\s, v)$. Since $v = \s'[l.f]$, we now have $l \notin \rog(\s', \s'[l.f])$. \item The only rule that makes an $l$ \reach is \textsc{new}. So consider $e =\EV[\Kw{new}\ C\oR v_1,\ldots,v_n\cR]$ and each $i$ with $C.i = \Kw{imm}\,\_$. But $v_i$ existed in the previous state and $l \notin \dom(\s)$; so by \VS and our reduction rules, $l \notin \rog(\s, v_i) = \rog(\s', \s'[l.f])$. \end{ienumerate} \end{proof} \setcounter{theorem}{0}\LS We can now finally prove the soundness of our invariant protocol: \SS \begin{theorem}[Soundness]\rm If $\VS(\s, \EV[r_l])$, then either $\valid(\s,l)$ or $\trusted(\EV,r_l)$. \end{theorem}\SS \begin{proof} \noindent Suppose $\VS(\s, e)$, and $e = \EV[r_l]$. Suppose $l$ is not $\valid$; since $l$ is \reach, by \thm{Stronger Soundness}, $\mony(e,l)$, $e = \E[\M{l}{e_1}{e_2}]$, and either: \begin{iitemize} \item $\EV = \E[\M{l}{\E'}{e_2}]$, that is $r_l$ (which by definition cannot equal $l$) was found inside of $e_1$, this contradicts the definition of \mony, or \item $\EV = \E[\M{l}{e_1}{\E'}]$, and thus $r_l$ was found inside $e_2$. By our reduction rules, all monitor expressions start with $e_2=l.\invariant$; if this has yet to be reduced, then $\E'[r_l] = l.\invariant$, thus $r_l$ is \trusted. The next execution step will be an \textsc{mcall}, so by our well-formedness rules for \Q!invariant()!, $e_2$ will only contain $l$ as the receiver of a field access; so if we just performed said \textsc{mcall}, $r_l = l.f$: hence $r_l$ is trusted. Otherwise, by \thm{Imm Not Circular}, \thm{Capsule Field Soundness}, and \HNC, no further reductions of $e_2$ could have introduced an occurrence of $l$, so we must have that $r_l$ was introduced by the \textsc{mcall} to \Q!invariant()!, and so it is \trusted. \end{iitemize} Thus either $l$ is $\valid$ or $r_l$ is \trusted. \end{proof}
ElvisResearchGroup/L42
papers/Toplas2020/proof.tex
TeX
lgpl-3.0
32,983
数据同步服务 -- `sync server` 用于将本地日志同步到后端 `db` 中,主要包含 `libsync` 和 `network` 两个模块。 说明:**sync server 不是必须安装的模块**。如果不部署该服务,HA的如下接口将失效: * [sync_status](../../api/ha/sync_status.md) * [sync_alive](../../api/ha/sync_alive.md) 同时,如果HA和DB之间的网络情况不理想,**数据不一致的概率会增加**。 **请根据生产环境的实际情况来决定是否部署该服务**。 ### libsync ### 目录:`hustdb/sync/module` #### `check_backend` #### 功能:定时检测后端db存活。 如果db可用,则通过 `pipe` 通知 `read_log` 模块读取该 `db` 下的日志文件,开始同步。 #### `release_file` #### 功能: 定时清理同步完成的文件 通过位图检测 `release_queue` 中的文件是否同步完成,如果同步完成则删除文件并释放资源。 #### `monitor` #### 功能:监控日志文件目录。 如果产生日志文件,则将文件加入对应 `db` 的 `file_queue`。 #### `read_log` #### 功能:读取日志文件。 从 `file_queue` 中取出日志文件,按行读取该日志文件,将数据加入线程池的 `data_queue`。 将读取完成的文件加入到 `release_queue` 中。 #### `sync_threadpool` #### 功能:线程池,同步数据。 线程池中线程从 `data_queue` 中取出数据,进行 `base64` 解码,构造 `url`,`query` 等,`POST` 到后端 `db` 中。 ### network ### 目录:`hustdb/sync/network` 该模块 **仅对 `HA` 模块提供 `http` 查询服务**。 目前提供的接口包括如下两个: #### `status` #### **接口:** `/status.html` **方法:** `GET` **参数:** 无 该接口用于判断 `sync server` 是否存活。 与 `HA` 对应的接口: [sync_alive](../../api/ha/sync_alive.md) #### `sync_status` #### **接口:** `/sync_status` **方法:** `GET` **参数:** * **backend_count** (必选) 该接口用于获取 `sync server` 进行数据同步的实时状态。 与 `HA` 对应的接口: [sync_status](../../api/ha/sync_status.md) ### 相关问题 ### **Q:** `sync server` 有多少线程? **A:** `4+n` 个;包括 `主线程`,`check_backend&release_file` , `monitor` , `read_log` 等4个线程,以及线程池的n个工作线程 **Q:** `sync server` 模块各子模块间如何配合? **A:** 子模块间通过 `pipe` 或者 `queue` 配合 **Q:** `sync server` 于 `HA` 如何通信? **A:** 以 `libevhtp` 为基本框架封装成 `http` 服务,`HA` 通过子请求查询 `sync server` 提供的接口。 **Q:** `sync server` 的局限与风险? **A:** 对于 `sync server` 开启前生成的日志, `sync server`无法自动同步。如果要同步这些日志,需要手动重新拷贝到 `logs`目录下对应的 `backends` 目录中。 [上一页](../ha.md) [回首页](../../index.md)
Qihoo360/huststore
hustdb/doc/doc/zh/advanced/ha/sync.md
Markdown
lgpl-3.0
2,940
<?php include 'cabecera.php'; ?> <section id="sec1"> <article id="destacadas"> <h6 class="tituloNoticia">LOS PROTAGONISTAS »</h6> <h1 class="titulosNoticias">Pepe y Ramos hacen posible el plan</h1> <ul class="listasNoticias"> <li>La táctica de Ancelotti sería irrealizable sin la pareja de centrales más en forma del mundo, que cortaron cada avance alemán, sobre todo en los balones aéreos</li> </ul> <hr class="suspensivos"> <p class="autorNoticias">DIEGO TORRES | Madrid | 23 ABR 2014 - 21:57 CET</p> <hr class="suspensivos"> <br> <img src="../img/ramos_saca_un_balon.jpg" class="imagenesNoticias"> <footer>Pepe y Ramos tratan de sacar un balón ante Ribéry.</footer> <hr class="suspensivos"> <br> <p>La charla de Carlo Ancelotti antes del partido concentró un mensaje esencial, telúrico, propio de su condición de provinciano. Porque, como decía su maestro, Arrigo Sacchi, se trata de una idea instalada en la conciencia del campesinado italiano desde la Edad Media. El entrenador del Madrid les dijo a sus jugadores que lo primero era defender todos juntos a la espera de una oportunidad y que, si esa oportunidad no llegaba en Chamartín, ya llegaría en Múnich, o nunca, pero que lo importante era prolongar la esperanza en la eliminatoria. Había que resistir como aquellos aldeanos sometidos por el bárbaro. Había que aguantar. Había que sobrevivir como fuese, aunque fuera a base de pan duro y lentejas.</p> <p>Defender, defender, defender. Eso hizo el Madrid ante las cascadas del Bayern, que avanzó desde fuera con Robben y Ribéry, por todas partes con Alaba, por el medio con Mandzukic, y desde la segunda línea con los alemanes, con Lahm, Schweinsteiger y Kroos. Una multitud invadió las praderas del Madrid, que se atrincheró alrededor de su área, donde destacaron los centrales. Los verdaderos héroes de esta estrategia. Pepe y Ramos hicieron las labores oscuras y silenciosas. Pusieron el cuerpo, metieron las piernas, los brazos, saltaron, cortaron, despejaron. Sin ellos el plan habría fracasado. Estuvieron espléndidos, rápidos, astutos para anticiparse. Dice Ancelotti que desde hace un par de meses le han quitado las dudas: ya sabe que Pepe y Ramos son los mejores centrales del mundo. En este momento no hay otros dos más en forma. Son la clase de pilares que sirven de apoyo a los equipos campeones.</p> <p>El Madrid no salió apenas de su campo y tuvo el 27% de la posesión durante el primer tiempo de partido. No fue una estadística gloriosa cuando se trata del club que más dinero ha invertido en fichajes en la última década, con más de 1.000 millones de euros. Una cantidad inaudita en la historia de la industria del deporte. Difícil de justificar solo con títulos, y tampoco los títulos han abundado últimamente.</p> <p>El presidente, Florentino Pérez, dice que su proyecto busca la belleza. Eso le pidió a Ancelotti cuando lo contrató y el entrenador se comprometió en su presentación a promover un fútbol “espectacular”. Estas aspiraciones, sin embargo, chocaron con la práctica. El entrenador lo argumenta con razones técnicas: los elementos más competitivos de la plantilla son aquellos que se expresan mejor contragolpeando, tal vez porque durante tres años Mourinho trabajó y contrató para hacer ese fútbol. De modo que el Madrid contragolpea. Le ganó la Copa al Barça contragolpeando y también contragolpeó al Bayern.</p> <p>Antes de contragolpear, sin embargo, es necesario defender. El Madrid, en este punto, tampoco goza de abundantes especialistas. Modric es mediapunta, Di María es extremo, Carvajal y Coentrão se manejan mejor cuando tienen el balón que sin él, y los delanteros ayudan lo mínimo imprescindible, y a veces tampoco eso. La contradicción parecía diabólica pero Ancelotti le encontró un remedio: Xabi Alonso cuida que todos estén en su sitio y Ramos y Pepe levantan la empalizada. Eso hicieron contra el Bayern, que no encontró el modo de filtrar pases interiores y acabó casi todas las jugadas centrando balones a la olla. Ahí destacaron Pepe y Ramos. Sobre todo Pepe, que en el apartado de los despejes de cabeza acabó llevándose la mayoría de duelos. En la primera mitad el equipo alemán disparó nueve veces a puerta contra seis del Madrid. Pero fueron tiros filtrados, sin precisión, rebotados muchas veces en las piernas de los defensas locales.</p> <p>Mandzukic, el destinatario principal de los centros, fue reducido a la impotencia. Otra buena intuición de Ancelotti, que bromeó estos días sobre el delantero centro croata. El entrenador dijo que se trataba de un excelente punta pero que, en el sistema de Guardiola, se encontraba despistado. Al hilo de esta observación añadió que Mandzukic, si jugaba, se convertiría en el tercer central del Madrid, un verdadero tarugo en los avances de su propio equipo. Presa fácil para Pepe y Ramos, que lo tomaron alternativamente sin darle tregua. Pepe fue sustituido por lesión en el minuto 73 y el estadio emitió un grito de adoración: “¡Peeeeepe, Peeeeepe…!”.</p> </article> <article id="opiniones"> <hr class="lineasNoticiasRelacionadas"> <h4 class="nRelacionadas">COMENTAR</h4> <hr class="lineasNoticiasRelacionadas"> <form> <textarea id="textoArea" rows="4" cols="50" maxlength="4"></textarea> <br> <input type="submit" value="Comentar" /> </form> <br> <article class="comentar"> <p>No hay ningún comentario.</p> </article> </article> </section> <section id="sec2"> <article id="relaciaonadas"> <hr class="lineasNoticiasRelacionadas"> <h4 class="nRelacionadas">NOTICIAS RELACIONADAS</h4> <hr class="lineasNoticiasRelacionadas"> <br> <h4 class="nRelacionadas2">En el Valle de Lecrín</h4> <aside class="relacionadas2"> <ul> <li><a href="../local/ancelotti_contra_somos_formidables.php">Ancelotti: "A la contra somos formidables"</a></li> <li><a href="../local/guardiola_hemos_sido_valientes.php">Guardiola: "Nosotros hemos sido valientes"</a></li> <li><a href="../local/lahm_fortaleza_debilidad.php">Lahm, fortaleza y debilidad</a></li> </ul> </aside> <h4 class="nRelacionadas2">En otros medios</h4> <aside class="relacionadas2"> <ul> <li><a href="http://www.lavanguardia.com/">lavanguardia.es</a></li> <li><a href="http://www.abc.es/">abc.es</a></li> <li><a href="http://www.rtve.es/">rtve.es</a></li> <li><a href="http://www.elmundo.es/">elmundo.es</a></li> <li><a href="http://www.20minutos.es/">20minutos.es</a></li> </ul> </aside> <h4 class="nRelacionadas2">Y además</h4> <aside class="relacionadas2"> <ul> <li><a href="#">El fin de Windows XP aúpa las ventas de PC de sobremesa en Europa (Dealerworld.es)</a></li> <li><a href="#">Los gastos no deducibles (Captio)</a></li> <li><a href="#">La censura planea sobre la regulación de Internet en México (El País)</a></li> <li><a href="#">Aguirre: la ciudadanía "no quiere políticos prepotentes en coches… (Expansión)</a></li> </ul> </aside> </article> <article id="publicitarios"> <a href="https://www.apple.com/es/"><img src="../img/HomerApple.jpg"></a> <a href="https://www.nestle.es/kitkat/aspx/index.aspx"><img src="../img/kitkat.jpg"></a> <a href="http://www.nike.com/es/es_es/"><img src="../img/nike.jpg" id="imgNike"></a> </article> </section> <?php include '../pie.php'; ?>
franciscomanuel/periodico
local/pepe_ramos_hacen_posible.php
PHP
lgpl-3.0
7,704
/******************************************************************************* * This file is part of romer. * * romer is distributed under the terms of the GNU Lesser General Public License (LGPL), Version 3.0. * * Copyright 2011-2014, The University of Manchester * * romer is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * romer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with romer. * If not, see http://www.gnu.org/licenses/. ******************************************************************************/ package uk.ac.manchester.cs.romer.compilation; /** * @author Rafael S. Goncalves <br/> * Information Management Group (IMG) <br/> * School of Computer Science <br/> * University of Manchester <br/> */ public class OnlineCompiler { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } }
rsgoncalves/romer
src/uk/ac/manchester/cs/romer/compilation/OnlineCompiler.java
Java
lgpl-3.0
1,355
package org.javlo.macro; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.javlo.context.ContentContext; import org.javlo.context.GlobalContext; import org.javlo.navigation.MenuElement; import org.javlo.navigation.MenuElementNameComparator; import org.javlo.service.PersistenceService; public class SortChildren extends AbstractMacro { @Override public String getName() { return "sort-children"; } @Override public String perform(ContentContext ctx, Map<String, Object> params) throws Exception { GlobalContext globalContext = GlobalContext.getInstance(ctx.getRequest()); List<MenuElement> mustSorted = new LinkedList<MenuElement>(ctx.getCurrentPage().getChildMenuElements()); Collections.sort(mustSorted, new MenuElementNameComparator(ctx, true)); int i=0; for (MenuElement menuElement : mustSorted) { i++; menuElement.setPriority(10*i); } mustSorted=null; PersistenceService persistenceService = PersistenceService.getInstance(globalContext); persistenceService.setAskStore(true); return null; } @Override public boolean isPreview() { return true; } };
Javlo/javlo
src/main/java/org/javlo/macro/SortChildren.java
Java
lgpl-3.0
1,176
/* This file is part of SharpPcap. SharpPcap is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SharpPcap is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with SharpPcap. If not, see <http://www.gnu.org/licenses/>. */ /* * Copyright 2005 Tamir Gal <tamir@tamirgal.com> * Copyright 2008-2010 Chris Morgan <chmorgan@gmail.com> */ namespace SharpPcap { /// <summary>A delegate for Packet Arrival events</summary> public delegate void PacketArrivalEventHandler(object sender, PacketCapture e); }
chmorgan/sharppcap
SharpPcap/PacketArrivalEventHandler.cs
C#
lgpl-3.0
951
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_26) on Sun Dec 22 15:55:34 GMT 2013 --> <TITLE> NVParameterBufferObject (LWJGL API) </TITLE> <META NAME="date" CONTENT="2013-12-22"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="NVParameterBufferObject (LWJGL API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/NVParameterBufferObject.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../org/lwjgl/opengl/NVPackedDepthStencil.html" title="class in org.lwjgl.opengl"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../org/lwjgl/opengl/NVPathRendering.html" title="class in org.lwjgl.opengl"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?org/lwjgl/opengl/NVParameterBufferObject.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="NVParameterBufferObject.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> org.lwjgl.opengl</FONT> <BR> Class NVParameterBufferObject</H2> <PRE> java.lang.Object <IMG SRC="../../../resources/inherit.gif" ALT="extended by "><B>org.lwjgl.opengl.NVParameterBufferObject</B> </PRE> <HR> <DL> <DT><PRE>public final class <B>NVParameterBufferObject</B><DT>extends java.lang.Object</DL> </PRE> <P> <HR> <P> <!-- =========== FIELD SUMMARY =========== --> <A NAME="field_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Field Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../org/lwjgl/opengl/NVParameterBufferObject.html#GL_FRAGMENT_PROGRAM_PARAMETER_BUFFER_NV">GL_FRAGMENT_PROGRAM_PARAMETER_BUFFER_NV</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Accepted by the &lt;target&gt; parameter of ProgramBufferParametersfvNV, ProgramBufferParametersIivNV, and ProgramBufferParametersIuivNV, BindBufferRangeNV, BindBufferOffsetNV, BindBufferBaseNV, and BindBuffer and the &lt;value&gt; parameter of GetIntegerIndexedvEXT:</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../org/lwjgl/opengl/NVParameterBufferObject.html#GL_GEOMETRY_PROGRAM_PARAMETER_BUFFER_NV">GL_GEOMETRY_PROGRAM_PARAMETER_BUFFER_NV</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Accepted by the &lt;target&gt; parameter of ProgramBufferParametersfvNV, ProgramBufferParametersIivNV, and ProgramBufferParametersIuivNV, BindBufferRangeNV, BindBufferOffsetNV, BindBufferBaseNV, and BindBuffer and the &lt;value&gt; parameter of GetIntegerIndexedvEXT:</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../org/lwjgl/opengl/NVParameterBufferObject.html#GL_MAX_PROGRAM_PARAMETER_BUFFER_BINDINGS_NV">GL_MAX_PROGRAM_PARAMETER_BUFFER_BINDINGS_NV</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Accepted by the &lt;pname&gt; parameter of GetProgramivARB:</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../org/lwjgl/opengl/NVParameterBufferObject.html#GL_MAX_PROGRAM_PARAMETER_BUFFER_SIZE_NV">GL_MAX_PROGRAM_PARAMETER_BUFFER_SIZE_NV</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Accepted by the &lt;pname&gt; parameter of GetProgramivARB:</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../org/lwjgl/opengl/NVParameterBufferObject.html#GL_VERTEX_PROGRAM_PARAMETER_BUFFER_NV">GL_VERTEX_PROGRAM_PARAMETER_BUFFER_NV</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Accepted by the &lt;target&gt; parameter of ProgramBufferParametersfvNV, ProgramBufferParametersIivNV, and ProgramBufferParametersIuivNV, BindBufferRangeNV, BindBufferOffsetNV, BindBufferBaseNV, and BindBuffer and the &lt;value&gt; parameter of GetIntegerIndexedvEXT:</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../org/lwjgl/opengl/NVParameterBufferObject.html#glProgramBufferParametersINV(int, int, int, java.nio.IntBuffer)">glProgramBufferParametersINV</A></B>(int&nbsp;target, int&nbsp;buffer, int&nbsp;index, java.nio.IntBuffer&nbsp;params)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../org/lwjgl/opengl/NVParameterBufferObject.html#glProgramBufferParametersIuNV(int, int, int, java.nio.IntBuffer)">glProgramBufferParametersIuNV</A></B>(int&nbsp;target, int&nbsp;buffer, int&nbsp;index, java.nio.IntBuffer&nbsp;params)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../org/lwjgl/opengl/NVParameterBufferObject.html#glProgramBufferParametersNV(int, int, int, java.nio.FloatBuffer)">glProgramBufferParametersNV</A></B>(int&nbsp;target, int&nbsp;buffer, int&nbsp;index, java.nio.FloatBuffer&nbsp;params)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ============ FIELD DETAIL =========== --> <A NAME="field_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Field Detail</B></FONT></TH> </TR> </TABLE> <A NAME="GL_MAX_PROGRAM_PARAMETER_BUFFER_BINDINGS_NV"><!-- --></A><H3> GL_MAX_PROGRAM_PARAMETER_BUFFER_BINDINGS_NV</H3> <PRE> public static final int <B>GL_MAX_PROGRAM_PARAMETER_BUFFER_BINDINGS_NV</B></PRE> <DL> <DD>Accepted by the &lt;pname&gt; parameter of GetProgramivARB: <P> <DL> <DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#org.lwjgl.opengl.NVParameterBufferObject.GL_MAX_PROGRAM_PARAMETER_BUFFER_BINDINGS_NV">Constant Field Values</A></DL> </DL> <HR> <A NAME="GL_MAX_PROGRAM_PARAMETER_BUFFER_SIZE_NV"><!-- --></A><H3> GL_MAX_PROGRAM_PARAMETER_BUFFER_SIZE_NV</H3> <PRE> public static final int <B>GL_MAX_PROGRAM_PARAMETER_BUFFER_SIZE_NV</B></PRE> <DL> <DD>Accepted by the &lt;pname&gt; parameter of GetProgramivARB: <P> <DL> <DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#org.lwjgl.opengl.NVParameterBufferObject.GL_MAX_PROGRAM_PARAMETER_BUFFER_SIZE_NV">Constant Field Values</A></DL> </DL> <HR> <A NAME="GL_VERTEX_PROGRAM_PARAMETER_BUFFER_NV"><!-- --></A><H3> GL_VERTEX_PROGRAM_PARAMETER_BUFFER_NV</H3> <PRE> public static final int <B>GL_VERTEX_PROGRAM_PARAMETER_BUFFER_NV</B></PRE> <DL> <DD>Accepted by the &lt;target&gt; parameter of ProgramBufferParametersfvNV, ProgramBufferParametersIivNV, and ProgramBufferParametersIuivNV, BindBufferRangeNV, BindBufferOffsetNV, BindBufferBaseNV, and BindBuffer and the &lt;value&gt; parameter of GetIntegerIndexedvEXT: <P> <DL> <DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#org.lwjgl.opengl.NVParameterBufferObject.GL_VERTEX_PROGRAM_PARAMETER_BUFFER_NV">Constant Field Values</A></DL> </DL> <HR> <A NAME="GL_GEOMETRY_PROGRAM_PARAMETER_BUFFER_NV"><!-- --></A><H3> GL_GEOMETRY_PROGRAM_PARAMETER_BUFFER_NV</H3> <PRE> public static final int <B>GL_GEOMETRY_PROGRAM_PARAMETER_BUFFER_NV</B></PRE> <DL> <DD>Accepted by the &lt;target&gt; parameter of ProgramBufferParametersfvNV, ProgramBufferParametersIivNV, and ProgramBufferParametersIuivNV, BindBufferRangeNV, BindBufferOffsetNV, BindBufferBaseNV, and BindBuffer and the &lt;value&gt; parameter of GetIntegerIndexedvEXT: <P> <DL> <DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#org.lwjgl.opengl.NVParameterBufferObject.GL_GEOMETRY_PROGRAM_PARAMETER_BUFFER_NV">Constant Field Values</A></DL> </DL> <HR> <A NAME="GL_FRAGMENT_PROGRAM_PARAMETER_BUFFER_NV"><!-- --></A><H3> GL_FRAGMENT_PROGRAM_PARAMETER_BUFFER_NV</H3> <PRE> public static final int <B>GL_FRAGMENT_PROGRAM_PARAMETER_BUFFER_NV</B></PRE> <DL> <DD>Accepted by the &lt;target&gt; parameter of ProgramBufferParametersfvNV, ProgramBufferParametersIivNV, and ProgramBufferParametersIuivNV, BindBufferRangeNV, BindBufferOffsetNV, BindBufferBaseNV, and BindBuffer and the &lt;value&gt; parameter of GetIntegerIndexedvEXT: <P> <DL> <DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#org.lwjgl.opengl.NVParameterBufferObject.GL_FRAGMENT_PROGRAM_PARAMETER_BUFFER_NV">Constant Field Values</A></DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="glProgramBufferParametersNV(int, int, int, java.nio.FloatBuffer)"><!-- --></A><H3> glProgramBufferParametersNV</H3> <PRE> public static void <B>glProgramBufferParametersNV</B>(int&nbsp;target, int&nbsp;buffer, int&nbsp;index, java.nio.FloatBuffer&nbsp;params)</PRE> <DL> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="glProgramBufferParametersINV(int, int, int, java.nio.IntBuffer)"><!-- --></A><H3> glProgramBufferParametersINV</H3> <PRE> public static void <B>glProgramBufferParametersINV</B>(int&nbsp;target, int&nbsp;buffer, int&nbsp;index, java.nio.IntBuffer&nbsp;params)</PRE> <DL> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="glProgramBufferParametersIuNV(int, int, int, java.nio.IntBuffer)"><!-- --></A><H3> glProgramBufferParametersIuNV</H3> <PRE> public static void <B>glProgramBufferParametersIuNV</B>(int&nbsp;target, int&nbsp;buffer, int&nbsp;index, java.nio.IntBuffer&nbsp;params)</PRE> <DL> <DD><DL> </DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/NVParameterBufferObject.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../org/lwjgl/opengl/NVPackedDepthStencil.html" title="class in org.lwjgl.opengl"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../org/lwjgl/opengl/NVPathRendering.html" title="class in org.lwjgl.opengl"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?org/lwjgl/opengl/NVParameterBufferObject.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="NVParameterBufferObject.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <i>Copyright &#169; 2002-2009 lwjgl.org. All Rights Reserved.</i> </BODY> </HTML>
GokulEvuri/VenganceRabbit
lib/Docs/javadoc/org/lwjgl/opengl/NVParameterBufferObject.html
HTML
lgpl-3.0
17,910
package de.invesdwin.util.collections.loadingcache.historical.key; import javax.annotation.concurrent.ThreadSafe; import de.invesdwin.util.collections.loadingcache.historical.query.index.IndexedFDate; import de.invesdwin.util.time.date.FDate; @ThreadSafe public class AdjustedFDate extends IndexedFDate { private final int adjustKeyProviderIdentityHashCode; public AdjustedFDate(final IHistoricalCacheAdjustKeyProvider adjustKeyProvider, final FDate adjustedKey) { super(adjustedKey); this.adjustKeyProviderIdentityHashCode = adjustKeyProvider.hashCode(); } public static FDate newAdjustedKey(final IHistoricalCacheAdjustKeyProvider adjustKeyProvider, final FDate key) { if (key == null) { return null; } if (key instanceof AdjustedFDate) { final AdjustedFDate cKey = (AdjustedFDate) key; if (cKey.adjustKeyProviderIdentityHashCode == adjustKeyProvider.hashCode()) { return cKey; } } return new AdjustedFDate(adjustKeyProvider, key); } @SuppressWarnings("deprecation") public static FDate maybeAdjustKey(final IHistoricalCacheAdjustKeyProvider adjustKeyProvider, final FDate key) { if (key == null) { return null; } if (key instanceof AdjustedFDate) { final AdjustedFDate cKey = (AdjustedFDate) key; return maybeAdjust(adjustKeyProvider, cKey); } else { final Object extension = key.getExtension(); if (extension instanceof AdjustedFDate) { final AdjustedFDate cKey = (AdjustedFDate) extension; return maybeAdjust(adjustKeyProvider, cKey); } else { return adjustKeyProvider.adjustKey(key); } } } private static FDate maybeAdjust(final IHistoricalCacheAdjustKeyProvider adjustKeyProvider, final AdjustedFDate cKey) { //only when we move to a different adjust key provider if (adjustKeyProvider.hashCode() != cKey.adjustKeyProviderIdentityHashCode) { return adjustKeyProvider.adjustKey(cKey); } else { return cKey; } } @SuppressWarnings("deprecation") public static boolean isAdjustedKey(final IHistoricalCacheAdjustKeyProvider adjustKeyProvider, final FDate key) { if (key == null) { return false; } if (key instanceof AdjustedFDate) { final AdjustedFDate cKey = (AdjustedFDate) key; return isAdjustedKey(adjustKeyProvider, cKey); } else { final Object extension = key.getExtension(); if (extension instanceof AdjustedFDate) { final AdjustedFDate cKey = (AdjustedFDate) extension; return isAdjustedKey(adjustKeyProvider, cKey); } else { return false; } } } private static boolean isAdjustedKey(final IHistoricalCacheAdjustKeyProvider adjustKeyProvider, final AdjustedFDate cKey) { return adjustKeyProvider.hashCode() == cKey.adjustKeyProviderIdentityHashCode; } }
subes/invesdwin-util
invesdwin-util-parent/invesdwin-util/src/main/java/de/invesdwin/util/collections/loadingcache/historical/key/AdjustedFDate.java
Java
lgpl-3.0
3,186
--Copyright (C) 2009 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --which carries forward this exception. object_draft_schematic_food_component_shared_container_barrel = SharedDraftSchematicObjectTemplate:new { appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0 } ObjectTemplates:addTemplate(object_draft_schematic_food_component_shared_container_barrel, 1809601710) object_draft_schematic_food_component_shared_container_cask = SharedDraftSchematicObjectTemplate:new { appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0 } ObjectTemplates:addTemplate(object_draft_schematic_food_component_shared_container_cask, 2983185528) object_draft_schematic_food_component_shared_container_large_glass = SharedDraftSchematicObjectTemplate:new { appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0 } ObjectTemplates:addTemplate(object_draft_schematic_food_component_shared_container_large_glass, 3740654207) object_draft_schematic_food_component_shared_container_small_glass = SharedDraftSchematicObjectTemplate:new { appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0 } ObjectTemplates:addTemplate(object_draft_schematic_food_component_shared_container_small_glass, 1819609352) object_draft_schematic_food_component_shared_ingredient_ball_of_dough = SharedDraftSchematicObjectTemplate:new { appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0 } ObjectTemplates:addTemplate(object_draft_schematic_food_component_shared_ingredient_ball_of_dough, 797799084) object_draft_schematic_food_component_shared_ingredient_carbosyrup = SharedDraftSchematicObjectTemplate:new { appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0 } ObjectTemplates:addTemplate(object_draft_schematic_food_component_shared_ingredient_carbosyrup, 752274773)
TheAnswer/FirstTest
bin/scripts/object/draft_schematic/food/component/objects.lua
Lua
lgpl-3.0
8,236
/*------------------------------------------------------------------------------------------------- _______ __ _ _______ _______ ______ ______ |_____| | \ | | |______ | \ |_____] | | | \_| | ______| |_____/ |_____] Copyright (c) 2016, antsdb.com and/or its affiliates. All rights reserved. *-xguo0<@ This program is free software: you can redistribute it and/or modify it under the terms of the GNU GNU Lesser General Public License, version 3, as published by the Free Software Foundation. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/lgpl-3.0.en.html> -------------------------------------------------------------------------------------------------*/ package com.antsdb.saltedfish.minke; /** * make sure that returned ranges is within the input. * * @author *-xguo0<@ */ public class RangeAligner implements RangesScanResult { private RangesScanResult upstream; RangeAligner(RangesScanResult upstream) { this.upstream = upstream; } @Override public boolean next() { boolean result = this.upstream.next(); return result; } @Override public Range getInput() { return this.upstream.getInput(); } @Override public Range getRange() { Range result = this.upstream.getRange(); Range input = getInput(); if (Range.compare(result.pKeyStart, result.startMark, input.pKeyStart, input.startMark) < 0) { result = result.clone(); result.pKeyStart = input.pKeyStart; result.startMark = input.startMark; } if (Range.compare(result.pKeyEnd, result.endMark, input.pKeyEnd, input.endMark) > 0) { result = result.clone(); result.pKeyEnd = input.pKeyEnd; result.endMark = input.endMark; } return result; } @Override public MinkePage getPage() { return this.upstream.getPage(); } }
waterguo/antsdb
fish-server/src/main/java/com/antsdb/saltedfish/minke/RangeAligner.java
Java
lgpl-3.0
2,039
<?php /** * Yuju autoload File * * @category common * @package YujuFramework * @author Daniel Fernández <daniel.fdez.fdez@gmail.com> * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1 * @link https://github.com/yuju-framework/yuju * @since version 1.0 */ spl_autoload_register(function ($class_name) { $class_name = str_replace('\\', '/', $class_name); if (!defined('ROOT')) { $root = substr(__DIR__, 0, strlen(__DIR__)-4).'/'; } else { $root = ROOT; } if (file_exists($root.'class/'.$class_name . '.php')) { require_once $root.'class/'.$class_name . '.php'; } elseif (defined('API') && file_exists(API.'class/'.$class_name . '.php')) { require_once API.'class/'.$class_name . '.php'; } });
yuju-framework/yuju
src/lib/autoload.php
PHP
lgpl-3.0
796
/* * 3D City Database - The Open Source CityGML Database * http://www.3dcitydb.org/ * * (C) 2013 - 2015, * Chair of Geoinformatics, * Technische Universitaet Muenchen, Germany * http://www.gis.bgu.tum.de/ * * The 3D City Database is jointly developed with the following * cooperation partners: * * virtualcitySYSTEMS GmbH, Berlin <http://www.virtualcitysystems.de/> * M.O.S.S. Computer Grafik Systeme GmbH, Muenchen <http://www.moss.de/> * * The 3D City Database Importer/Exporter program is free software: * you can redistribute it and/or modify it under the terms of the * GNU Lesser General Public License as published by the Free * Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This software 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 org.citydb.modules.citygml.importer.database.xlink.resolver; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.citydb.modules.citygml.common.database.cache.CacheTable; import org.citydb.modules.citygml.common.database.uid.UIDCacheEntry; import org.citydb.modules.citygml.common.database.xlink.DBXlinkGroupToCityObject; import org.citydb.modules.common.filter.ImportFilter; import org.citydb.modules.common.filter.feature.FeatureClassFilter; import org.citygml4j.model.citygml.CityGMLClass; public class XlinkGroupToCityObject implements DBXlinkResolver { private final Connection batchConn; private final CacheTable cacheTable; private final DBXlinkResolverManager resolverManager; private PreparedStatement psSelectTmp; private PreparedStatement psGroupMemberToCityObject; private PreparedStatement psGroupParentToCityObject; private int parentBatchCounter; private int memberBatchCounter; private FeatureClassFilter featureClassFilter; public XlinkGroupToCityObject(Connection batchConn, CacheTable cacheTable, ImportFilter importFilter, DBXlinkResolverManager resolverManager) throws SQLException { this.batchConn = batchConn; this.cacheTable = cacheTable; this.resolverManager = resolverManager; this.featureClassFilter = importFilter.getFeatureClassFilter(); init(); } private void init() throws SQLException { psSelectTmp = cacheTable.getConnection().prepareStatement("select GROUP_ID from " + cacheTable.getTableName() + " where GROUP_ID=? and IS_PARENT=?"); psGroupMemberToCityObject = batchConn.prepareStatement("insert into GROUP_TO_CITYOBJECT (CITYOBJECT_ID, CITYOBJECTGROUP_ID, ROLE) values " + "(?, ?, ?)"); psGroupParentToCityObject = batchConn.prepareStatement("update CITYOBJECTGROUP set PARENT_CITYOBJECT_ID=? where ID=?"); } public boolean insert(DBXlinkGroupToCityObject xlink) throws SQLException { // for groupMembers, we do not only lookup gmlIds within the document, but also within // the whole database! UIDCacheEntry cityObjectEntry = resolverManager.getDBId(xlink.getGmlId(), CityGMLClass.ABSTRACT_CITY_OBJECT, true); if (cityObjectEntry == null || cityObjectEntry.getId() == -1) return false; if (featureClassFilter.filter(cityObjectEntry.getType())) return true; // be careful with cyclic groupings! if (cityObjectEntry.getType() == CityGMLClass.CITY_OBJECT_GROUP) { ResultSet rs = null; try { psSelectTmp.setLong(1, cityObjectEntry.getId()); psSelectTmp.setLong(2, xlink.isParent() ? 1 : 0); rs = psSelectTmp.executeQuery(); if (rs.next()) { resolverManager.propagateXlink(xlink); return true; } } finally { if (rs != null) { try { rs.close(); } catch (SQLException sqlEx) { // } rs = null; } } } if (xlink.isParent()) { psGroupParentToCityObject.setLong(1, cityObjectEntry.getId()); psGroupParentToCityObject.setLong(2, xlink.getGroupId()); psGroupParentToCityObject.addBatch(); if (++parentBatchCounter == resolverManager.getDatabaseAdapter().getMaxBatchSize()) { psGroupParentToCityObject.executeBatch(); parentBatchCounter = 0; } } else { psGroupMemberToCityObject.setLong(1, cityObjectEntry.getId()); psGroupMemberToCityObject.setLong(2, xlink.getGroupId()); psGroupMemberToCityObject.setString(3, xlink.getRole()); psGroupMemberToCityObject.addBatch(); if (++memberBatchCounter == resolverManager.getDatabaseAdapter().getMaxBatchSize()) { psGroupMemberToCityObject.executeBatch(); memberBatchCounter = 0; } } return true; } @Override public void executeBatch() throws SQLException { psGroupMemberToCityObject.executeBatch(); psGroupParentToCityObject.executeBatch(); parentBatchCounter = 0; memberBatchCounter = 0; } @Override public void close() throws SQLException { psGroupMemberToCityObject.close(); psGroupParentToCityObject.close(); psSelectTmp.close(); } @Override public DBXlinkResolverEnum getDBXlinkResolverType() { return DBXlinkResolverEnum.GROUP_TO_CITYOBJECT; } }
virtualcitySYSTEMS/importer-exporter
src/org/citydb/modules/citygml/importer/database/xlink/resolver/XlinkGroupToCityObject.java
Java
lgpl-3.0
5,328
/* Copyright (C) 2009-2011 EPFL (Ecole Polytechnique Fédérale de Lausanne) Michele Tavella <michele.tavella@epfl.ch> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this file. If not, see <http://www.gnu.org/licenses/>. */ #include "IDSerializerRapid.hpp" #include "IDTypes.hpp" #include <tobicore/TCException.hpp> #include <tobicore/TCTools.hpp> #include <tobicore/rapidxml.hpp> #include <tobicore/rapidxml_print.hpp> #include <iostream> #include <stdlib.h> #include <string.h> #include <vector> #include <cmath> #ifdef WIN32 #ifndef NAN static const unsigned long __nan[2] = {0xffffffff, 0x7fffffff}; #define NAN (*(const float *) __nan) #endif #endif #ifdef __BORLANDC__ using namespace std; #endif using namespace rapidxml; IDSerializerRapid::IDSerializerRapid(IDMessage* const message, const bool indent, const bool declaration) : IDSerializer(message) { this->_indent = indent; this->_declaration = declaration; } //----------------------------------------------------------------------------- IDSerializerRapid::~IDSerializerRapid(void) { } //----------------------------------------------------------------------------- std::string* IDSerializerRapid::Serialize(std::string* buffer) { if(buffer == NULL) return NULL; if(IDSerializer::message == NULL) throw TCException("iD message not set, cannot serialize"); buffer->clear(); // XML document and buffers xml_document<> doc; //std::string xml_as_string; //std::string xml_no_indent; // XML declaration if(this->_declaration) { xml_node<>* decl = doc.allocate_node(node_declaration); decl->append_attribute(doc.allocate_attribute("version", "1.0")); decl->append_attribute(doc.allocate_attribute("encoding", "utf-8")); doc.append_node(decl); } char cacheFidx[16], cacheEvent[128], cacheValue[128]; TCTools::itoa(IDSerializer::message->GetBlockIdx(), cacheFidx); TCTools::itoa(IDSerializer::message->GetEvent(), cacheEvent); TCTools::ftoa(IDSerializer::message->GetValue(), cacheValue); IDFvalue fvalue = IDSerializer::message->GetFamily(); std::string timestamp, reference; IDSerializer::message->absolute.Get(&timestamp); IDSerializer::message->relative.Get(&reference); // Root node xml_node<>* root = doc.allocate_node(node_element, IDMESSAGE_ROOTNODE_NEW); root->append_attribute(doc.allocate_attribute(IDMESSAGE_VERSIONNODE, IDMESSAGE_VERSION)); //absolute timestamp root->append_attribute(doc.allocate_attribute(IDMESSAGE_ABSOLUTE_TS, timestamp.c_str())); //relative timestamp root->append_attribute(doc.allocate_attribute(IDMESSAGE_RELATIVE_TS, reference.c_str())); doc.append_node(root); // desc xml_node<>* desc = doc.allocate_node(node_element, IDMESSAGE_DESCRIPTIONNODE, IDSerializer::message->_description.c_str()); root->append_node(desc); //block xml_node<>* block = doc.allocate_node(node_element, IDMESSAGE_BLOCKNODE, cacheFidx); root->append_node(block); //family xml_node<>* family = doc.allocate_node(node_element, IDMESSAGE_FAMILYNODE, fvalue.c_str()); root->append_node(family); //event xml_node<>* event = doc.allocate_node(node_element, IDMESSAGE_EVENTNODE, cacheEvent); root->append_node(event); //absolute timestamp // xml_node<>* abs_ts = doc.allocate_node(node_element, IDMESSAGE_ABSOLUTE_TS, timestamp.c_str()); // root->append_node(abs_ts); // //relative timestamp // xml_node<>* rel_ts = doc.allocate_node(node_element, IDMESSAGE_RELATIVE_TS, reference.c_str()); // root->append_node(rel_ts); #ifdef WIN32 if(!_isnan(message->GetValue())) #else if(!__isnan(message->GetValue())) #endif { xml_node<>* val = doc.allocate_node(node_element, IDMESSAGE_VALUENODE, cacheValue); root->append_node(val); } if(!message->GetSource().empty()) { IDFvalue src_str = message->GetSource().c_str(); xml_node<>* src = doc.allocate_node(node_element, IDMESSAGE_SOURCENODE, src_str.c_str()); root->append_node(src); } // for debugging //rapidxml::print(std::cout, doc, 0); // former attribute based TiD Msg // xml_node<>* root = doc.allocate_node(node_element, IDMESSAGE_ROOTNODE_NEW); // root->append_attribute(doc.allocate_attribute(IDMESSAGE_VERSIONNODE, // IDMESSAGE_VERSION)); // root->append_attribute(doc.allocate_attribute(IDMESSAGE_DESCRIPTIONNODE, // IDSerializer::message->_description.c_str())); // root->append_attribute(doc.allocate_attribute(IDMESSAGE_FRAMENODE_2, // cacheFidx)); // root->append_attribute(doc.allocate_attribute(IDMESSAGE_FAMILYNODE, // fvalue.c_str())); // root->append_attribute(doc.allocate_attribute(IDMESSAGE_EVENTNODE, // cacheEvent)); // root->append_attribute(doc.allocate_attribute(IDMESSAGE_VALUENODE, // cacheValue)); // root->append_attribute(doc.allocate_attribute(IDMESSAGE_TIMESTAMPNODE_2, // timestamp.c_str())); // root->append_attribute(doc.allocate_attribute(IDMESSAGE_REFERENCENODE_2, // reference.c_str())); // if( message->GetSource().length() > 0 ) // { // root->append_attribute(doc.allocate_attribute(IDMESSAGE_SOURCENODE, // message->GetSource().c_str())); // } if(this->_indent) print(std::back_inserter(*buffer), doc); else print(std::back_inserter(*buffer), doc, print_no_indenting); return buffer; } //----------------------------------------------------------------------------- std::string* IDSerializerRapid::Deserialize(std::string* const buffer) { if(buffer == NULL) throw TCException("iD buffer-pointer is NULL", #ifdef _WIN32 __FUNCSIG__ #else __PRETTY_FUNCTION__ #endif ); xml_document<> doc; std::string cache; std::vector<char> xml_copy(buffer->begin(), buffer->end()); xml_copy.push_back('\0'); //doc.parse<parse_declaration_node | parse_no_data_nodes>(&xml_copy[0]); //doc.parse<parse_declaration_node>(&xml_copy[0]); doc.parse<parse_validate_closing_tags>(&xml_copy[0]); xml_node<>* rootnode = doc.first_node(IDMESSAGE_ROOTNODE); if(rootnode == NULL) rootnode = doc.first_node(IDMESSAGE_ROOTNODE_NEW); if(rootnode == NULL) throw TCException("TiD root node not found", #ifdef _WIN32 __FUNCSIG__ #else __PRETTY_FUNCTION__ #endif ); /* Check version */ cache = rootnode->first_attribute(IDMESSAGE_VERSIONNODE)->value(); // old attribute based version if(cache.compare(IDMESSAGE_VERSION_SUPPORTED) == 0 ) { // Get frame number cache.clear(); cache = rootnode->first_attribute(IDMESSAGE_FRAMENODE)->value(); IDSerializer::message->SetBlockIdx(atol(cache.c_str())); // Get timestamp cache.clear(); cache = rootnode->first_attribute(IDMESSAGE_TIMESTAMPNODE)->value(); IDSerializer::message->absolute.Set(cache); cache.clear(); cache = rootnode->first_attribute(IDMESSAGE_REFERENCENODE)->value(); IDSerializer::message->relative.Set(cache); cache = rootnode->first_attribute(IDMESSAGE_DESCRIPTIONNODE)->value(); IDSerializer::message->SetDescription(cache); cache = rootnode->first_attribute(IDMESSAGE_FAMILYNODE)->value(); IDSerializer::message->SetFamily(cache); // if(cache.compare(IDTYPES_FAMILY_BIOSIG) == 0) // IDSerializer::message->SetFamilyType(IDMessage::TxtFamilyBiosig); // else if(cache.compare(IDTYPES_FAMILY_CUSTOM) == 0) // IDSerializer::message->SetFamilyType(IDMessage::TxtFamilyCustom); // else // IDSerializer::message->SetFamilyType(IDMessage::TxtFamilyUndef); cache.clear(); cache = rootnode->first_attribute(IDMESSAGE_EVENTNODE)->value(); IDSerializer::message->SetEvent(atoi(cache.c_str())); return buffer; } //------------------------- // new node based version //------------------------- else if( cache.compare(IDMESSAGE_VERSION) == 0 ) { // for debugging //rapidxml::print(std::cout, doc, 0); //block cache = rootnode->first_node(IDMESSAGE_BLOCKNODE)->value(); IDSerializer::message->SetBlockIdx(atol(cache.c_str())); // Get timestamp cache.clear(); cache = rootnode->first_attribute(IDMESSAGE_ABSOLUTE_TS)->value(); IDSerializer::message->absolute.Set(cache); cache.clear(); cache = rootnode->first_attribute(IDMESSAGE_RELATIVE_TS)->value(); IDSerializer::message->relative.Set(cache); // cache.clear(); // cache = rootnode->first_node(IDMESSAGE_ABSOLUTE_TS)->value(); // IDSerializer::message->absolute.Set(cache); // cache.clear(); // cache = rootnode->first_node(IDMESSAGE_RELATIVE_TS)->value(); // IDSerializer::message->relative.Set(cache); //description cache = rootnode->first_node(IDMESSAGE_DESCRIPTIONNODE)->value(); IDSerializer::message->SetDescription(cache); // familiy cache = rootnode->first_node(IDMESSAGE_FAMILYNODE)->value(); IDSerializer::message->SetFamily(cache); // if(cache.compare(IDTYPES_FAMILY_BIOSIG) == 0) // IDSerializer::message->SetFamilyType(IDMessage::TxtFamilyBiosig); // else if(cache.compare(IDTYPES_FAMILY_CUSTOM) == 0) // IDSerializer::message->SetFamilyType(IDMessage::TxtFamilyCustom); // else // IDSerializer::message->SetFamilyType(IDMessage::TxtFamilyUndef); //event cache.clear(); cache = rootnode->first_node(IDMESSAGE_EVENTNODE)->value(); IDSerializer::message->SetEvent(atoi(cache.c_str())); //value if(rootnode->first_node(IDMESSAGE_VALUENODE)) { cache.clear(); cache = rootnode->first_node(IDMESSAGE_VALUENODE)->value(); IDSerializer::message->SetValue(atof(cache.c_str())); } else IDSerializer::message->SetValue(NAN); //source if(rootnode->first_node(IDMESSAGE_SOURCENODE)) { cache.clear(); cache = rootnode->first_node(IDMESSAGE_SOURCENODE)->value(); IDSerializer::message->SetSource(cache); } else IDSerializer::message->SetSource(""); // former code // cache = rootnode->first_attribute(IDMESSAGE_BLOCKNODE)->value(); // IDSerializer::message->SetBlockIdx(atol(cache.c_str())); // // Get timestamp // cache.clear(); // cache = rootnode->first_attribute(IDMESSAGE_ABSOLUTE_TS)->value(); // IDSerializer::message->absolute.Set(cache); // cache.clear(); // cache = rootnode->first_attribute(IDMESSAGE_RELATIVE_TS)->value(); // IDSerializer::message->relative.Set(cache); // cache = rootnode->first_attribute(IDMESSAGE_DESCRIPTIONNODE)->value(); // IDSerializer::message->SetDescription(cache); // cache = rootnode->first_attribute(IDMESSAGE_FAMILYNODE)->value(); // if(cache.compare(IDTYPES_FAMILY_BIOSIG) == 0) // IDSerializer::message->SetFamilyType(IDMessage::FamilyBiosig); // else if(cache.compare(IDTYPES_FAMILY_CUSTOM) == 0) // IDSerializer::message->SetFamilyType(IDMessage::FamilyCustom); // else // IDSerializer::message->SetFamilyType(IDMessage::FamilyUndef); // cache.clear(); // cache = rootnode->first_attribute(IDMESSAGE_EVENTNODE)->value(); // IDSerializer::message->SetEvent(atoi(cache.c_str())); // cache.clear(); // cache = rootnode->first_attribute(IDMESSAGE_VALUENODE)->value(); // IDSerializer::message->SetValue(atof(cache.c_str())); // if(rootnode->first_attribute(IDMESSAGE_SOURCENODE)) // { // cache.clear(); // cache = rootnode->first_attribute(IDMESSAGE_SOURCENODE)->value(); // IDSerializer::message->SetSource(cache); // } // else // IDSerializer::message->SetSource(""); return buffer; } else { std::string info("iD version mismatch: "); info.append(IDMESSAGE_VERSION); info.append("/"); info.append(cache); throw TCException(info, #ifdef _WIN32 __FUNCSIG__ #else __PRETTY_FUNCTION__ #endif ); } } //-----------------------------------------------------------------------------
tools4BCI/core
src/tobiid/IDSerializerRapid.cpp
C++
lgpl-3.0
14,198
#!/usr/bin/env python3 # coding: utf8 """ Unit tests for module PySetTrie (see settrie.py). Author: Márton Miháltz https://sites.google.com/site/mmihaltz/ """ import unittest from settrie import SetTrie, SetTrieMap, SetTrieMultiMap class TestSetTrie(unittest.TestCase): """ UnitTest for SetTrie class """ def setUp(self): self.t = SetTrie([{1, 3}, {1, 3, 5}, {1, 4}, {1, 2, 4}, {2, 4}, {2, 3, 5}]) def test_print(self): expected = """None 1 2 4# 3# 5# 4# 2 3 5# 4# """ from io import StringIO outp = StringIO() self.t.printtree(stream=outp) self.assertEqual(outp.getvalue(), expected) def test_iter(self): a = [] for s in self.t: a.append(s) self.assertEqual(a, [{1, 2, 4}, {1, 3}, {1, 3, 5}, {1, 4}, {2, 3, 5}, {2, 4}]) def test_iter2(self): it = iter(self.t) for s in it: pass self.assertRaises(StopIteration, it.__next__) def test_iter3(self): t2 = SetTrie() it = iter(t2) self.assertRaises(StopIteration, it.__next__) def test_aslist(self): self.assertEqual(self.t.aslist(), [{1, 2, 4}, {1, 3}, {1, 3, 5}, {1, 4}, {2, 3, 5}, {2, 4}]) def test_str(self): self.assertEqual(str(self.t), "[{1, 2, 4}, {1, 3}, {1, 3, 5}, {1, 4}, {2, 3, 5}, {2, 4}]") def test_contains(self): self.assertTrue(self.t.contains( {1, 3} )) self.assertFalse(self.t.contains( {1} )) self.assertTrue(self.t.contains( {1, 3, 5} )) self.assertFalse(self.t.contains( {1, 3, 5, 7} )) def test_in(self): self.assertTrue({1, 3} in self.t) self.assertFalse({1} in self.t) self.assertTrue({1, 3, 5} in self.t) self.assertFalse({1, 3, 5, 7} in self.t) def test_hassuperset(self): self.assertTrue(self.t.hassuperset({3, 5})) self.assertFalse(self.t.hassuperset({6})) self.assertTrue(self.t.hassuperset({1, 2, 4})) self.assertFalse(self.t.hassuperset({2, 4, 5} )) def test_supersets(self): self.assertEqual(self.t.supersets({3, 5}), [{1, 3, 5}, {2, 3, 5}]) self.assertEqual(self.t.supersets({1, 4}), [{1, 2, 4}, {1, 4}]) self.assertEqual(self.t.supersets({1, 3, 5}), [{1, 3, 5}]) self.assertEqual(self.t.supersets({2}), [{1, 2, 4}, {2, 3, 5}, {2, 4}]) self.assertEqual(self.t.supersets({1}), [{1, 2, 4}, {1, 3}, {1, 3, 5}, {1, 4}]) self.assertEqual(self.t.supersets({1, 2, 5}), []) self.assertEqual(self.t.supersets({1, 2, 4, 5}), []) self.assertEqual(self.t.supersets({6}), []) def test_hassubset(self): self.assertTrue(self.t.hassubset({1, 2, 3})) self.assertTrue(self.t.hassubset({2, 3, 4, 5})) self.assertTrue(self.t.hassubset({1, 4})) self.assertTrue(self.t.hassubset({2, 3, 5})) self.assertFalse(self.t.hassubset({3, 4, 5})) self.assertFalse(self.t.hassubset({6, 7, 8, 9, 1000})) def test_subsets(self): self.assertEqual(self.t.subsets({1, 2, 4, 11}), [{1, 2, 4}, {1, 4}, {2, 4}]) self.assertEqual(self.t.subsets({1, 2, 4}), [{1, 2, 4}, {1, 4}, {2, 4}]) self.assertEqual(self.t.subsets({1, 2}), []) self.assertEqual(self.t.subsets({1, 2, 3, 4, 5}), [{1, 2, 4}, {1, 3}, {1, 3, 5}, {1, 4}, {2, 3, 5}, {2, 4}]) self.assertEqual(self.t.subsets({0, 1, 3, 5}), [{1, 3}, {1, 3, 5}]) self.assertEqual(self.t.subsets({1, 2, 5}), []) self.assertEqual(self.t.subsets({1, 4}), [{1, 4}]) # :) self.assertEqual(self.t.subsets({1, 3, 5}), [{1, 3}, {1, 3, 5}]) self.assertEqual(self.t.subsets({1, 3, 5, 111}), [{1, 3}, {1, 3, 5}]) self.assertEqual(self.t.subsets({1, 4, 8}), [{1, 4}]) self.assertEqual(self.t.subsets({2, 3, 4, 5}), [{2, 3, 5}, {2, 4}]) self.assertEqual(self.t.subsets({2, 3, 5, 6}), [{2, 3, 5}]) class TestSetTrieMap(unittest.TestCase): """ UnitTest for SetTrieMap class """ def setUp(self): self.t = SetTrieMap([({1, 3}, 'A'), ({1, 3, 5}, 'B'), ({1, 4}, 'C'), ({1, 2, 4}, 'D'), ({2, 4}, 'E'), ({2, 3, 5}, 'F')]) #self.t.printtree() def test_print(self): expected = """None 1 2 4: 'D' 3: 'A' 5: 'B' 4: 'C' 2 3 5: 'F' 4: 'E' """ from io import StringIO outp = StringIO() self.t.printtree(stream=outp) self.assertEqual(outp.getvalue(), expected) def test_contains(self): self.assertTrue(self.t.contains( {1, 3} )) self.assertFalse(self.t.contains( {1} )) self.assertTrue(self.t.contains( {1, 3, 5} )) self.assertFalse(self.t.contains( {1, 3, 5, 7} )) def test_in(self): self.assertTrue({1, 3} in self.t) self.assertFalse({1} in self.t) self.assertTrue({1, 3, 5} in self.t) self.assertFalse({1, 3, 5, 7} in self.t) def test_get(self): self.assertEqual(self.t.get({1, 3}), 'A') self.assertEqual(self.t.get({1, 3, 5}), 'B') self.assertEqual(self.t.get({1, 4}), 'C') self.assertEqual(self.t.get({1, 2, 4}), 'D') self.assertEqual(self.t.get({2, 4}), 'E') self.assertEqual(self.t.get({2, 3, 5}), 'F') self.assertEqual(self.t.get({1, 2, 3}), None) self.assertEqual(self.t.get({100, 101, 102}, 0xDEADBEEF), 0xDEADBEEF) self.assertEqual(self.t.get({}), None) def test_assign(self): self.assertEqual(self.t.get({1, 3}), 'A') self.t.assign({1, 3}, 'AAA') self.assertEqual(self.t.get({1, 3}), 'AAA') self.assertEqual(self.t.get({100, 200}), None) self.t.assign({100, 200}, 'FOO') self.assertEqual(self.t.get({100, 200}), 'FOO') self.setUp() def test_hassuperset(self): self.assertTrue(self.t.hassuperset({3, 5})) self.assertFalse(self.t.hassuperset({6})) self.assertTrue(self.t.hassuperset({1, 2, 4})) self.assertFalse(self.t.hassuperset({2, 4, 5} )) def test_supersets(self): self.assertEqual(self.t.supersets({3, 5}), [({1, 3, 5}, 'B'), ({2, 3, 5}, 'F')]) self.assertEqual(self.t.supersets({1}), [({1, 2, 4}, 'D'), ({1, 3}, 'A'), ({1, 3, 5}, 'B'), ({1, 4}, 'C')]) self.assertEqual(self.t.supersets({1, 2, 5}), []) self.assertEqual(self.t.supersets({3, 5}, mode='keys'), [{1, 3, 5}, {2, 3, 5}]) self.assertEqual(self.t.supersets({1}, mode='keys'), [{1, 2, 4}, {1, 3}, {1, 3, 5}, {1, 4}]) self.assertEqual(self.t.supersets({1, 2, 5}, mode='keys'), []) self.assertEqual(self.t.supersets({3, 5}, mode='values'), ['B', 'F']) self.assertEqual(self.t.supersets({1}, mode='values'), ['D', 'A', 'B', 'C']) self.assertEqual(self.t.supersets({1, 2, 5}, mode='values'), []) def test_hassubset(self): self.assertTrue(self.t.hassubset({1, 2, 3})) self.assertTrue(self.t.hassubset({2, 3, 4, 5})) self.assertTrue(self.t.hassubset({1, 4})) self.assertTrue(self.t.hassubset({2, 3, 5})) self.assertFalse(self.t.hassubset({3, 4, 5})) self.assertFalse(self.t.hassubset({6, 7, 8, 9, 1000})) def test_subsets(self): self.assertEqual(self.t.subsets({1, 2, 4, 11}), [({1, 2, 4}, 'D'), ({1, 4}, 'C'), ({2, 4}, 'E')]) self.assertEqual(self.t.subsets({1, 2, 4}), [({1, 2, 4}, 'D'), ({1, 4}, 'C'), ({2, 4}, 'E')]) self.assertEqual(self.t.subsets({1, 2}), []) self.assertEqual(self.t.subsets({1, 2, 3, 4, 5}), [({1, 2, 4}, 'D'), ({1, 3}, 'A'), ({1, 3, 5}, 'B'), ({1, 4}, 'C'), ({2, 3, 5}, 'F'), ({2, 4}, 'E')] ) self.assertEqual(self.t.subsets({0, 1, 3, 5}), [({1, 3}, 'A'), ({1, 3, 5}, 'B')]) self.assertEqual(self.t.subsets({1, 2, 5}), []) self.assertEqual(self.t.subsets({1, 2, 4, 11}, mode='keys'), [{1, 2, 4}, {1, 4}, {2, 4}]) self.assertEqual(self.t.subsets({1, 2, 4}, mode='keys'), [{1, 2, 4}, {1, 4}, {2, 4}]) self.assertEqual(self.t.subsets({1, 2}, mode='keys'), []) self.assertEqual(self.t.subsets({1, 2, 3, 4, 5}, mode='keys'), [{1, 2, 4}, {1, 3}, {1, 3, 5}, {1, 4}, {2, 3, 5}, {2, 4}]) self.assertEqual(self.t.subsets({0, 1, 3, 5}, mode='keys'), [{1, 3}, {1, 3, 5}]) self.assertEqual(self.t.subsets({1, 2, 5}, mode='keys'), []) self.assertEqual(self.t.subsets({1, 2, 4, 11}, mode='values'), ['D', 'C', 'E']) self.assertEqual(self.t.subsets({1, 2, 4}, mode='values'), ['D', 'C', 'E']) self.assertEqual(self.t.subsets({1, 2}, mode='values'), []) self.assertEqual(self.t.subsets({1, 2, 3, 4, 5}, mode='values'), ['D', 'A', 'B', 'C', 'F', 'E']) self.assertEqual(self.t.subsets({0, 1, 3, 5}, mode='values'), ['A', 'B']) self.assertEqual(self.t.subsets({1, 2, 5}, mode='values'), []) self.assertEqual(self.t.subsets({1, 4}), [({1, 4}, 'C')]) self.assertEqual(self.t.subsets({1, 3, 5}), [({1, 3}, 'A'), ({1, 3, 5}, 'B')]) self.assertEqual(self.t.subsets({1, 3, 5, 111}), [({1, 3}, 'A'), ({1, 3, 5}, 'B')]) self.assertEqual(self.t.subsets({1, 4, 8}), [({1, 4}, 'C')]) self.assertEqual(self.t.subsets({2, 3, 4, 5}), [({2, 3, 5}, 'F'), ({2, 4}, 'E')]) self.assertEqual(self.t.subsets({2, 3, 5, 6}), [({2, 3, 5}, 'F')]) def test_iters(self): self.assertEqual(self.t.aslist(), [({1, 2, 4}, 'D'), ({1, 3}, 'A'), ({1, 3, 5}, 'B'), ({1, 4}, 'C'), ({2, 3, 5}, 'F'), ({2, 4}, 'E')] ) self.assertEqual(list(self.t.keys()), [{1, 2, 4}, {1, 3}, {1, 3, 5}, {1, 4}, {2, 3, 5}, {2, 4}] ) self.assertEqual(list(self.t.values()), ['D', 'A', 'B', 'C', 'F', 'E'] ) self.assertEqual(list(self.t.__iter__()), list(self.t.keys())) class TestSetTrieMultiMap(unittest.TestCase): """ UnitTest for SetTrieMultiMap class """ def setUp(self): self.t = SetTrieMultiMap([({1, 3}, 'A'), ({1, 3}, 'AA'), ({1, 3, 5}, 'B'), ({1, 4}, 'C'), ({1, 4}, 'CC'), ({1, 2, 4}, 'D'), ({1, 2, 4}, 'DD'), ({2, 4}, 'E'), ({2, 3, 5}, 'F'), ({2, 3, 5}, 'FF'), ({2, 3, 5}, 'FFF')]) def test_aslist(self): self.assertEqual(self.t.aslist(), [({1, 2, 4}, 'D'), ({1, 2, 4}, 'DD'), ({1, 3}, 'A'), ({1, 3}, 'AA'), ({1, 3, 5}, 'B'), ({1, 4}, 'C'), ({1, 4}, 'CC'), ({2, 3, 5}, 'F'), ({2, 3, 5}, 'FF'), ({2, 3, 5}, 'FFF'), ({2, 4}, 'E')] ) def test_assign_returned_value(self): x = SetTrieMultiMap() self.assertEqual(x.assign({1, 3}, 'A'), 1) self.assertEqual(x.assign({1, 3}, 'AA'), 2) self.assertEqual(x.assign({1, 3}, 'A'), 3) self.assertEqual(x.assign({2, 4, 5}, 'Y'), 1) def test_count(self): self.assertEqual(self.t.count({1, 3}), 2) self.assertEqual(self.t.count({1, 3, 5}), 1) self.assertEqual(self.t.count({1, 3, 4}), 0) self.assertEqual(self.t.count({111, 222}), 0) self.assertEqual(self.t.count({2, 3, 5}), 3) def test_iterget(self): self.assertEqual(list(self.t.iterget({1, 3})), ['A', 'AA']) self.assertEqual(list(self.t.iterget({1, 3, 4})), []) def test_get(self): self.assertEqual(self.t.get({1, 3}), ['A', 'AA']) self.assertEqual(self.t.get({1, 2, 4}), ['D', 'DD']) self.assertEqual(self.t.get({1, 3, 5}), ['B']) self.assertEqual(self.t.get({2, 3, 5}), ['F', 'FF', 'FFF']) self.assertEqual(self.t.get({2, 4}), ['E']) self.assertEqual(self.t.get({1, 3, 4}), None) self.assertEqual(self.t.get({44}, []), []) def test_hassuperset(self): self.assertTrue(self.t.hassuperset({3, 5})) self.assertFalse(self.t.hassuperset({6})) self.assertTrue(self.t.hassuperset({1, 2, 4})) self.assertFalse(self.t.hassuperset({2, 4, 5} )) def test_supersets(self): self.assertEqual(self.t.supersets({3, 5}), [({1, 3, 5}, 'B'), ({2, 3, 5}, 'F'), ({2, 3, 5}, 'FF'), ({2, 3, 5}, 'FFF')]) self.assertEqual(self.t.supersets({3, 5}, mode='values'), ['B', 'F', 'FF', 'FFF']) self.assertEqual(self.t.supersets({3, 5}, mode='keys'), [{1, 3, 5}, {2, 3, 5}]) self.assertEqual(self.t.supersets({1}), [({1, 2, 4}, 'D'), ({1, 2, 4}, 'DD'), ({1, 3}, 'A'), ({1, 3}, 'AA'), ({1, 3, 5}, 'B'), ({1, 4}, 'C'), ({1, 4}, 'CC')] ) self.assertEqual(self.t.supersets({1}, mode='keys'), [{1, 2, 4}, {1, 3}, {1, 3, 5}, {1, 4}]) self.assertEqual(self.t.supersets({1}, mode='values'), ['D', 'DD', 'A', 'AA', 'B', 'C', 'CC']) self.assertEqual(self.t.supersets({1, 2, 5}), []) self.assertEqual(self.t.supersets({1, 2, 5}, mode='keys'), []) self.assertEqual(self.t.supersets({1, 2, 5}, mode='values'), []) def test_hassubset(self): self.assertTrue(self.t.hassubset({1, 2, 3})) self.assertTrue(self.t.hassubset({2, 3, 4, 5})) self.assertTrue(self.t.hassubset({1, 4})) self.assertTrue(self.t.hassubset({2, 3, 5})) self.assertFalse(self.t.hassubset({3, 4, 5})) self.assertFalse(self.t.hassubset({6, 7, 8, 9, 1000})) def test_subsets(self): self.assertEqual(self.t.subsets({1, 2, 4, 11}), [({1, 2, 4}, 'D'), ({1, 2, 4}, 'DD'), ({1, 4}, 'C'), ({1, 4}, 'CC'), ({2, 4}, 'E')] ) self.assertEqual(self.t.subsets({1, 2, 4, 11}, mode='keys'), [{1, 2, 4}, {1, 4}, {2, 4}]) self.assertEqual(self.t.subsets({1, 2, 4, 11}, mode='values'), ['D', 'DD', 'C', 'CC', 'E']) self.assertEqual(self.t.subsets({1, 2, 4}), [({1, 2, 4}, 'D'), ({1, 2, 4}, 'DD'), ({1, 4}, 'C'), ({1, 4}, 'CC'), ({2, 4}, 'E')]) self.assertEqual(self.t.subsets({1, 2, 4}, mode='keys'), [{1, 2, 4}, {1, 4}, {2, 4}]) self.assertEqual(self.t.subsets({1, 2, 4}, mode='values'), ['D', 'DD', 'C', 'CC', 'E']) self.assertEqual(self.t.subsets({1, 2}), []) self.assertEqual(self.t.subsets({1, 2}, mode='keys'), []) self.assertEqual(self.t.subsets({1, 2}, mode='values'), []) self.assertEqual(self.t.subsets({1, 2, 3, 4, 5}), [({1, 2, 4}, 'D'), ({1, 2, 4}, 'DD'), ({1, 3}, 'A'), ({1, 3}, 'AA'), ({1, 3, 5}, 'B'), ({1, 4}, 'C'), ({1, 4}, 'CC'), ({2, 3, 5}, 'F'), ({2, 3, 5}, 'FF'), ({2, 3, 5}, 'FFF'), ({2, 4}, 'E')] ) self.assertEqual(self.t.subsets({1, 2, 3, 4, 5}), self.t.aslist()) self.assertEqual(self.t.subsets({1, 2, 3, 4, 5}, mode='keys'), list(self.t.keys())) self.assertEqual(self.t.subsets({1, 2, 3, 4, 5}, mode='keys'), [{1, 2, 4}, {1, 3}, {1, 3, 5}, {1, 4}, {2, 3, 5}, {2, 4}]) self.assertEqual(self.t.subsets({1, 2, 3, 4, 5}, mode='values'), ['D', 'DD', 'A', 'AA', 'B', 'C', 'CC', 'F', 'FF', 'FFF', 'E']) self.assertEqual(self.t.subsets({1, 2, 3, 4, 5}, mode='values'), list(self.t.values())) self.assertEqual(self.t.subsets({0, 1, 3, 5}), [({1, 3}, 'A'), ({1, 3}, 'AA'), ({1, 3, 5}, 'B')]) self.assertEqual(self.t.subsets({0, 1, 3, 5}, mode='keys'), [{1, 3}, {1, 3, 5}]) self.assertEqual(self.t.subsets({0, 1, 3, 5}, mode='values'), ['A', 'AA', 'B']) self.assertEqual(self.t.subsets({1, 2, 5}), []) self.assertEqual(self.t.subsets({1, 2, 5}, mode='keys'), []) self.assertEqual(self.t.subsets({1, 2, 5}, mode='values'), []) self.assertEqual(self.t.subsets({1, 4}), [({1, 4}, 'C'), ({1, 4}, 'CC')]) self.assertEqual(self.t.subsets({1, 3, 5}), [({1, 3}, 'A'), ({1, 3}, 'AA'), ({1, 3, 5}, 'B')]) self.assertEqual(self.t.subsets({1, 3, 5, 111}), [({1, 3}, 'A'), ({1, 3}, 'AA'), ({1, 3, 5}, 'B')]) self.assertEqual(self.t.subsets({1, 4, 8}), [({1, 4}, 'C'), ({1, 4}, 'CC')]) self.assertEqual(self.t.subsets({2, 3, 4, 5}), [({2, 3, 5}, 'F'), ({2, 3, 5}, 'FF'), ({2, 3, 5}, 'FFF'), ({2, 4}, 'E')]) self.assertEqual(self.t.subsets({2, 3, 5, 6}), [({2, 3, 5}, 'F'), ({2, 3, 5}, 'FF'), ({2, 3, 5}, 'FFF')]) # - - - - - - - # If module is executed from command line, perform tests: if __name__ == "__main__": unittest.main(verbosity=2)
mmihaltz/pysettrie
tests/test_settrie.py
Python
lgpl-3.0
15,405
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.3.1"/> <title>Core3: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Core3 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.3.1 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespaceserver.html">server</a></li><li class="navelem"><a class="el" href="namespaceserver_1_1zone.html">zone</a></li><li class="navelem"><a class="el" href="namespaceserver_1_1zone_1_1objects.html">objects</a></li><li class="navelem"><a class="el" href="namespaceserver_1_1zone_1_1objects_1_1tangible.html">tangible</a></li><li class="navelem"><a class="el" href="namespaceserver_1_1zone_1_1objects_1_1tangible_1_1powerup.html">powerup</a></li><li class="navelem"><a class="el" href="classserver_1_1zone_1_1objects_1_1tangible_1_1powerup_1_1_powerup_object_helper.html">PowerupObjectHelper</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">server::zone::objects::tangible::powerup::PowerupObjectHelper Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="classserver_1_1zone_1_1objects_1_1tangible_1_1powerup_1_1_powerup_object_helper.html">server::zone::objects::tangible::powerup::PowerupObjectHelper</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="classserver_1_1zone_1_1objects_1_1tangible_1_1powerup_1_1_powerup_object_helper.html#aae8da6d68889dfbbf20bfef4823b4bb9">createAdapter</a>(DistributedObjectStub *obj)</td><td class="entry"><a class="el" href="classserver_1_1zone_1_1objects_1_1tangible_1_1powerup_1_1_powerup_object_helper.html">server::zone::objects::tangible::powerup::PowerupObjectHelper</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classserver_1_1zone_1_1objects_1_1tangible_1_1powerup_1_1_powerup_object_helper.html#afe01a1c415d95dc5b724c98e17007cc0">finalizeHelper</a>()</td><td class="entry"><a class="el" href="classserver_1_1zone_1_1objects_1_1tangible_1_1powerup_1_1_powerup_object_helper.html">server::zone::objects::tangible::powerup::PowerupObjectHelper</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classserver_1_1zone_1_1objects_1_1tangible_1_1powerup_1_1_powerup_object_helper.html#a1d6263e57237d3429fd01ecf89730600">instantiateObject</a>()</td><td class="entry"><a class="el" href="classserver_1_1zone_1_1objects_1_1tangible_1_1powerup_1_1_powerup_object_helper.html">server::zone::objects::tangible::powerup::PowerupObjectHelper</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classserver_1_1zone_1_1objects_1_1tangible_1_1powerup_1_1_powerup_object_helper.html#a82ebfc6391a64107ac90da2895f798b7">instantiateServant</a>()</td><td class="entry"><a class="el" href="classserver_1_1zone_1_1objects_1_1tangible_1_1powerup_1_1_powerup_object_helper.html">server::zone::objects::tangible::powerup::PowerupObjectHelper</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classserver_1_1zone_1_1objects_1_1tangible_1_1powerup_1_1_powerup_object_helper.html#af40f059398c3a9e851260b19da851944">PowerupObjectHelper</a>()</td><td class="entry"><a class="el" href="classserver_1_1zone_1_1objects_1_1tangible_1_1powerup_1_1_powerup_object_helper.html">server::zone::objects::tangible::powerup::PowerupObjectHelper</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classserver_1_1zone_1_1objects_1_1tangible_1_1powerup_1_1_powerup_object_helper.html#a66db0d62d8d7312232efa8e08b233418">Singleton&lt; PowerupObjectHelper &gt;</a> class</td><td class="entry"><a class="el" href="classserver_1_1zone_1_1objects_1_1tangible_1_1powerup_1_1_powerup_object_helper.html">server::zone::objects::tangible::powerup::PowerupObjectHelper</a></td><td class="entry"><span class="mlabel">friend</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="classserver_1_1zone_1_1objects_1_1tangible_1_1powerup_1_1_powerup_object_helper.html#a58d80f6c13a3785ad9bd13ffbd5170f0">staticInitializer</a></td><td class="entry"><a class="el" href="classserver_1_1zone_1_1objects_1_1tangible_1_1powerup_1_1_powerup_object_helper.html">server::zone::objects::tangible::powerup::PowerupObjectHelper</a></td><td class="entry"><span class="mlabel">private</span><span class="mlabel">static</span></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Oct 15 2013 17:30:09 for Core3 by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.3.1 </small></address> </body> </html>
kidaa/Awakening-Core3
doc/html/classserver_1_1zone_1_1objects_1_1tangible_1_1powerup_1_1_powerup_object_helper-members.html
HTML
lgpl-3.0
6,261
{% extends "./leanengine_cloudfunction_guide.tmpl" %} {% set platformName = "Python" %} {% set runtimeName = "python" %} {% set gettingStartedName = "python-getting-started" %} {% set productName = "LeanEngine" %} {% set storageName = "LeanStorage" %} {% set leanengine_middleware = "[LeanCloud Python SDK](https://github.com/leancloud/python-sdk)" %} {% set storage_guide_url = "[Python SDK](./leanstorage_guide-python.html)" %} {% set cloud_func_file = "`$PROJECT_DIR/cloud.py`" %} {% set runFuncName = "`leancloud.cloudfunc.run`" %} {% set defineFuncName = "`engine.define`" %} {% set runFuncApiLink = "[leancloud.cloudfunc.run](http://leancloud.readthedocs.io/zh_CN/latest/#leancloud.cloudfunc.run)" %} {% set hook_before_save = "before_save" %} {% set hook_after_save = "after_save" %} {% set hook_before_update = "before_update" %} {% set hook_after_update = "after_update" %} {% set hook_before_delete = "before_delete" %} {% set hook_after_delete = "after_delete" %} {% set hook_on_verified = "on_verified" %} {% set hook_on_login = "on_login" %} {% set hook_message_received = "_messageReceived" %} {% set hook_receiver_offline = "_receiversOffline" %} {% set hook_message_sent = "_messageSent" %} {% set hook_conversation_start = "_conversationStart" %} {% set hook_conversation_started = "_conversationStarted" %} {% set hook_conversation_add = "_conversationAdd" %} {% set hook_conversation_remove = "_conversationRemove" %} {% set hook_conversation_update = "_conversationUpdate" %} {% block initialize %} ## 初始化 定义云函数 / Hook 函数都需要一个 leancloud.Engine 实例,你需要在项目中自己初始化此实例。 ```python # cloud.py import leancloud engine = leancloud.Engine() ``` ```python # wsgi.py import leancloud from app import app from cloud import engine app = engine.wrap(app) ``` 更多关于 **WSGI 函数** 的内容,请参考 [WSGI 接口](http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001432012393132788f71e0edad4676a3f76ac7776f3a16000) 或者 [PEP333](https://www.python.org/dev/peps/pep-0333/)。 {% endblock %} {% block cloudFuncExample %} ```python @engine.define def averageStars(movie, **params): reviews = leancloud.Query(Review).equal_to('movie', movie).find() result = sum(x.get('stars') for x in reviews) return result ``` 客户端 SDK 调用时,云函数的名称默认为 Python 代码中函数的名称。有时需要设置云函数的名称与 Python 代码中的函数名称不相同,可以在 `engine.define` 后面指定云函数名称,比如: ```python @engine.define('averageStars') def my_custom_average_start(movie, **params): pass ``` {% endblock %} {% block cloudFuncParams %} 调用云函数时的参数会直接传递给云函数,因此直接声明这些参数即可。另外调用云函数时可能会根据不同情况传递不同的参数,这时如果定义云函数时没有声明这些参数,会触发 Python 异常,因此建议声明一个额外的关键字参数(关于关键字参数,请参考[此篇文档](http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431752945034eb82ac80a3e64b9bb4929b16eeed1eb9000) 中`关键字参数`一节。)来保存多余的参数。 ```python @engine.define def my_cloud_func(foo, bar, baz, **params): pass ``` 除了调用云函数的参数之外,还可以通过 `engine.current` 对象,来获取到调用此云函数的客户端的其他信息。`engine.current` 对象上的属性包括: - `engine.current.user: leancloud.User`:客户端所关联的用户(根据客户端发送的 LC-Session 头)。 - `engine.current.session_token: str`:客户端发来的 sessionToken(X-LC-Session 头)。 - `engine.current.meta: dict`:有关客户端的更多信息,目前只有一个 remote_address 属性表示客户端的 IP。 {% endblock %} {% block runFuncExample %} 参考[调用云函数](#SDK_调用云函数)一节。 但是这样调用会真的发起一次 HTTP 请求,去请求部署在云引擎上的云函数。如果想要直接调用本地(当前进程)中的云函数,或者发起调用就是在云引擎中,想要省去一次 HTTP 调用的开销,可以使用 `leancloud.cloudfunc.run.local` 来取代 `leanengine.cloudfunc.run`,这样会直接在当前进程中执行一个函数调用,而不会发起 HTTP 请求来调用此云函数。 {% endblock %} {% block beforeSaveExample %} ```python @engine.before_save('Review') # Review 为需要 hook 的 class 的名称 def before_review_save(review): comment = review.get('comment') if not comment: raise leancloud.LeanEngineError(message='No comment!') if len(comment) > 140: review.comment.set('comment', comment[:137] + '...') ``` {% endblock %} {% block afterSaveExample %} ```python import leancloud @engine.after_save('Comment') # Comment 为需要 hook 的 class 的名称 def after_comment_save(comment): post = leancloud.Query('Post').get(comment.id) post.increment('commentCount') try: post.save() except leancloud.LeanCloudError: raise leancloud.LeanEngineError(message='An error occurred while trying to save the Post. ') ``` {% endblock %} {% block afterSaveExample2 %} ```python @engine.after_save('_User') def after_user_save(user): print user user.set('from', 'LeanCloud') try: user.save() except LeanCloudError, e: print 'error:', e ``` {% endblock %} {% block beforeUpdateExample %} ```python @engine.before_update('Review') def before_hook_object_update(obj): # 如果 comment 字段被修改了,检查该字段的长度 assert obj.updated_keys == ['clientValue'] if 'comment' not in obj.updated_keys: # comment 字段没有修改,跳过检查 return if len(obj.get('comment')) > 140: # 拒绝过长的修改 raise leancloud.LeanEngineError(message='comment 长度不得超过 140 个字符') ``` **注意:** 不要修改 `obj`,因为对它的改动并不会保存到数据库,但可以通过抛出一个 `leancloud.LeanEngineError` ,拒绝这次修改。 {% endblock %} {% block afterUpdateExample %} ```python import leancloud @engine.after_update('Article') # Article 为需要 hook 的 class 的名称 def after_article_update(article): print 'article with id {} updated!'.format(article.id) ``` {% endblock %} {% block beforeDeleteExample %} ```python import leancloud @engine.before_delete('Album') # Album 为需要 hook 的 class 的名称 def before_album_delete(album): query = leancloud.Query('Photo') query.equal_to('album', album) try: matched_count = query.count() except leancloud.LeanCloudError: raise engine.LeanEngineError(message='cloud code error') if count > 0: raise engine.LeanEngineError(message='Can\'t delete album if it still has photos.') ``` {% endblock %} {% block afterDeleteExample %} ```python import leancloud @engine.after_delete('Album') # Album 为需要 hook 的 class 的名称 def after_album_delete(album): query = leancloud.Query('Photo') query.equal_to('album', album) try: query.destroy_all() except leancloud.LeanCloudError: raise leancloud.LeanEngineError(message='cloud code error') ``` {% endblock %} {% block onVerifiedExample %} ```python @engine.on_verified('sms') def on_sms_verified(user): print user ``` {% endblock %} {% block onLoginExample %} ```python @engine.on_login def on_login(user): print 'on login:', user if user.get('username') == 'noLogin': # 如果抛出 LeanEngineError,则用户无法登录(收到 401 响应) raise LeanEngineError('Forbidden') # 没有抛出异常,函数正常执行完毕的话,用户可以登录 ``` {% endblock %} {% block errorCodeExample %} 错误响应码允许自定义,但是必须遵守 [HTTP 状态码](https://zh.wikipedia.org/zh-hans/HTTP状态码) 的格式,比如 4xx。云引擎抛出的 `LeanCloudError`(数据存储 API 会抛出此异常)会直接将错误码和原因返回给客户端。若想自定义错误码,可以自行构造 `LeanEngineError`,将 `code` 与 `error` 传入。否则 `code` 为 1, `message` 为错误对象的字符串形式。 ```python @engine.define def error_code(**params): leancloud.User.login('not_this_user', 'xxxxxxx') ``` {% endblock %} {% block errorCodeExample2 %} ```python from leancloud import LeanEngineError @engine.define def custom_error_code(**params): raise LeanEngineError(123, '自定义错误信息') ``` {% endblock %} {% block errorCodeExampleForHooks %} ```python @engine.before_save('Review') # Review 为需要 hook 的 class 的名称 def before_review_save(review): comment = review.get('comment') if not comment: raise leancloud.LeanEngineError( code=123, message='自定义错误信息' ) ``` {% endblock %} {% block cloudFuncRegister %} ### 分离云函数 在实际使用中有这样一种场景:我们将关于 `Post` 类的云函数和关于 `Commit` 类的云函数分离成两个文件,方便管理。 ```Python # Post.py import leancloud post_engine = leancloud.Engine() @post_engine.define def post_func(): pass ``` ```Python # Commit.py import leancloud commit_engine = leancloud.Engine() @commit_engine.define def commit_func(): pass ``` 然后,我们就可以统一在 `cloud.py` 下对两个文件进行合并管理。 ```Python # cloud.py import leancloud from Post import post_engine from Commit import commit_engine engine = leancloud.Engine() # 将 CommitEngine 和 PostEngine 的云函数同步到 engine 中 engine.register(post_engine) engine.register(commit_engine) ``` 其效果等同于在 `cloud.py` 中注册 `commit_func` 和 `post_func` 两个云函数。 在使用 `engine.register` 函数过程中,请务必不要注册相同的函数名称。 {% endblock %} {% block hookDeadLoop %} #### 防止死循环调用 在实际使用中有这样一种场景:在 `Post` 类的 `{{hook_after_update}}` Hook 函数中,对传入的 `Post` 对象做了修改并且保存,而这个保存动作又会再次触发 `{{hook_after_update}}`,由此形成死循环。针对这种情况,我们为所有 Hook 函数传入的 `leancloud.Object` 对象做了处理,以阻止死循环调用的产生。 不过请注意,以下情况还需要开发者自行处理: - 对传入的 `leancloud.Object` 对象进行 `fetch` 操作。 - 重新构造传入的 `leancloud.Object` 对象,如使用 `leancloud.Object.create_without_data()` 方法。 对于使用上述方式产生的对象,请根据需要自行调用以下 API: - `leancloud.Object.disable_before_hook()` 或 - `leancloud.Object.disable_after_hook()` 这样,对象的保存或删除动作就不会再次触发相关的 Hook 函数。 ```python @engine.after_update('Post') def after_post_update(post): # 直接修改并保存对象不会再次触发 after update hook 函数 post.set('foo', 'bar') post.save() # 如果有 fetch 操作,则需要在新获得的对象上调用相关的 disable 方法 # 来确保不会再次触发 Hook 函数 post.fetch() post.disable_after_hook() post.set('foo', 'bar') # 如果是其他方式构建对象,则需要在新构建的对象上调用相关的 disable 方法 # 来确保不会再次触发 Hook 函数 post = leancloud.Object.extend('Post').create_without_data(post.id) post.disable_after_hook() post.save() ``` {% endblock %} {% block code_hook_message_received %} ```python @engine.define def _messageReceived(**params): # params = { # 'fromPeer': 'Tom', # 'receipt': false, # 'groupId': null, # 'system': null, # 'content': '{"_lctext":"耗子,起床!","_lctype":-1}', # 'convId': '5789a33a1b8694ad267d8040', # 'toPeers': ['Jerry'], # '__sign': '1472200796787,a0e99be208c6bce92d516c10ff3f598de8f650b9', # 'bin': false, # 'transient': false, # 'sourceIP': '121.239.62.103', # 'timestamp': 1472200796764, # } print('_messageReceived start') content = json.loads(params['content']) text = content._lctext print('text:', text) processed_content = text.replace('XX中介', '**') print('_messageReceived end') # 必须含有以下语句给服务端一个正确的返回,否则会引起异常 return { 'content': processed_content, } ``` {% endblock %} {% block code_hook_receiver_offline %} ```python @engine.define def _receiversOffline(**params): print('_receiversOffline start') # params['content'] 为消息内容 content = params['content'] short_content = content[:6] print('short_content:', short_content) payloads = { # 自增未读消息的数目,不想自增就设为数字 'badge': 'Increment', 'sound': 'default', # 使用开发证书 '_profile': 'dev', 'alert': short_content, } print('_receiversOffline end') return { 'pushMessage': json.dumps(payloads), } ``` {% endblock %} {% block code_hook_message_sent %} ```python @engine.define def _messageSent(**params): print('_messageSent start') print('params:', params) print('_messageSent end') return {} # 在云引擎中打印的日志如下: # _messageSent start # params: {'__sign': '1472703266575,30e1c9b325410f96c804f737035a0f6a2d86d711', # 'bin': False, # 'content': '12345678', # 'convId': '5789a33a1b8694ad267d8040', # 'fromPeer': 'Tom', # 'msgId': 'fptKnuYYQMGdiSt_Zs7zDA', # 'offlinePeers': ['Jerry'], # 'onlinePeers': [], # 'receipt': False, # 'sourceIP': '114.219.127.186', # 'timestamp': 1472703266522, # 'transient': False} # _messageSent end ``` {% endblock %} {% block code_hook_conversation_start %} ```python @engine.define def _conversationStart(**params): print('_conversationStart start') print('params:', params) print('_conversationStart end') return {} # 在云引擎中打印的日志如下: # _conversationStart start # params: {'__sign': '1472703266397,b57285517a95028f8b7c34c68f419847a049ef26', # 'attr': {'name': 'Tom & Jerry'}, # 'initBy': 'Tom', # 'members': ['Tom', 'Jerry']} # _conversationStart end ``` {% endblock %} {% block code_hook_conversation_started %} ```python @engine.define def _conversationStarted(**params): print('_conversationStarted start') print('params:', params) print('_conversationStarted end') return {} # 在云引擎中打印的日志如下: # _conversationStarted start # params: {'__sign': '1472723167361,f5ceedde159408002fc4edb96b72aafa14bc60bb', # 'convId': '5789a33a1b8694ad267d8040'} # _conversationStarted end ``` {% endblock %} {% block code_hook_conversation_add %} ```python @engine.define def _conversationAdd(**params): print('_conversationAdd start') print('params:', params) print('_conversationAdd end') return {} 在云引擎中打印的日志如下: # _conversationAdd start # params: {'__sign': '1472786231813,a262494c252e82cb7a342a3c62c6d15fffbed5a0', # 'convId': '5789a33a1b8694ad267d8040', # 'initBy': 'Tom', # 'members': ['Mary']} # _conversationAdd end ``` {% endblock %} {% block code_hook_conversation_remove %} ```python @engine.define def _conversationRemove(**params): print('_conversationRemove start') print('params:', params) print('removed client Id:', params['members'][0]); print('_conversationRemove end') return {} # 在云引擎中打印的日志如下: # _conversationRemove start # params: {'__sign': '1472787372605,abdf92b1c2fc4c9820bc02304f192dab6473cd38', # 'convId': '57c8f3ac92509726c3dadaba', # 'initBy': 'Tom', # 'members': ['Jerry']} # removed client Id: Jerry # _conversationRemove end ``` {% endblock %} {% block code_hook_conversation_update %} ```python @engine.define def _conversationUpdate(**params): print('_conversationUpdate start') print('params:', params) print('name:', params['attr']['name']) print('_conversationUpdate end') return {} # 在云引擎中打印的日志如下: # _conversationUpdate start # params: {'__sign': '1472787372605,abdf92b1c2fc4c9820bc02304f192dab6473cd38', # 'convId': '57c8f3ac92509726c3dadaba', # 'initBy': 'Tom', # 'members': ['Jerry']} # name: 聪明的喵星人 # _conversationUpdate end ``` {% endblock %} {% block useMasterKey %} ```python // 通常位于 wsgi.py leancloud.use_master_key(True) ``` {% endblock %} {% block cloudFuncTimeout %} ### 云函数超时 云函数超时时间为 15 秒,如果超过阈值,SDK 将强制向客户端返回 HTTP status code 为 503 的响应,body 为 `The request timed out on the server.`。 #### 超时的处理方案 我们建议将代码中的任务转化为异步队列处理,以优化运行时间,避免云函数或定时任务发生超时。 Python 运行环境使用了 gevent 作为 event loop,所以你可以根据情况自己 gevent.spawn 一个 Greenlet 来处理异步逻辑。例如: ```python def handle(req): data = do_some_stuff() @gevent.spawn def stuff_should_be_executed_asynchronously(): resp = requests.get('http://time.consuming.api.com/foo', data=data) do_more_stuff(resp.json) return # 上面的函数会异步地执行,这里会直接返回 ``` {% endblock %}
sdjcw/leancloud-docs
views/leanengine_cloudfunction_guide-python.md
Markdown
lgpl-3.0
17,483
#include "OutOfProcessClipboard.h" #include <QtCore/QFile> #include <QtDebug> OutOfProcessClipboard::OutOfProcessClipboard(QObject* parent) : QObject(parent) { } void OutOfProcessClipboard::setText(const QString& text) { QFile tempFile("/tmp/qt-widget-inspector-clipboard"); tempFile.open(QIODevice::WriteOnly | QIODevice::Truncate); tempFile.write(text.toUtf8()); tempFile.close(); // start the xclip utility detached so that it is not an inferior // of the current process and hence will not be interrupted by gdb // if the user interrupts the current process if (!QProcess::startDetached("xclip",QStringList() << tempFile.fileName() << "-i" << "-selection" << "clipboard")) { emit error("There was a problem copying text with 'xclip', please check that it is installed."); } }
robertknight/Qt-Inspector
OutOfProcessClipboard.cpp
C++
lgpl-3.0
798
VoidTeleport ============== Void Teleport plugin for Bukkit.
HIKARU0721/VoidTeleport
README.md
Markdown
lgpl-3.0
64
/** * Copyright 2013 Mark Browning * Licensed under the LGPL 3.0 or later (See LICENSE.md for details) */ package com.mtbs3d.minecrift.provider; import java.io.File; import com.mtbs3d.minecrift.api.IEyePositionProvider; import com.mtbs3d.minecrift.api.PluginType; import de.fruitfly.ovr.enums.EyeType; import com.mtbs3d.minecrift.api.BasePlugin; import net.minecraft.client.Minecraft; import net.minecraft.util.Vec3; /** * "None" head position plugin * @author mabrowning * */ public class NullEyePosition extends BasePlugin implements IEyePositionProvider { private Vec3 headPos; private Vec3 leftEyePos; private Vec3 rightEyePos; @Override public String getID() { return "null-pos"; } @Override public String getName() { return "Neck Model"; } @Override public String getInitializationStatus() { return ""; } @Override public String getVersion() { return "1.0"; } @Override public boolean init(File nativeDir) { return true; } @Override public boolean init() { return true; } @Override public boolean isInitialized() { return true; } @Override public void poll(float delta) { } @Override public void destroy() { } @Override public boolean isCalibrated(PluginType type) { return true; } @Override public void beginCalibration(PluginType type) {} @Override public void updateCalibration(PluginType type) {} @Override public String getCalibrationStep(PluginType type) { return ""; } //Basic neck model: @Override public void update(float ipd, float yawHeadDegrees, float pitchHeadDegrees, float rollHeadDegrees, float worldYawOffsetDegrees, float worldPitchOffsetDegrees, float worldRollOffsetDegrees) { float cameraYaw = (worldYawOffsetDegrees + yawHeadDegrees ) % 360; headPos = new Vec3(0, Minecraft.getMinecraft().vrSettings.neckBaseToEyeHeight, -Minecraft.getMinecraft().vrSettings.eyeProtrusion); headPos.rotateAroundZ( rollHeadDegrees * PIOVER180 ); headPos.rotateAroundX( pitchHeadDegrees * PIOVER180 ); headPos.rotateAroundY( -cameraYaw * PIOVER180 ); leftEyePos = new Vec3(headPos.xCoord, headPos.yCoord, headPos.zCoord); leftEyePos.xCoord -= (ipd / 2f); rightEyePos = new Vec3(headPos.xCoord, headPos.yCoord, headPos.zCoord); rightEyePos.xCoord += (ipd / 2f); } @Override public Vec3 getCenterEyePosition() { return headPos; } @Override public Vec3 getEyePosition(EyeType eye) { if (eye == EyeType.ovrEye_Left) return leftEyePos; else return rightEyePos; } @Override public void resetOrigin() { } @Override public void setPrediction(float delta, boolean enable) { } @Override public void resetOriginRotation() { } @Override public void eventNotification(int eventId) { } public void beginFrame() { beginFrame(0); } public void beginFrame(int frameIndex) { polledThisFrame = false; } public void endFrame() { } }
Zackgetu/zack
src/com/mtbs3d/minecrift/provider/NullEyePosition.java
Java
lgpl-3.0
3,016
#ifndef _L3D_H #define _L3D_H #include "application.h" #include "neopixel.h" #define PIXEL_COUNT 512 #define PIXEL_PIN D0 #define PIXEL_TYPE WS2812B #define INTERNET_BUTTON D2 #define MODE D3 #define STREAMING_PORT 2222 /** An RGB color. */ struct Color { unsigned char red, green, blue; Color(int r, int g, int b) : red(r), green(g), blue(b) {} Color() : red(0), green(0), blue(0) {} }; /** A point in 3D space. */ struct Point { float x; float y; float z; Point() : x(0), y(0), z(0) {} Point(float _x, float _y, float _z) : x(_x), y(_y), z(_z) {} }; /** An L3D LED cube. Provides methods for drawing in 3D. Controls the LED hardware. */ class Cube { private: int maxBrightness; bool onlinePressed; bool lastOnline; Adafruit_NeoPixel strip; UDP udp; int lastUpdated; char localIP[24]; char macAddress[20]; int port; void emptyFlatCircle(int x, int y, int z, int r, Color col); public: int size; Cube(unsigned int s, unsigned int mb); Cube(void); void setVoxel(int x, int y, int z, Color col); void setVoxel(Point p, Color col); Color getVoxel(int x, int y, int z); Color getVoxel(Point p); void line(int x1, int y1, int z1, int x2, int y2, int z2, Color col); void line(Point p1, Point p2, Color col); void sphere(int x, int y, int z, int r, Color col); void sphere(Point p, int r, Color col); void shell(float x, float y, float z, float r, Color col); void shell(float x, float y, float z, float r, float thickness, Color col); void shell(Point p, float r, Color col); void shell(Point p, float r, float thickness, Color col); void background(Color col); Color colorMap(float val, float min, float max); Color lerpColor(Color a, Color b, int val, int min, int max); void begin(void); void show(void); void listen(void); void initButtons(void); void onlineOfflineSwitch(void); void joinWifi(void); void updateNetworkInfo(void); int setPort(String port); }; // common colors const Color black = Color(0x00, 0x00, 0x00); const Color grey = Color(0x92, 0x95, 0x91); const Color yellow = Color(0xff, 0xff, 0x14); const Color magenta = Color(0xc2, 0x00, 0x78); const Color orange = Color(0xf9, 0x73, 0x06); const Color teal = Color(0x02, 0x93, 0x86); const Color red = Color(0xe5, 0x00, 0x00); const Color brown = Color(0x65, 0x37, 0x00); const Color pink = Color(0xff, 0x81, 0xc0); const Color blue = Color(0x03, 0x43, 0xdf); const Color green = Color(0x15, 0xb0, 0x1a); const Color purple = Color(0x7e, 0x1e, 0x9c); const Color white = Color(0xff, 0xff, 0xff); #endif
enjrolas/beta-cube-library
firmware/beta-cube-library.h
C
lgpl-3.0
2,711
/******************************************************************************* * Copyright (c) 2004-2009, Jean-Marc François. All Rights Reserved. * Originally licensed under the New BSD license. See the LICENSE_OLD file. * Copyright (c) 2013, Timo Klerx. All Rights Reserved. * Now licensed under LGPL. See the LICENSE file. * This file is part of jhmmt. * * jhmmt is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jhmmt is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with jhmmt. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package be.ac.ulg.montefiore.run.jahmm.apps.cli; import java.io.*; import java.util.EnumSet; import be.ac.ulg.montefiore.run.jahmm.*; import be.ac.ulg.montefiore.run.jahmm.apps.cli.CommandLineArguments.Arguments; import be.ac.ulg.montefiore.run.jahmm.io.*; import be.ac.ulg.montefiore.run.jahmm.toolbox.KullbackLeiblerDistanceCalculator; /** * This class implements an action that computes the Kullback-Leibler * distance between two HMMs. */ public class KLActionHandler extends ActionHandler { public void act() throws FileNotFoundException, IOException, FileFormatException, AbnormalTerminationException { EnumSet<Arguments> args = EnumSet.of( Arguments.OPDF, Arguments.IN_HMM, Arguments.IN_KL_HMM); CommandLineArguments.checkArgs(args); InputStream st = Arguments.IN_KL_HMM.getAsInputStream(); Reader reader1 = new InputStreamReader(st); st = Arguments.IN_HMM.getAsInputStream(); Reader reader2 = new InputStreamReader(st); distance(Types.relatedObjs(), reader1, reader2); } private <O extends Observation & CentroidFactory<O>> void distance(RelatedObjs<O> relatedObjs, Reader reader1, Reader reader2) throws IOException, FileFormatException { Hmm<O> hmm1 = HmmReader.read(reader1, relatedObjs.opdfReader()); Hmm<O> hmm2 = HmmReader.read(reader2, relatedObjs.opdfReader()); KullbackLeiblerDistanceCalculator kl = new KullbackLeiblerDistanceCalculator(); System.out.println(kl.distance(hmm1, hmm2)); } }
TKlerx/jhmmt
src/main/java/be/ac/ulg/montefiore/run/jahmm/apps/cli/KLActionHandler.java
Java
lgpl-3.0
2,637